Shashant Dahikar Shashant Dahikar - 4 months ago 116
iOS Question

C style for statement removed from swift 3.0, successor() is unavailable

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)

}

Answer

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>