jam*_*rez 10 objective-c swift
我正在尝试在Swift中复制一些Objective C cocoa.一切都很好,直到我遇到以下情况:
// Set a new type and creator:
unsigned long type = 'TEXT';
unsigned long creator = 'pdos';
Run Code Online (Sandbox Code Playgroud)
如何从单引号字符文字中创建Int64(或正确的Swift等价物)?
类型:
public typealias AEKeyword = FourCharCode
public typealias OSType = FourCharCode
public typealias FourCharCode = UInt32
Run Code Online (Sandbox Code Playgroud)
我在我的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
}
Run Code Online (Sandbox Code Playgroud)
编辑:
另外
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
}
Run Code Online (Sandbox Code Playgroud)
或者仍然更加迅速
func fourCharCode(from string : String) -> FourCharCode
{
return string.utf16.reduce(0, {$0 << 8 + FourCharCode($1)})
}
Run Code Online (Sandbox Code Playgroud)
我从 Swift API 中找到了以下类型别名:
typealias FourCharCode = UInt32
typealias OSType = FourCharCode
Run Code Online (Sandbox Code Playgroud)
以及以下功能:
func NSFileTypeForHFSTypeCode(hfsFileTypeCode: OSType) -> String!
func NSHFSTypeCodeFromFileType(fileTypeString: String!) -> OSType
Run Code Online (Sandbox Code Playgroud)
这应该允许我创建等效的代码:
let type : UInt32 = UInt32(NSHFSTypeCodeFromFileType("TEXT"))
let creator : UInt32 = UInt32(NSHFSTypeCodeFromFileType("pdos"))
Run Code Online (Sandbox Code Playgroud)
但是那些 4 个字符的字符串不起作用并返回0.
如果将每个字符串用'单引号括起来'并调用相同的函数,您将获得正确的返回值:
let type : UInt32 = UInt32(NSHFSTypeCodeFromFileType("'TEXT'"))
let creator : UInt32 = UInt32(NSHFSTypeCodeFromFileType("'pdos'"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1622 次 |
| 最近记录: |