Skip to content

Instantly share code, notes, and snippets.

@donly
Forked from patrickjuchli/FourCharCode+String.swift
Last active June 23, 2022 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donly/a591ee23b669dc61159b49f5a3a91d48 to your computer and use it in GitHub Desktop.
Save donly/a591ee23b669dc61159b49f5a3a91d48 to your computer and use it in GitHub Desktop.
import Foundation
/**
Set FourCharCode/OSType using a String.
Examples:
let test: FourCharCode = "420v"
let test2 = FourCharCode("420f")
print(test.string, test2.string)
*/
extension FourCharCode: ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
var code: FourCharCode = 0
// Value has to consist of 4 printable ASCII characters, e.g. '420v'.
// Note: This implementation does not enforce printable range (32-126)
if value.count == 4 && value.utf8.count == 4 {
for byte in value.utf8 {
code = code << 8 + FourCharCode(byte)
}
}
else {
print("FourCharCode: Can't initialize with '\(value)', only printable ASCII allowed. Setting to '????'.")
code = 0x3F3F3F3F // = '????'
}
self = code
}
public init(extendedGraphemeClusterLiteral value: String) {
self = FourCharCode(stringLiteral: value)
}
public init(unicodeScalarLiteral value: String) {
self = FourCharCode(stringLiteral: value)
}
public init(_ value: String) {
self = FourCharCode(stringLiteral: value)
}
public var string: String {
let bytes: [CChar] = [
CChar((self >> 24) & 0xff),
CChar((self >> 16) & 0xff),
CChar((self >> 8) & 0xff),
CChar(self & 0xff),
0
]
let result = String(cString: bytes)
let characterSet = CharacterSet.whitespaces
return result.trimmingCharacters(in: characterSet)
}
}
@donly
Copy link
Author

donly commented Jun 23, 2022

Usage example:

var formatDesc: CMFormatDescription? = nil
CMFormatDescriptionCreate(allocator: nil, mediaType: kCMMediaType_Text, mediaSubType: FourCharCode(stringLiteral: "tx3g"), extensions: nil, formatDescriptionOut: &formatDesc)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment