Last active
April 6, 2016 11:10
-
-
Save TheDarkCode/87b77df7b5c138714c4644030267e72a to your computer and use it in GitHub Desktop.
Extensions for working with unicode scalars when doing string manipulations. Simple optimization in Swift 2.2 that can save valuable ms.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Unicode Scalar Playground | |
import Foundation | |
var str = "Hello, playground" | |
protocol _UnicodeScalarType { | |
func toChar() -> Character | |
} | |
extension UnicodeScalar: _UnicodeScalarType { | |
func toChar() -> Character { | |
return Character(self) | |
} | |
} | |
extension Array where Element : _UnicodeScalarType { | |
func toString() -> String { | |
var str = String() | |
for scalar in self { | |
str += "\(scalar.toChar())" | |
} | |
return str | |
} | |
} | |
public extension String { | |
subscript(index: Int) -> Character { | |
return self[startIndex.advancedBy(index)] | |
} | |
subscript(range: Range<Int>) -> String { | |
let char0 = startIndex.advancedBy(range.startIndex) | |
let charN = startIndex.advancedBy(range.endIndex) | |
return self[char0..<charN] | |
} | |
func toUnicodeArray() -> Array<UnicodeScalar> { | |
let scalars = self.unicodeScalars | |
return Array(scalars) | |
} | |
} | |
str.toUnicodeArray() // [72, 101, 108, 108, 111, 44, 32, 112, 108, 97, 121, 103, 114, 111, 117, 110, 100] | |
str.toUnicodeArray()[0].toChar() // "H" | |
str.toUnicodeArray().toString() // "Hello, playground" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment