从swift 3.0删除语句的C样式,successor()不可用

时间:2016-07-22 06:38:41

标签: ios swift swift3

任何人都可以帮我更新这个循环到swift 3.0。帮助赞赏。谢谢!

for var index = trimmedString.startIndex; index < trimmedString.endIndex; index = index.successor().successor() {

        let byteString = trimmedString.substringWithRange(Range<String.Index>(start: index, end: index.successor().successor()))
        let num = UInt8(byteString.withCString { strtoul($0, nil, 16) })
        data?.appendBytes([num] as [UInt8], length: 1)

    }

1 个答案:

答案 0 :(得分:2)

在Swift 3中,&#34;集合移动他们的索引&#34;,见  关于斯威夫特进化的A New Model for Collections and Indices。特别是,

let toIndex = string.index(fromIndex, offsetBy: 2, limitedBy: string.endIndex)

将索引fromIndex提升2个字符位置,但仅限 如果它适合有效的索引范围,并返回nil 除此以外。因此循环可以写为

let string = "0123456789abcdef"
let data = NSMutableData()

var fromIndex = string.startIndex
while let toIndex = string.index(fromIndex, offsetBy: 2, limitedBy: string.endIndex) {

    // Extract hex code at position fromIndex ..< toIndex:
    let byteString = string.substring(with: fromIndex..<toIndex)
    var num = UInt8(byteString.withCString { strtoul($0, nil, 16) })
    data.append(&num, length: 1)

    // Advance to next position:
    fromIndex = toIndex
}

print(data) // <01234567 89abcdef>