swift基本语法02

<4>循环

func demo(){
    //  swift 3.0 把for循环discard
    //  ++ 改成 +=  在swift 2.0
    //        for var i = 0; i < 3; i++ {
    //            print(i)
    //        }
    //1.for循环
    //  0 ..< 3 , 表示范围, [0, 3) 0 ,1 ,2
    //  0 ... 3 , 表示范围, [0, 3] 0 ,1 ,2, 3
    for i in 0..<3 {
        print(i)
    }
    for i in 0...3 {
        print(i)
    }
    for _ in 0..<3 {
        print("好好学习天天向上")
    }
    
    // 2. do - while 改成 repeat - while 是swift 2.0的时候
    var num = 3
    repeat {
        
        print(num)
        num -= 1
    } while num > 0
    
    
     // 3. while循环
    var total = 3
    while total > 0{
        print(total)
        total -= 1
    }
}

<5.> 字符串

func demo(){
    
    /*
     oc 字符串使用NSString, 继承NSObject, 它是一个对象
     swift里面字符串使用String, 它是一个结构体, 它的量级比NSString要轻, 性能要比NSString要快, 官方推荐使用String
     
     var 定义可变的字符串
     let 定义的不可变的字符串
     
     String 类型可以直接支持遍历
     NSString 不可以
     */
    
    //1.可变字符串
    var str = "难受想哭"
    str = "蓝瘦香菇"
    print(str)
    
    //不可变字符串
    let str1 = "旺仔牛奶"
    print(str1)
    
    //创建空字符串
    let str2: String = ""
    var str3: String = ""
    var str4: String = String()
    str4 = "iPhone7"
    print(str4)
    
    //2.遍历字符串
    let str5 = "hello kitty"
    for value in str5.characters {
        print(value)
    }
    
    //在指定编码下的字节的个数
    let len = str5.lengthOfBytes(using: String.Encoding.utf8)
    print(len)
    
    //获取的字符的个数
    let len2 = str5.characters.count
    print(len2)
    
    //3.字符串的拼接
    let s1 = "爱江山"
    let s2 = "更爱美人"
    
    //可以使用+做字符串的拼接
    let result = s1 + s2
    print(result)
    
    //\(xxx)拼接字符串
    let year: Int = 22
    let age = "我 \(year) 岁了"
    print(age)
    
    var message = "办证:"
    message += "6666666"
    print(message)
    
    //4.字符串的格式化
    let h = 15
    let m = 21
    let s = 3
    let newStr = String(format: "%02d: %02d: %02d", arguments: [h,m,s])
    print(newStr)
    
    //5.字符串的截取
    // String 和 NSString直接可以无缝转换使用as关键字
    let ns = "a2bc"
    let startIndex = ns.index(ns.startIndex, offsetBy: 1)
    let endIndex = ns.index(ns.endIndex, offsetBy: -1)
    let ns1 = ns.substring(with: startIndex..

你可能感兴趣的:(swift基本语法02)