EDIT: also how to get character n in a string.
EDIT: also how to get character n in a string.
You can also add your own String extension for length and index character at in a String with:
extension String {
var length: Int { return countElements(self) }
subscript (i: Int) -> String {
return String(Array(self)[i])
}
}
Which will now let you use `.length` on strings, e.g: "Cat".length; //3
And get the character at index with: "Cat"[1]; //a
I've more useful extensions at: https://github.com/mythz/swift-linq-examples/blob/master/src...Which enables LINQ-like querying in Swift: https://github.com/mythz/swift-linq-examples
[0] What is a character especially in various non-latin scripts? I think it is well handled in Swift, from what I can see it has been considered carefully but I haven't yet needed to get my head round it.
Edit: Corrected - too fast in the playground and actually checked an array. .utf16count not .count
countElements(string)
returns the number of Unicode code points in a string. I'm not sure about the random character, though. Swift is very much oriented towards Unicode rather than bytes when it comes to strings.Short story: “number of characters” and “nth character” are more complicated questions than you might think when you deal with full Unicode text.
Looks like a great article, thanks!
let codepoint: UInt32 = ...random choice code here...
let scalar = UnicodeScalar(codepoint)
let string = String(scalar) func randChar(alphabet:String?)->String {
let alpha = alphabet ? alphabet! : "abcdefghijklmnopqrstuvwxyz"
let rand:Int = Int(arc4random_uniform(UInt32(countElements(alpha))))
var gen = alpha.generate()
for i in 0..<rand {
gen.next()
}
return String(gen.next()!)
}
mikeash obviously has the answer if the codepoints are consecutive.This was quite annoying to do, more so than I expected. If you convert to UTF16 view you can alter the index by advanceBy but then I couldn't find an easy way to convert back from the UInt16 to a Character/String but mikeash also covers that. However I'm not sure that conversion to UTF16 is any less work internally than iterating through the index.