您的位置:首页 > 移动开发 > Swift

Swift笔记:函数

2016-04-15 10:28 399 查看
函数

//声明函数
func sayhello(person:String) -> String {
let  str = "hello," + person

return str
}

//调用函数
print(sayhello("locay"))

//hello,locay


以 func 作为前缀。 ->(一个连字符后跟一个右尖括号)后跟返回类型的名称的方式来表示函数返回值。函数名后面()为函数参数。

无参函数(Functions Without Parameters)

func sayHelloWorld() -> String {
return "hello, world"
}
print(sayHelloWorld())
// prints "hello, world"


多参数函数 (Functions With Multiple Parameters)

func sayHello(personName: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return sayHelloAgain(personName)
} else {
return sayHello(personName)
}
}
print(sayHello("Tim", alreadyGreeted: true))
// prints "Hello again, Tim!"


无返回值函数(Functions Without Return Values)

func sayGoodbye(personName: String) {
print("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"


多重返回值函数(Functions with Multiple Return Values)

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)
}


函数类型(Function Types)

每个函数都有种特定的函数类型,由函数的参数类型和返回类型组成。

func addTwoInts(a: Int, _ b: Int) -> Int {
return a + b
}
func multiplyTwoInts(a: Int, _ b: Int) -> Int {
return a * b
}


这两个函数的类型是 (Int, Int) -> Int,可以解读为“这个函数类型有两个 Int 型的参数并返回一个 Int 型的值。”。

func printHelloWorld() {
print("hello, world")
}


这个函数的类型是:() -> Void,或者叫“没有参数,并返回 Void 类型的函数”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数 swift