欢迎加QQ群讨论:157672725
函数
1.使用func来声明一个函数,使用名字和参数来调用函数,使用->来指定函数返回值的类型
func hello(name: String,msg: String) -> String {
return "Hello \(name),\(msg)."
}
print(hello("CatchZeng","are you ok?"))
输出:Hello CatchZeng,are you ok?
2.使用元组来让一个函数返回多个值。该元组的元素可以用名称或数字来表示
func calculateStatistics(scores: [Int]) -> (min: Int,max: Int,sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min,max,sum)
}
let statistics = calculateStatistics([5,3,100,9])
print(statistics.sum)
print("\n")
print(statistics.2)//等价于sum
输出:
120
120
3.函数可以带有可变个数的参数,这些参数在函数内表现为数组的形式
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
print(sumOf())
print("\n")
print(sumOf(100,0,1))
输出:
0
101
func fucTest() -> Int {
var i = 0
func add() {
i += 1
}
add()
return i
}
print(fucTest())
输出:1
func fucTest() -> (Int -> Int) {
func add(number: Int) -> Int {
return 1 + number
}
return add
}
var test = fucTest()
print(test(1))
输出:2
func hasAnyMatches(list: [Int],condition: Int -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20,19,7,12]
print(hasAnyMatches(numbers,lessThanTen))
输出:true
@H_301_261@ 原文链接:https://www.f2er.com/swift/326057.html