Consider this function to build a string of random characters:
func makeToken(length: Int) -> String { let chars: String = "abcdefghijklmnopqrstuvwxyz0123456789!?@#$%ABCDEFGHIJKLMNOPQRSTUVWXYZ" var result: String = "" for _ in 0..<length { let idx = Int(arc4random_uniform(UInt32(chars.characters.count))) let idxEnd = idx + 1 let range: Range = idx..<idxEnd let char = chars.substring(with: range) result += char } return result } This throws an error on the substring method:
Cannot convert value of type 'Range<Int>' to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>') I'm confused why I can't simply provide a Range with 2 integers, and why it's making me go the roundabout way of making a Range<String.Index>.
So I have to change the Range creation to this very over-complicated way:
let idx = Int(arc4random_uniform(UInt32(chars.characters.count))) let start = chars.index(chars.startIndex, offsetBy: idx) let end = chars.index(chars.startIndex, offsetBy: idx + 1) let range: Range = start..<end Why isn't it good enough for Swift for me to simply create a range with 2 integers and the half-open range operator? (..<)
Quite the contrast to "swift", in javascript I can simply do chars.substr(idx, 1)