我的代码中的Swift 3迁移错误

时间:2016-10-04 10:27:31

标签: ios swift swift3

我的代码中出现错误

func dataFromHexadecimalString(_ key:String) -> NSString? {

    let trimmedString = key.trimmingCharacters(in: CharacterSet(charactersIn: "<> ")).replacingOccurrences(of: " ", with: "")


    let regex: NSRegularExpression?
    do {
        regex = try NSRegularExpression(pattern: "^[0-9a-f]*$", options: .caseInsensitive)
    } catch _ as NSError {
        regex = nil
    }
    let found = regex?.firstMatch(in: trimmedString, options: [], range: NSMakeRange(0, trimmedString.characters.count))
    if found == nil || found?.range.location == NSNotFound || trimmedString.characters.count % 2 != 0 {
        return nil
    }


    let data = NSMutableData(capacity: trimmedString.characters.count / 2)

    //I am Getting error here i.e C-style for statement has been removed in Swift 3
    for var index = trimmedString.startIndex; index < trimmedString.endIndex; index = Collection.index(after: Collection.index(after: index)) {
        let byteString = trimmedString.substring(with: (index ..< Collection.index(after: Collection.index(after: index))))
        let num = UInt8(byteString.withCString { strtoul($0, nil, 16) })
        data?.append([num] as [UInt8], length: 1)
    }

    let enCodedUTF8String = NSString(data: data! as Data, encoding: String.Encoding.utf8.rawValue)

    return enCodedUTF8String

}

获取错误,C-style for statement has been removed 见上面的代码注释

1 个答案:

答案 0 :(得分:0)

从我能告诉您的代码......

//I am Getting error here i.e C-style for statement has been removed in Swift 3
for var index = trimmedString.startIndex; index < trimmedString.endIndex; index = Collection.index(after: Collection.index(after: index)) {
    let byteString = trimmedString.substring(with: (index ..< Collection.index(after: Collection.index(after: index))))
    let num = UInt8(byteString.withCString { strtoul($0, nil, 16) })
    data?.append([num] as [UInt8], length: 1)
}

是否正在迭代trimmedString的指数,但正在进行2?一次?

如果index为0(它将开始),那么下一个索引将是......

指数后索引后的指数... 2后经过0

那么2?然后是4?那么6?

然后你从该索引获取子字符串到下一个索引?

然后您从中创建UInt8并将其附加到某些数据中......

因此...

我想最简单的改变是while循环......

var index = trimmedString.startIndex

while index < trimmedString.endIndex {
    // note I used the ... for the range to avoid the repeated... index after index after index
    let byteString = trimmedString.substring(with: (index ... Collection.index(after: index)))
    let num = UInt8(byteString.withCString { strtoul($0, nil, 16) })
    data?.append([num] as [UInt8], length: 1)

    // check the docs, there are easier ways of moving the index by more than one place.
    index = Collection(index, offsetBy: 2)
}

这样的事情应该是最初的改变。

@vadian提出了更好的方法

正如@vadian指出的那样,在一行代码中完成所有这些工作有一种更简单,更优雅的方式......

let enCodedUTF8String = data.map{ String(format: "%02x", $0) }.joined()

我认为情况确实如此,但我自己无法想出来。