swift 區間運算子(... 和 ..

weixin_34148340發表於2018-10-30
  1. 閉區間運算子:a...b
//遍歷0-10,包含0和10
for i in 0...10 {
    
    print("\(i)");
}
  1. 半閉區間運算子 a..<b
//包含0,不包含10
for i in 0..<10 {
    
    print("______\(i)");
    
}

3.倒序迴圈

//輸出結果為9,8,7...0
for i in (0..<10).reversed() {
    
    print("++++++++\(i)");
}

4.字串擷取

let words = "hangge.com"
let range = words.index(words.startIndex,offsetBy:4) ..< words.index(words.startIndex,offsetBy:6);
let rangeStr2 = words.substring(with: range)
  1. 檢查字串裡的字元是不是都是合法字元(比如是不是都是小寫)
let wordsx = "Hangge.com"

let interval = "a"..."z"
for c in wordsx.characters {
    if !interval.contains(String(c)){
        print("\(c)不是小寫字母")
    }
}

/*
 輸出結果:
 H不是小寫字母
 .不是小寫字母
 */

相關文章