我正在尝试在 Swift 中复制一些 Objective C cocoa。一切都很好,直到我遇到以下情况:
// Set a new type and creator:
unsigned long type = 'TEXT';
unsigned long creator = 'pdos';
如何从这样的单引号字 rune 字创建 Int64(或正确的 Swift 等价物)?
类型:
public typealias AEKeyword = FourCharCode
public typealias OSType = FourCharCode
public typealias FourCharCode = UInt32
最佳答案
我在我的 Cocoa Scripting 应用程序中使用它,它正确地考虑字符 > 0x80
func OSTypeFrom(string : String) -> UInt {
var result : UInt = 0
if let data = string.dataUsingEncoding(NSMacOSRomanStringEncoding) {
let bytes = UnsafePointer<UInt8>(data.bytes)
for i in 0..<data.length {
result = result << 8 + UInt(bytes[i])
}
}
return result
}
编辑:
或者
func fourCharCodeFrom(string : String) -> FourCharCode
{
assert(string.count == 4, "String length must be 4")
var result : FourCharCode = 0
for char in string.utf16 {
result = (result << 8) + FourCharCode(char)
}
return result
}
或者仍然更快
func fourCharCode(from string : String) -> FourCharCode
{
return string.utf16.reduce(0, {$0 << 8 + FourCharCode($1)})
}
关于objective-c - Swift 等效于 Objective-C FourCharCode 单引号文字(例如 'TEXT' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31320243/