Swift is equivalent to Objective-C FourCharCode single quote literals (for example, "TEXT")

I am trying to play some Objective C cocoa in Swift. All is well, until I came across the following:

// Set a new type and creator: unsigned long type = 'TEXT'; unsigned long creator = 'pdos'; 

How can I create Int64s (or the correct Swift equivalent) from single quotation letter literals like this?

+5
source share
3 answers

I use this in my Cocoa Scripting applications, it correctly counts characters> 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 } 

Edit:

As an alternative

 func fourCharCodeFrom(string : String) -> FourCharCode { assert(string.characters.count == 4, "String length must be 4") var result : FourCharCode = 0 for char in string.utf16 { result = (result << 8) + FourCharCode(char) } return result } 
+5
source

Note: this should work, but it really doesn’t work - there must be an error. I leave this here to document that it does not work, may work in the future, but for the time being it is best to use the accepted answer.

I discovered the following type types from the Swift API:

 typealias FourCharCode = UInt32 typealias OSType = FourCharCode 

And the following functions:

 func NSFileTypeForHFSTypeCode(hfsFileTypeCode: OSType) -> String! func NSHFSTypeCodeFromFileType(fileTypeString: String!) -> OSType 

This should allow me to create equivalent code:

 let type : UInt32 = UInt32(NSHFSTypeCodeFromFileType("TEXT")) let creator : UInt32 = UInt32(NSHFSTypeCodeFromFileType("pdos")) 

WARNING: But this does not work on Xcode 7.0 beta (7A121l)

+2
source

Here is a simple function

 func mbcc(foo: String) -> Int { let chars = foo.utf8 var result: Int = 0 for aChar in chars { result = result << 8 + Int(aChar) } return result } let a = mbcc("TEXT") print(String(format: "0x%lx", a)) // Prints 0x54455854 

It will work for strings that will fit in Int. As soon as they get longer, he starts to play numbers on top.

If you use

 result = result * 256 + Int(aChar) 

you should get a crash when the line gets too big.

+1
source

All Articles