Swift 1.2和Swift 2.0中的字符串长度

Mol*_*nda 32 string swift

在以前版本的Swift中,我有以下代码.

func myfunc(mystr: String) {
    if mystr.utf16Count >= 3 {
Run Code Online (Sandbox Code Playgroud)

随着最新版本的Swift 1.2,我现在收到以下错误.

'utf16Count' is unavailable: Take the count of a UTF-16 view instead, i.e. count(str.utf16)
Run Code Online (Sandbox Code Playgroud)

好的,所以我按如下方式更改了我的代码.

func myfunc(mystr: String) {
    if count(mystr.utf16) >= 3 {
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我现在得到以下错误消息.

'(String.UTF16View) -> _' is not identical to 'Int16'
Run Code Online (Sandbox Code Playgroud)

使用Swift 1.2获取字符串长度的正确方法是什么?

Dha*_*esh 87

您可以使用扩展名,如:

extension String {
     var length: Int { return count(self)         }  // Swift 1.2
}
Run Code Online (Sandbox Code Playgroud)

你可以使用它:

if mystr.length >= 3 {

}
Run Code Online (Sandbox Code Playgroud)

或者您可以直接计算:

if count(mystr) >= 3{

}
Run Code Online (Sandbox Code Playgroud)

这对我也有用:

if count(mystr.utf16) >= 3 {

}
Run Code Online (Sandbox Code Playgroud)

对于Swift 2.0:

extension String {
    var length: Int {
        return characters.count
    }
}
let str = "Hello, World"
str.length  //12
Run Code Online (Sandbox Code Playgroud)

另一个扩展:

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

如果你想直接使用:

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
Run Code Online (Sandbox Code Playgroud)


pie*_*e23 23

您必须使用包含属性计数的characters属性:

yourString.characters.count


que*_*ful 7

Swift 2.0 UPDATE

extension String {
    var count: Int { return self.characters.count }
}
Run Code Online (Sandbox Code Playgroud)

使用:

var str = "I love Swift 2.0!"
var n = str.count
Run Code Online (Sandbox Code Playgroud)

有用的编程技巧和黑客


BLC*_*BLC 6

这里有一个 - 从这里复制

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
}
Run Code Online (Sandbox Code Playgroud)