C style for statement removed from swift 3.0, succ

2019-06-07 01:11发布

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)

    }

标签: ios swift swift3
1条回答
贪生不怕死
2楼-- · 2019-06-07 01:47

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>
查看更多
登录 后发表回答