String length in Swift 1.2 and Swift 2.0 [duplicate]

Solution 1:

You can use extension for it like:

extension String {
     var length: Int { return count(self)         }  // Swift 1.2
}

and you can use it:

if mystr.length >= 3 {

}

Or you can directly count this way:

if count(mystr) >= 3{

}

And this is also working for me :

if count(mystr.utf16) >= 3 {

}

For Swift 2.0:

extension String {
    var length: Int {
        return characters.count
    }
}
let str = "Hello, World"
str.length  //12

Another extension:

extension String {
    var length: Int {
        return (self as NSString).length
    }
}
let str = "Hello, World"
str.length //12

If you want direct use:

let str: String = "Hello, World"
print(str.characters.count) // 12

let str1: String = "Hello, World"
print(str1.endIndex) // 12

let str2 = "Hello, World"
NSString(string: str2).length  //12

Solution 2:

You have to use characters property that contains the property count :

yourString.characters.count

Solution 3:

Swift 2.0 UPDATE

extension String {
    var count: Int { return self.characters.count }
}

Use:

var str = "I love Swift 2.0!"
var n = str.count

Helpful Progamming Tips and Hacks

Solution 4:

Here is all in one -- copied from here

let str = "Hello"
let count = str.length    // returns 5 (Int)

extension String {
    var length: Int { return countElements(self) }  // Swift 1.1
}
extension String {
    var length: Int { return count(self)         }  // Swift 1.2
}
extension String {
    var length: Int { return characters.count    }  // Swift 2.0
}

Solution 5:

count(mystr) is the correct way, you do not need to convert the encoding.

This: if count(mystr.utf16) >= 3 is fine as long as you do Int16(3)

Edit: this is an old answer. OP updated his question to reflect Swift 2 and the above answer is correct.