从 swift 3.0 中删除语句的 C 样式,successor() 不可用 [英] C style for statement removed from swift 3.0, successor() is unavailable

查看:21
本文介绍了从 swift 3.0 中删除语句的 C 样式,successor() 不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮我更新这个 for 循环到 swift 3.0.0 吗?帮助表示赞赏.谢谢!

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)

    }

推荐答案

在 Swift 3 中,Collections move their index",参见集合和索引的新模型 关于 Swift 进化.尤其是

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)

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

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>

这篇关于从 swift 3.0 中删除语句的 C 样式,successor() 不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆