swift(二)

来源:互联网 发布:歌曲软件下载大全 编辑:程序博客网 时间:2024/06/05 18:26

记录下  今天学的东西。。看到闭包了。。看不下去了。。


   let strValue1:String? = "abcd"//声明了一个Optional类型值,可能包含一个String值,也可能什么都不包含 等同于    var strValue1: Optional<String>

        let hasValue = strValue1?.characters.count

        print("hasValue:\(hasValue)")//声明一个可选类型


        

        let strValue2:String! = "def"//隐式拆包

        let hasValue2 = strValue2.characters.count

        print("hasValue:\(hasValue2)")

      //使用强制拆包需要确定里面一定是非nil的值

        

       

        var count :Int?

        count = 100

        if count !=nil {

            print("count is\(String(count))")

        }

        

        //可选绑定

        let possibleCount ="abc"

        iflet actualNumber = Int(possibleCount) {

            print("\(possibleCount) value of\(actualNumber)")

        }else {

            print("no value")

        }

        

        //as类型转换  is类型检查

        

        //断言

//        let age = -3

//        assert(age >= 0, "This is assert")//会打印this is assert会崩 

        

        //创建一个集合

        var setB =Set<String>()

        setB.insert("abc")

        setB.insert("def")

        setB.insert("123")

        print("\(setB)")

        

        for jihein setB.sort() {

            print("\(jihe)")

        }

        

        //字典

        var airports: [String:String] = ["111":"a","222":"b"]

        print("airports :\(airports.count)");

        

        iflet oldValue = airports.updateValue("123456", forKey:"11") {

            print("The old Value\(oldValue)")

        }

        

        for (airportCode, airportName)in airports {

            print("\(airportName):\(airportCode)")

        }


        //swift中的fallthrough 使代码块执行继续连接到下一个case的执行代码cswitch相同

        

        //带标签的语句

        //label name: while condition { statements }

        //eg: gameLoop: while square != finalSquare {}

        

        //使用guard执行取决于布尔值 一个guard里面总代有一个else

        func greet(person: [String:String]) {

            guardlet name = person["name"]else {

                return

            }

            

            print("Hello\(name)")

            

            guardlet location = person["location"]else {

                

                print("I hope the weather is nice near you")

                return

            }

            print("I hope the weather is nice in\(location).")

        }

        

        

        greet(["name":"John"])

        


0 0
原创粉丝点击