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

后端 未结 7 2553
天命终不由人
天命终不由人 2021-02-20 12:54

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\         


        
7条回答
  •  天命终不由人
    2021-02-20 13:23

    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(data.bytes)
        for i in 0..

    Edit:

    Alternatively

    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
    }
    

    or still swiftier

    func fourCharCode(from string : String) -> FourCharCode
    {
      return string.utf16.reduce(0, {$0 << 8 + FourCharCode($1)})
    }
    

提交回复
热议问题