Swift 等效于 Objective-C FourCharCode 单引号文字(例如“TEXT") [英] Swift equivalent to Objective-C FourCharCode single quote literals (e.g. 'TEXT')
本文介绍了Swift 等效于 Objective-C FourCharCode 单引号文字(例如“TEXT")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 Swift 中复制一些 Objective C 可可.一切都很好,直到我遇到以下情况:
I am trying replicate some Objective C cocoa in Swift. All is good until I come across the following:
// Set a new type and creator:
unsigned long type = 'TEXT';
unsigned long creator = 'pdos';
如何从这样的单引号字符文字创建 Int64(或正确的 Swift 等效项)?
How can I create Int64s (or the correct Swift equivalent) from single quote character literals like this?
类型:
public typealias AEKeyword = FourCharCode
public typealias OSType = FourCharCode
public typealias FourCharCode = UInt32
推荐答案
我在我的 Cocoa Scripting 应用程序中使用它,它正确地考虑字符 > 0x80
I'm using this in my Cocoa Scripting apps, it considers characters > 0x80 correctly
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)})
}
这篇关于Swift 等效于 Objective-C FourCharCode 单引号文字(例如“TEXT")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文