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

后端 未结 7 2334
青春惊慌失措
青春惊慌失措 2021-02-20 13:05

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:18

    Extend ExpressibleByStringLiteral to use four-character string literals directly:

    extension FourCharCode: ExpressibleByStringLiteral {
    
        public init(stringLiteral value: StringLiteralType) {
            if let data = value.data(using: .macOSRoman), data.count == 4 {
                self = data.reduce(0, {$0 << 8 + Self($1)})
            } else {
                self = 0
            }
        }
    
    }
    

    Now you can just pass a string literal as the FourCharCode / OSType / UInt32 parameter:

    let record = NSAppleEventDescriptor.record()
    record.setDescriptor(NSAppleEventDescriptor(boolean: true), forKeyword: "test")
    

提交回复
热议问题