Swift學習1.0

weixin_33850890發表於2016-10-06
swift基本資料型別簡介及基本使用
    var Xnum: Int = 15; //Int為指定資料型別
    var Xfloat: CGFloat = 14.1
    // 元組
    let student: (String, Int, Double, Int) = ("lisi",24,90.0,15)
    let student1 = (name:"zhangsan", age:26)//直接定義元組資料

    //可選值 optionals, 兩種狀態:有值,沒有值(nil)
    var optValue: Int? = 3

    Xfloat = CGFloat(Xnum)//強轉型別
        //元組資料提取
        print(student1.name)
        print(student1.age)
        let (name, age, score, number) = student
        print(name,age,score,number)
        
        if (optValue != nil){//可選值有值為真,無值為假
            print(optValue)
        }
        //表示對可選值的強制解析,可選值!(提取可選值)如可選值沒有值時,不能進行強制解析。否則會有執行時的錯誤
        let svalue: Int = optValue!
        print(svalue)
        
        //可選繫結 (比強制解析更加安全)
        if let svalue1 = optValue {
            
            print(svalue1)
        }
        
        //隱式可選型別
        let intValue:Int = impOptValue
        print(intValue)
        
        //字串操作
        let str1:String = "http:www.baidu.com"
        let str2:String = "1"
        let url:String = str1 + str2//字串拼接
        print(url);
        
        let char = str1[str1.index(after: str1.startIndex)]//獲取指定位置的字元
        print(char)
        
        let subString = str1[str1.startIndex...str1.index(str1.startIndex, offsetBy: 4)]
        print(subString)//擷取指定位置的字串
        
        let urlStr:String = "http:www.baidu.com/num=\(str2)"        
        let rangStr: Range = urlStr.range(of: str1)!
        print(rangStr)
        
//        let subUrlString = urlStr[urlStr.startIndex...urlStr]
        
        if urlStr.hasPrefix("http") {//判斷字串字首
            print(urlStr)
        }
        
        if urlStr.hasPrefix(str2) {//字尾
            print(urlStr)
        }
        
        let studentValue:Student = self.getMultipleValues()
        print(studentValue)
        
        // 關係運算子
        let res:Bool = 5 == 5+3
        
        if res {
        }
        
        let testInt: Int = 3 > 2 ? 3 : 2//三元運算子
        print(testInt)
        
        for i in 1...5 {//for迴圈遍歷
            print(i)
        }
        
        var array = [1,2,3,4];
        array.remove(at: 0);//刪除陣列中某個位置的元素
        var range1: Range<Int> = 1..<5
        var range2 = 1...6
        print(range2)
        print(range1)
        
        range1 = 0..<2
        range2 = 0...2
        array[range1] = [1,1]
        array.replaceSubrange(1..<2, with: [1,3])//替換某個區間的元素
        print("arry:=\(array)")
        
        for item in array {
            print("for in item: \(item)")
        }
        ///
        for (index, value) in array.enumerated() {//遍歷陣列 index為陣列下表 value為對應的元素
            
            print("for enumerated index:\(index) value:\(value)")
        }

相關文章