Get the length of a String

2019-01-01 10:03发布

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.

标签: swift string
30条回答
琉璃瓶的回忆
2楼-- · 2019-01-01 10:12

If you are just trying to see if a string is empty or not (checking for length of 0), Swift offers a simple boolean test method on String

myString.isEmpty

The other side of this coin was people asking in ObjectiveC how to ask if a string was empty where the answer was to check for a length of 0:

NSString is empty

查看更多
像晚风撩人
3楼-- · 2019-01-01 10:12

String and NSString are toll free bridge so you can use all methods available to NSString with swift String

let x = "test" as NSString
let y : NSString = "string 2"
let lenx = x.count
let leny = y.count
查看更多
呛了眼睛熬了心
4楼-- · 2019-01-01 10:12

Swift 4 update comparing with swift 3

Swift 4 removes the need for a characters array on String. This means that you can directly call count on a string without getting characters array first.

"hello".count                  // 5

Whereas in swift 3, you will have to get characters array and then count element in that array. Note that this following method is still available in swift 4.0 as you can still call characters to access characters array of the given string

"hello".characters.count       // 5

Swift 4.0 also adopts Unicode 9 and it can now interprets grapheme clusters. For example, counting on an emoji will give you 1 while in swift 3.0, you may get counts greater than 1.

"                                                                    
查看更多
弹指情弦暗扣
5楼-- · 2019-01-01 10:13

in Swift 2.x the following is how to find the length of a string

let findLength = "This is a string of text"
findLength.characters.count

returns 24

查看更多
大哥的爱人
6楼-- · 2019-01-01 10:13

Here is what I ended up doing

let replacementTextAsDecimal = Double(string)

if string.characters.count > 0 &&
    replacementTextAsDecimal == nil &&
    replacementTextHasDecimalSeparator == nil {
        return false
}
查看更多
姐姐魅力值爆表
7楼-- · 2019-01-01 10:15

For XCode 7.3 and Swift 2.2.

let str = "                                                                    
查看更多
登录 后发表回答