james_alvarez james_alvarez - 6 months ago 41
Swift Question

Swift equivalent to Objective-C FourCharCode single quote literals (e.g. 'TEXT')

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';


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

Answer

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
}

Edit:

Alternatively

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