2016-09-27 91 views
0

我想從字符串中創建一個CRC32哈希值,因此我得到了zlib函數crc32 。zlib的crc32函數在swift中失敗3無法爲類型爲'UnsafePointer <Bytef>'的類型爲'(UnsafeRawPointer)'的參數列表調用初始值設定項'

但在Swift 3中,這會產生問題。

的代碼看起來是這樣的:

func crc32HashString(_ string: String) { 
    let strData = string.data(using: String.Encoding.utf8, allowLossyConversion: false) 
    let crc = crc32(uLong(0), UnsafePointer<Bytef>(strData!.bytes), uInt(strData!.length)) 
} 

編譯器給了我這個錯誤:

Cannot invoke initializer for type 'UnsafePointer<Bytef>' with an argument list of type '(UnsafeRawPointer)' 

如何解決這個問題?

最好的問候,並感謝您的幫助!

阿圖爾

回答

1

一個Data值的字節被使用

/// Access the bytes in the data. 
/// 
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. 
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType 

方法來訪問。它調用與(鍵入)指針字節的閉合:

let strData = string.data(using: .utf8)! // Conversion to UTF-8 cannot fail 
let crc = strData.withUnsafeBytes { crc32(0, $0, numericCast(strData.count)) } 

這裏$0的類型被自動推斷爲 UnsafePointer<Bytef>從上下文。

+0

謝謝你的答覆! –

+0

很好的答案Martin。快速提問:爲什麼在這裏使用'numericCast'而不是'strData.count'?這是用來防止溢出? – JAL

+1

@JAL:'strData.count'是一個'Int',但'crc32()'帶有'uInt'參數。所以你必須將該值轉換爲'uInt(strData.count)',或者使用泛型函數'numericCast'來轉換任意有符號和無符號整數類型。這是一個你挑選哪一個品味的問題。 –

相關問題