Method
function
in class, struct and enum.
func msg(name: String, age: Int) -> String {
return ("\(name) \(age)")
}
let message = msg(name: "Ian", age: 3)
print(message)
func add(x: Int, y: Int) -> Int {
return (x + y)
}
let addNumber = add(x:3, y:7)
print(addNumber)
}
External Parameter and Internal Parameter
func add(first: x: Int, second y: Int) {
return (x + y) // return(first + second) error
}
add(first: 10, second: 20) // add(x: 10, y: 20) error
first and second
are external Parameter and x and y
are Internal Parameter
func add1(x: Int, y: Int) -> Int {
return (x + y)
}
let x1 = add1(x: 3, y: 9)
print(x1)
func add2(first x: Int, second y: Int) -> Int {
return (x + y)
}
let x2 = add2(first: 10, second: 20)
print(x2)
func add3(_ x: Int, _ y: Int) -> Int {
return (x + y)
}
let x3 = add3(20, 30)
print(x3)
func add4(_ x: Int, with y: Int) -> Int {
return (x + y)
}
let x4 = add4(10, with: 20)
print(x4)
print(type(of: x1)) // Int
print(type(of: add1)) // (Int, Int) -> Int
Return multiple results
func converter(length: Float) -> (yards: Float, centimeters: Float, meters: Float) {
let yards = length * 0.0277778
let centimeters = length * 2.54
let meters = length * 0.0254
return (yards, centimeters, meters)
}
var theLength = converter(length:20)
print(theLength.yards)
print(theLength.centimeters)
print(theLength.meters)