首页 > 编程语言 > 详细

Swift String length property

时间:2015-12-19 13:41:19      阅读:439      评论:0      收藏:0      [点我收藏+]

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


Swift String length property

原文:http://www.cnblogs.com/bhlsheji/p/5058906.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!