Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sketchytech/5f88d1445fcd486614bc to your computer and use it in GitHub Desktop.
Save sketchytech/5f88d1445fcd486614bc to your computer and use it in GitHub Desktop.
Working with bytes and strings in Swift (Unicode Scalar, UTF8 and UTF16)
newStr = "hello 😂😒😡"
// the number of elements:
let count = newStr.utf16Count
// create array of appropriate length:
var array = [UInt16](count: count, repeatedValue: 0)
for a in enumerate(newStr.utf16) {
array[a.index] = a.element
}
NSString(bytes: &array, length: count*sizeof(UInt16), encoding: NSUTF16LittleEndianStringEncoding)
var str = "Hello "
var str2 = "playground"
// create unicode scalar array
var arr = [UnicodeScalar]()
// add byte array of unicode scalars
arr += str.unicodeScalars
var arr2 = [UnicodeScalar]()
arr2 += str2.unicodeScalars
arr += arr2
var str3 = String()
// extract characters from array
for a in arr {
str3.append(Character(a))
}
str3 // returns "Hello playground"
// Alternative that works
if let b = String.stringWithBytesNoCopy(&arr, length:arr.count * sizeof(UnicodeScalar), encoding: NSUTF32LittleEndianStringEncoding, freeWhenDone: false) {
b
}
var str = "Hello "
var str2 = "playground"
// create UInt16 array
var arr = [UInt16]()
// add byte array of UInt16
arr += str.utf16
var arr2 = [UInt16]()
arr2 += str2.utf16
arr += arr2
if let a = String.stringWithBytesNoCopy(&arr, length:arr.count * sizeof(UInt16), encoding: NSUTF16LittleEndianStringEncoding, freeWhenDone: false) {
a
}
var str = "Hello "
var str2 = "playground"
// create UInt8 array
var arr = [UInt8]()
// add byte array of UInt8
arr += str.utf8
var arr2 = [UInt8]()
arr2 += str2.utf8
arr += arr2
if let a = String.stringWithBytes(arr, encoding:NSUTF8StringEncoding) {
a
}
@sketchytech
Copy link
Author

In these examples I've transformed two strings into byte arrays, concatenated the byte arrays and then transformed back into strings.

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