1.语法:
func 函数名(参数)->返回值{}
func funcname(Parameters) -> returntype { Statement1 Statement2 --- Statement N return parameters }函数没有参数的情况。例如:
func sayHelloWorld() -> String { return "hello,world" } print(sayHelloWorld()) // Prints "hello,world"
函数也可以有多个参数,参数之间用逗号隔开:
func greet(person: String,alreadyGreeted: Bool) -> String { if alreadyGreeted { return greetAgain(person: person) } else { return greet(person: person) } } print(greet(person: "Tim",alreadyGreeted: true)) // Prints "Hello again,Tim!"
函数没有返回值的情况:
func greet(person: String) { print("Hello,\(person)!") } greet(person: "Dave") // Prints "Hello,Dave!"
多个返回值的情况:
func minMax(array: [Int]) -> (min: Int,max: Int) { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin,currentMax) }原文链接:https://www.f2er.com/swift/323307.html