【发布时间】:2016-12-25 07:19:01
【问题描述】:
extension String {
/// Create NSData from hexadecimal string representation
///
/// This takes a hexadecimal representation and creates a NSData object. Note, if the string has any spaces, those are removed. Also if the string started with a '<' or ended with a '>', those are removed, too. This does no validation of the string to ensure it's a valid hexadecimal string
///
/// The use of `strtoul` inspired by Martin R at http://stackoverflow.com/a/26284562/1271826
///
/// - returns: NSData represented by this hexadecimal string. Returns nil if string contains characters outside the 0-9 and a-f range.
func dataFromHexadecimalString() -> NSData? {
let trimmedString = self.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<> ")).stringByReplacingOccurrencesOfString(" ", withString: "")
// make sure the cleaned up string consists solely of hex digits, and that we have even number of them
var error: NSError?
let regex: NSRegularExpression?
do {
regex = try NSRegularExpression(pattern: "^[0-9a-f]*$", options: .CaseInsensitive)
} catch let error1 as NSError {
error = error1
regex = nil
}
let found = regex?.firstMatchInString(trimmedString, options: [], range: NSMakeRange(0, trimmedString.characters.count))
if found == nil || found?.range.location == NSNotFound || trimmedString.characters.count % 2 != 0 {
return nil
}
// everything ok, so now let's build NSData
let data = NSMutableData(capacity: trimmedString.characters.count / 2)
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)
}
return data
}
}
尝试将上述代码片段中的 for 循环转换为 swift 3,目前是用 swift 2.3 编写的,但遇到了问题。错误是:“C-style for statement has been removed in Swift 3”
下面的 for 循环是我在 xcode 上按下“转换为 swift 3”按钮后发生的情况。
for var index = trimmedString.startIndex; index < trimmedString.endIndex; index = <#T##Collection corresponding to your index##Collection#>.index(after: <#T##Collection corresponding to `index`##Collection#>.index(after: index)) {
let byteString = trimmedString.substring(with: (index ..< <#T##Collection corresponding to your index##Collection#>.index(after: <#T##Collection corresponding to `index`##Collection#>.index(after: index))))
let num = UInt8(byteString.withCString { strtoul($0, nil, 16) })
data?.append([num] as [UInt8], length: 1)
}
extension NSData {
/// Create hexadecimal string representation of NSData object.
///
/// - returns: String representation of this NSData object.
func hexadecimalString() -> String {
let string = NSMutableString(capacity: length * 2)
var byte: UInt8 = 0
for i in 0 ..< length {
getBytes(&byte, range: NSMakeRange(i, 1))
string.appendFormat("%02x", byte)
}
return string as String
}
}
上面代码 sn-p 中的 for 循环在 swift 3 中也不起作用。如何为 swift 3 重写这个?这个错误是:“无法使用类型为'(to:inout UInt8,from:NSRange)'的参数列表调用'copyBytes'”
任何帮助表示赞赏。我使用这些函数为我正在使用的第三方服务构建一个特殊的 url,但努力将这个复杂的语法更新为 swift 3。
错误截图here
【问题讨论】:
-
搜索
[swift] dataFromHexadecimalString很快就会显示这个答案stackoverflow.com/a/26502285/1187415,该答案已在不久前针对Swift 3 进行了更新。
标签: ios swift cryptography swift3 hex