Swift常用技巧

学习资料来源Swift 图书展示项目开发实战,阅读了一些其它文章,案例还是讲的通熟易懂,记录一下,方便后期回忆。

泛型

Swift学习之泛型

var num1 = "123", num2 = "str:"
func swapValue(_ num1:inout T, _ num2:inout T){
    (num1,num2) = (num2,num1)
}

swapValue(&num1, &num2)
num1
num2

守卫

Swift的Guard语句

func checkup(person:[String:String]){
    guard let id = person["id"] else {
        print ("没有身份证不许进考场")
        return
    }
    
    guard let examNumber = person["examNumber"] else {
        print ("没有准考证,不许进考场")
        return
    }
    
    print ("身份证号\(id),准考证\(examNumber)")
    
}

//checkup(person: ["id":"111","examNumber":"222"])
checkup(person: ["id":"111"])

属性观察

Swift - 属性观察器 Property Observer

let MaxValue = 999
let Minvalue = -999
var number:Int = 0 {
willSet {
    print ("将从\(number)变成\(newValue)")
    
}
didSet{
    if number > MaxValue {
        number = MaxValue
    } else if number < Minvalue {
        number = Minvalue
    }
    print ("已经从\(oldValue)变为\(number)")
}
}

number = 1000
number

扩展

iOS学习笔记46-Swift(六)扩展

extension Int {
    func times(closure : (()->())?){
        if self >= 0 {
            for _ in 0..

协议扩展

extension CustomStringConvertible {
    var upperdescription:String {
        return self.description.uppercased()
    }
}
["key":"value"].description
["key":"value"].upperdescription

你可能感兴趣的:(Swift常用技巧)