Swift String length property

Swift的String居然没有length属性,好难受,每次要获取String的字符串长度都要借助全局函数countElements。


没办法。仅仅有扩展String结构体,给它加入一个属性了。


import Foundation

extension String {
    
    // readonly computed property
    var length: Int {
        return countElements(self)
    }
}

        let a = "hechengmen"
        
        println(a.length)    // 10

只是须要注意的是,与Objective-C不同的是。swift用的不是category。而是extension,而且extension没有名字哦。另外extension仅仅能加入computed property。不能加入stored property或者property observer。

只是,后来发如今String的扩展中,提供了一个和Objective-C String的length相应属性

    /// Returns the number of Unicode characters in the `String`.
    var utf16Count: Int { get }

所以感觉没有必要自己定义一个length属性了。以后就直接用utf16Count属性吧。

(这名字真别扭)


println(a.utf16Count) // 10


原文地址:https://www.cnblogs.com/bhlsheji/p/5058906.html