美文网首页
Swift - 区间运算符(... 和 ..<)

Swift - 区间运算符(... 和 ..<)

作者: 乖_摸摸头F | 来源:发表于2018-11-16 14:28 被阅读0次
    1、闭区间运算符:a...b

    for i in 512...1024{
    //从512遍历到1024(包括1024)
    }

    2、半闭区间运算符:a..<b

    var fruts = ["apple","orange","banana"]
    let frutsCount = fruts.count
    for i in 0..< frutsCount{
    print("第(i+1)个水果是(fruts[i])")
    }

    3、倒序循环,通过 reversed() 方法,我们可以将一个正序循环变成逆序循环。(输出结果:3、2、1、0)

    for i in (0..<4).reversed() {
    print(i)
    }

    4、字符串范围也可以使用区间运算符

    //字符串截取
    let words = "Hangge.com"
    //不使用区间运算符
    let index = words.index(words.startIndex, offsetBy: 4)
    let index2 = words.index(words.startIndex, offsetBy: 6)
    let range1 = Range(uncheckedBounds: (lower: index, upper: index2))
    let rangeStr1 = words.substring(with: range1) //ge
    print(rangeStr1)
    //使用区间运算符
    let range2 = words.index(words.startIndex, offsetBy: 4)..<words.index(words.startIndex,offsetBy: 6)
    let rangeStr2 = words.substring(with: range2) //ge
    print(rangeStr2)

    相关文章

      网友评论

          本文标题:Swift - 区间运算符(... 和 ..<)

          本文链接:https://www.haomeiwen.com/subject/tqrmfqtx.html