swift从入门到放弃-基本语法(2)


  • 基本语法
    • 字符串
    • 元组
    • 高阶方法
字符串

swift3.0中提供了如下两个格式化字符串的方法

String(format: <#T##String#>, <#T##arguments: CVarArg...##CVarArg#>)

String(format: <#T##String#>, arguments: <#T##[CVarArg]#>)

元组

元组(tuples)把多个值组合成一个复合值。元组内的值可以是任意类型,并不要求是相同类型。

let http404Error = (404,"not found")
let (statusCode, statusMessage) = http404Error
print(statusCode)                       //404
print(statusMessage)                    //not found
print(http404Error.0)                   //404
print(http404Error.1)                   //not found

也可以在定义元组的时候给单个元素命名

let http200Error = (stautsCode:200,describe:"ok")
print(http200Error.stautsCode)          //200
print(http200Error.describe)            //ok

高阶方法

Swift 标准库提供了名为 sorted(by:) 的方法,它会根据你所提供的用于排序的闭包函数将已知类型数组中的值进行排序.

用数组names调用方法,传入一个自定义闭包,实现排序的目的

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let result = names.sorted { (numb1, numb2) -> Bool in
    numb1 < numb2
}
print(result)   //["Alex", "Barry", "Chris", "Daniella", "Ewa"]

逆天级的运算符方法,不知道看到下面这种表达方式的你有没有想哭呢

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
result = names.sorted(by: <)
print(result)   //["Alex", "Barry", "Chris", "Daniella", "Ewa"]

上一篇swift初步接触

你可能感兴趣的:(swift从入门到放弃-基本语法(2))