对成员'+'的含糊引用-尝试在String扩展内递增整数变量

时间:2019-05-05 14:34:28

标签: ios swift

我在String扩展中具有以下实例函数:

func numberOfCharactersInATweet(withShortURLLength shortURLLength:UInt, andShortURLLengthHTTPS shortURLLengthHTTPS:UInt) -> NSInteger {
    var numCharacters = 0
    let stringLength = self.count
    self.enumerateSubstrings(in: Range(NSMakeRange(0, stringLength))!, options: NSString.EnumeratingOptions.byComposedCharactersSequences) { (subString, subStringRange, enclosingRange, stop) in
        numCharacters = numCharacters + 1
        (Ambiguous reference to member '+')
    }

    return numCharacters
}

我想我知道我为什么收到该消息。这是因为我想增加一个整数变量,但是该成员'+'在我扩展的String类中也定义为串联运算符。我该如何告诉将“ +”成员用于整数?

1 个答案:

答案 0 :(得分:2)

我怀疑这是否与任何+覆盖有关。就目前情况而言,没有这样的覆盖,我无法编译您的代码。它似乎是一个非常奇怪的Swift版本。通过进行一些更正,我得以使其在Swift 5中的String扩展中进行编译:

func numberOfCharactersInATweet(withShortURLLength shortURLLength:UInt, andShortURLLengthHTTPS shortURLLengthHTTPS:UInt) -> NSInteger {
    var numCharacters = 0
    let stringLength = self.utf16.count
    let range = self.startIndex..<self.endIndex
    self.enumerateSubstrings(in: range, options: .byComposedCharacterSequences) { (subString, subStringRange, enclosingRange, stop) in
        numCharacters = numCharacters + 1
    }
    return numCharacters
}

但是,您的代码极其奇怪。任何参数(shortURLLengthshortURLLengthHTPPSsubStringsubStringRangeenclosingRangestop都没有使用。正如罗布·纳皮尔(Rob Napier)在评论中指出的那样,很难看出此String扩展的用途是什么。您要做的只是数字符。这应该是Objective-C方法的Swift转换吗?如果是这样,则不需要它。如果您只想知道合成Unicode中的字符数,那么在现代Swift中,就是字符串的count

let s = "This is a string  with some emoji in it ."
print(s.count)
print(s.numberOfCharactersInATweet(withShortURLLength: 0, andShortURLLengthHTTPS: 0))
// both give "43"