Swift第一天学习
override func viewDidLoad() {
super.viewDidLoad()
// 1.
print(sumof(1,2,3,4,5,6,7,8,9,10))
// 2.show it
showLabel.text = String(sumof(1,2,3,4,5,6,7,8,9,10))
// 3.函数嵌套
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y + sumof(1,2,3,4,5,6)
}
print(returnFifteen())
// 4.
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
let increment = makeIncrementer()
print(increment(7))
// 5.一个函数可以使用另一个函数当参数
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
}
let numbers = [20,34,56,2]
hasAnyMatches(numbers, condition: lessThanTen)
print("\(hasAnyMatches(numbers, condition: lessThanTen)) is")
// ({})匿名闭包
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
// 判断是不是奇数
print(jishu(9))
}
func jishu(number: Int) -> Bool {
if number % 2 != 0 {
return false
}
return true
}
func sumof(numbers:Int...) ->Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}