Sunday 2 October 2016

swift - Get the length of a String



How do you get the length of a String? For example, I have a variable defined like:



var test1: String = "Scott"



However, I can't seem to find a length method on the string.


Answer



Swift 5+:



test1.count


(Swift 5.0 strings can, in some ways, simply be treated as an array. Hence you can use .count or for example .first)







As of Swift 4



It's just:



test1.count


for reasons.




(Thanks to Martin R)



As of Swift 2:



With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:



test1.characters.count



(Thanks to JohnDifool for the heads up)



As of Swift 1



Use the count characters method:



let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
println("unusualMenagerie has \(count(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"



right from the Apple Swift Guide



(note, for versions of Swift earlier than 1.2, this would be countElements(unusualMenagerie) instead)



for your variable, it would be



length = count(test1) // was countElements in earlier versions of Swift



Or you can use test1.utf16count


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...