我正在尝试在
Swift中复制一些Objective C cocoa.一切都很好,直到我遇到以下情况:
// Set a new type and creator: unsigned long type = 'TEXT'; unsigned long creator = 'pdos';
如何从这样的单引号字符文字创建Int64(或正确的Swift等价物)?
类型:
public typealias AEKeyword = FourCharCode public typealias OSType = FourCharCode public typealias FourCharCode = UInt32
我在我的Cocoa Scripting应用程序中使用它,它认为字符> 0x80正确
原文链接:https://www.f2er.com/swift/319482.htmlfunc 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)}) }