Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
jon kelson
5,149 PointsHi what's the difference between functions and methods in terms of where they are positioned?
Hi what's the difference between functions and methods in swift in terms of where they are positioned?
1 Answer
Michael Hulet
47,913 PointsA function is declared at the global scope and can run without making an instance of a class, struct, or enum, but a method is declared on a class, struct, or enum and you have to instantiate one before you can use it. For example:
// This is a function
func add(left: Int, right: Int) -> Int{
return left + right
}
//It can be called like this
add(left: 5, right: 10) // returns 15
struct Number{
let value: Int
//This is a method
func add(other: Int) -> Number{
return Number(value: self.value + other)
}
//Inits are also methods
init(value: Int){
self.value = value
}
}
//They can be called like this
let first = Number(value: 5)
let result = first.add(other: 10)
result.value // is 15
jon kelson
5,149 Pointsjon kelson
5,149 PointsThank you Michael very much . I understand those now . Just one last quick question if that's ok . Q. , so why don't we just use one or the other , methods or functions . Is there advantages one over the other . Thanks
Michael Hulet
47,913 PointsMichael Hulet
47,913 PointsThat's quite an argument that really depends on who you ask (functional vs. object-oriented paradigms). Apple's frameworks are designed to be object-oriented, and really wants you to favor methods over functions, and that's what Treehouse teaches
jon kelson
5,149 Pointsjon kelson
5,149 PointsOk so I guess you can use either , either inside your class etc or outside they do the same thing , but preferrably use methods . Many thanks for a great answer Michael ?