【问题标题】:C style for statement removed from swift 3.0, successor() is unavailable从 swift 3.0 中删除的 C 样式语句,successor() 不可用
【发布时间】:2016-07-22 06:38:41
【问题描述】:

谁能帮我把这个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)

    }

【问题讨论】:

标签: ios swift swift3


【解决方案1】:

在 Swift 3 中,“集合移动它们的索引”,请参阅 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>

【讨论】:

  • 嘿,谢谢,我不确定 offsetBy 参数?有什么意义?
  • @ShashantDahikar:正如我所说,offsetBy: 2 将索引增加 2,就像 .successor().successor() 在您的 Swift 2 代码中所做的那样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多