gpt4 book ai didi

ios - 从 swift 3.0 中删除语句的 C 样式,successor() 不可用

转载 作者:搜寻专家 更新时间:2023-11-01 07:21:48 24 4
gpt4 key购买 nike

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

}

最佳答案

在 Swift 3 中,“Collections move their index”,参见 A New Model for Collections and Indices 关于 Swift 的演变。特别是,

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>

关于ios - 从 swift 3.0 中删除语句的 C 样式,successor() 不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38519762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com