Swift Functions
Functions (with inputs)
func MyFunction(m: String, n: Int){
print(m)
}
MyFunction(m: "Hello")
>> HelloFunction output
func MyFunction() -> Int{
return 123
}
// The type after the -> indicates the type of data that function will outputFunction labels
Three ways to label parameters: no label, word label, or underscore label.
// No Labels
func DoAdd(a:Int, b:Int) -> Int{
var sum = 5 + 7
return sum
}
DoAdd(a:5, b:7)
// With word labels
func DoAdd(firstNum a:Int, secNum b:Int) -> Int{
var sum = 5 + 7
return sum
}
DoAdd(firstNum:5, secNum:7)
// With underscore labels
func DoAdd(_ a:Int,_ b:Int) -> Int{
var sum = 5 + 7
return sum
}
DoAdd(5,7)Function signatures
The function signature is the combination of function name and parameter labels (not just the name). So these two are different signatures even though both are named DoAdd:
// ONE
func DoAdd(a:Int, b:Int) -> Int{
var sum = 5 + 7
return sum
}
DoAdd(a:5, b:7)
// TWO
func DoAdd(_ a:5, _ b:7) -> Int{
var sum = 5 + 7
return sum
}
DoAdd(5,7)See next
- Swift-Structures — functions live inside structures as methods