Swift 学习第一节
@(Swift 深入学习小记)
- if 语句缺省值的使用。
var str: String? = "string"
if let s = str {
print("print \(s)")
}
- switch 支持任意类型的数据以及各种比较操作(不仅仅是整数)
let str = "red pepper"
switch str {
case "celery":
print("add some raisins and make ants on a log.")
case let x where x.hasSuffix("pepper"):
print("It is a spicy \(x)")
}
- for 循环来遍历字典
let dic = ["name":"chuck", "age":"10", "nickname":"zhangsan"]
for (kind, numbers) in dic {
for number in numbers {
if number == "10" {
print("is age number == 10")
}
}
}
- while 知道代码满足条件
var n = 2
while n < 100 {
n = n * 2
}
print(n)
var m = 2
repeat {
m = m * 2
} while m < 100
print(m)
-
函数与闭包
- 函数可以用元祖来当返回值
func array(arr: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = arr[0]
var max = arr[0]
var sum = 0
for a in arr {
if a > max {
max = a
} else if a < min {
min = a
}
sum += a
}
return (min, max, sum)
}
- 函数可以带可变参数
func sum(numbers: Int...) -> Int {
var sum = 0
for num in numbers {
sum += num
}
return sum
}
- 函数还可以嵌套
- 函数也可以当另一个函数的参数传入
- 闭包
// 闭包可以直接使用,在确定的情况下,可以省略参数和返回值类型
let numbers = [1,0,2,3,4]
let sum = numbers.map({ (num:Int) -> Int in
let resutl = 3 * num
return resutl
})
let sum = numbers.map({number in number * 3})
// 在最后一个参数是一个闭包的时候,可以直接用花括号取消小括号
let sor = numbers.sorted {$0 > $1}
- Switch 支持 Where 进一步条件判断(还可以添加复合分支)
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
// 打印 "(1, -1) is on the line x == -y"
-
fallthrough 可以用来贯穿switch
-
泛型
- 泛型函数
- 泛型类型
网友评论