您的位置:首页 > 移动开发 > Swift

swift(二)

2015-10-22 17:37 337 查看
记录下  今天学的东西。。看到闭包了。。看不下去了。。

   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"
        if
let 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 jihe
in setB.sort() {
            print("\(jihe)")
        }
        
        //字典
        var airports: [String:
String] = ["111":"a","222":"b"]
        print("airports :\(airports.count)");
        
        if
let oldValue = airports.updateValue("123456", forKey:
"11") {
            print("The old Value
\(oldValue)")
        }
        
        for (airportCode, airportName)
in airports {
            print("\(airportName):\(airportCode)")
        }

        //swift中的fallthrough 
使代码块执行继续连接到下一个case的执行代码
和c的switch相同
        
        //带标签的语句
        //label name: while condition { statements }
        //eg: gameLoop: while square != finalSquare {}
        
        //使用guard执行取决于布尔值 
一个guard里面总代有一个else
        func greet(person: [String:
String]) {
            guard
let name = person["name"]
else {
                return
            }
            
            print("Hello
\(name)")
            
            guard
let 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"])
        
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swift iOS