String的长度作为String的扩展名

时间:2015-04-09 20:10:36

标签: ios xcode swift count

我知道会有很多指向重复的指针,但是在我更新到xcode 6.3之前这已经有效了,现在它有问题。

剧本:

extension String {

    func removeCharsFromEnd(count:Int) -> String {
        var getSelf = self as String
        var stringLength = count(getSelf.utf16)

        let substringIndex = (stringLength < count) ? 0 : stringLength - count

        return self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

错误:无法调用&#39;计数&#39;使用类型列表的参数&#39;(String.UTF16View)&#39;


我还想指出,这种新的计数方法适用于我用过的其他地方(在此扩展之外)。

提前致谢。

2 个答案:

答案 0 :(得分:5)

count是您的扩展方法参数的名称并隐藏了 Swift库函数count()。您可以重命名参数 或致电

var stringLength = Swift.count(getSelf.utf16)

明确。

但请注意,计算UTF-16代码单元的数量在这里是错误的,它应该是

var stringLength = Swift.count(getSelf)

计算字符串中的字符数,因为那是什么 advance()也很重要。您可以使用

轻松验证
let foo = "".removeCharsFromEnd(1)
println(foo)

以下是您的方法的简化版本:

extension String {

    func removeCharsFromEnd(count : Int) -> String {
        precondition(count >= 0, "Attempt to call removeCharsFromEnd() with a negative count")
        // Decrement `endIndex` by `count`, but not beyond `startIndex`:
        let idx = advance(self.endIndex, -count, self.startIndex)
        return self.substringToIndex(idx)
    }
}

使用具有负距离的advance()的三参数版本。

更新 Swift 2 / Xcode 7:

extension String {

    func removeCharsFromEnd(count : Int) -> String {
        precondition(count >= 0, "Attempt to call removeCharsFromEnd() with a negative count")
        // Decrement `endIndex` by `count`, but not beyond `startIndex`:
        let idx = self.endIndex.advancedBy(-count, limit: self.startIndex)
        return self.substringToIndex(idx)
    }
}

答案 1 :(得分:2)

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"
"".removeCharsFromEnd(1)             // ""

你也可以使用下标:

extension String {
    subscript(index: Int) -> String? {
        guard index >= 0 && index < characters.count else { return nil }
        return String(self[startIndex.advancedBy(index)])
    }
    subscript(range: Range<Int>) -> String? {
        guard
            range.startIndex >= 0 &&
            range.endIndex <= characters.count &&
            startIndex.advancedBy(range.endIndex) <= endIndex &&
            startIndex.advancedBy(range.startIndex) >= startIndex &&
            range.startIndex.distanceTo(range.endIndex) <= characters.count
        else { return nil }
        return self[startIndex.advancedBy(range.startIndex)..<startIndex.advancedBy(range.endIndex)]
    }
}

"Hello, playground"[0...4] // "Hello"
"Hello, playground"[5]      // ","
"Hello, playground"[7...16]  // "playground"

""[1]  // ""