包含在 Swift 中放置在自己的方法中时语法不同的地方

Contains where syntax different when placed in own method in Swift

我试图将一些代码从一种方法重构为它自己的方法,但编译器在抱怨。

此代码在较长的方法中运行良好

let aboutLocation = self.locationWords.contains(where: {[=11=].caseInsensitiveCompare((newmessage)!) == .orderedSame})

if (aboutLocation) {
    self.startLocationServices()
}

当我尝试将代码放入其自己的方法中时,它会给出错误消息:Extraneous argument label 'where' in call 并建议我删除该词。

func startLocationServicesIfLocation(newmessage:String){
    let aboutLocation = self.locationWords.contains(where: {[=12=].caseInsensitiveCompare((newmessage)!) == .orderedSame})

    if (aboutLocation) {
        self.startLocationServices()
    }
}

为什么一种方法内部与另一种方法不同

该错误具有误导性。

在函数中,参数 newmessage 是非可选的,因此您必须删除感叹号(以及括号 - 也围绕 if 条件 - 无论如何)。

let aboutLocation = self.locationWords.contains(where: {[=10=].caseInsensitiveCompare(newmessage) == .orderedSame})
if aboutLocation { ...

但您确实可以使用尾随闭包语法省略 where 参数标签

let aboutLocation = locationWords.contains{ [=11=].caseInsensitiveCompare(newmessage) == .orderedSame }