问题
Can anyone please help me update this for loop to swift 3.0. help appreciated. Thank you!
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:
In Swift 3, "Collections move their index", see A New Model for Collections and Indices on Swift evolution. In particular,
let toIndex = string.index(fromIndex, offsetBy: 2, limitedBy: string.endIndex)
advanced the index fromIndex by 2 character positions, but only
if it fits into the valid range of indices, and returns nil
otherwise. Therefore the loop can be written as
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>
来源:https://stackoverflow.com/questions/38519762/c-style-for-statement-removed-from-swift-3-0-successor-is-unavailable