If you're sure you don't need to worry about anything other than ASCII, you can use the utf16Count
property (which is the length
property of the bridged NSString
):
let stringLength = superLongString.utf16Count
If you want to be able to handle Unicode you need to walk the string, you just don't want to walk the whole string. Here's a function to count just up to your limit:
func lengthLessThanMax(#string: String, maximum max: Int) -> Bool {
var idx = string.startIndex
var count = 0
while idx < string.endIndex && count < max {
++count
idx = idx.successor()
}
return count < max
}
lengthLessThanMax(string: "Hello!", maximum: 10)
// true
lengthLessThanMax(string: "Hello! Nice to meet you!", maximum: 10)
// false