zoukankan      html  css  js  c++  java
  • 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


  • 相关阅读:
    刘汝佳,竖式问题
    二叉树
    sort
    hash
    贪心算法
    FFT,NTT 专题
    hdu 5861 Road 两棵线段树
    hdu 5862 Counting Intersections
    hdu 5833 Zhu and 772002 ccpc网络赛 高斯消元法
    hdu 5800 To My Girlfriend + dp
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5058906.html
Copyright © 2011-2022 走看看