Length of String as extension of String

后端 未结 2 443
独厮守ぢ
独厮守ぢ 2021-01-22 23:18

I know that there will be lots of pointers to duplicates but this worked before I updated to xcode 6.3 and now it has a problem with it.

The script:

exte         


        
相关标签:
2条回答
  • 2021-01-22 23:32
    var str = "Hello, playground"
    
    extension String {
        func removeCharsFromEnd(n:Int) -> String {
            return substringWithRange(Range(start: startIndex, end: advance(startIndex, count(self) < n ? 0 : count(self)-n )))
        }
    }
    
    "Hello, playground".removeCharsFromEnd(3)  // "Hello, playgro"
    "                                                                    
    0 讨论(0)
  • 2021-01-22 23:41

    count is the name of your extension method parameter and hides the Swift library function count(). You can rename the parameter or call

    var stringLength = Swift.count(getSelf.utf16)
    

    explicitly.

    But note that counting the number of UTF-16 code units is wrong here, it should be

    var stringLength = Swift.count(getSelf)
    

    to count the number of characters in the string, because that is what advance() also counts. You can verify that easily with

    let foo = "                                                                    
    0 讨论(0)
提交回复
热议问题