任何人都可以帮我更新这个循环到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)
}
答案 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>