Avatar
norio_nomura 1/31/2019 3:19 AM
ランタイムの内部表現に依存してるかどうかまでは確かめてないですが。 依存してるぽい。
3:24 AM
このコードをmacOSで実行すると、stringUTF16Backendを使うとtest()内でクラッシュする。 import Foundation #if !compiler(>=5) private extension String.UTF8View { func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R? { return nil } } #endif extension String { var nativeEncoding: Encoding { return utf8.withContiguousStorageIfAvailable({$0}) != nil ? .utf8 : .utf16 } } func printUTF16<S: StringProtocol>(_ string: S, label: String) { print(label, string.utf16.map { "\\u{\(String($0, radix: 16))}" }.joined()) } func test(_ string: String) { let utf16Index = string.utf16.index(before: string.utf16.endIndex) let utf16Before = string[..<utf16Index] printUTF16(utf16Before, label: "before:") let utf16After = string[utf16Index...] printUTF16(utf16After, label: "after:") printUTF16(utf16Before + utf16After, label: "joined:") print(utf16After.utf8.count) print(utf16After.utf16.count) } // https://emojipedia.org/family-man-woman-girl-boy/ let string = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{200d}\u{1f466}" print(string.nativeEncoding) test(string) let tempfileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString) try string.write(to: tempfileURL, atomically: true, encoding: .utf16) let stringUTF16Backend = try String(contentsOfFile: tempfileURL.path) print(stringUTF16Backend.nativeEncoding) test(stringUTF16Backend) defer { try! FileManager.default.removeItem(at: tempfileURL) } (edited)