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

Ios 包含在Swift中放入自己的方法时语法不同的位置,ios,swift,string,contains,Ios,Swift,String,Contains,我试图将一个方法中的一些代码重构成它自己的方法,但编译器却在抱怨 这段代码在较长的方法中运行良好 let aboutLocation = self.locationWords.contains(where: {$0.caseInsensitiveCompare((newmessage)!) == .orderedSame}) if (aboutLocation) { self.startLocationServices() } 当我尝试按如下方式将代码放在它自己的方法中时,它会给出错

我试图将一个方法中的一些代码重构成它自己的方法,但编译器却在抱怨

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

let aboutLocation = self.locationWords.contains(where: {$0.caseInsensitiveCompare((newmessage)!) == .orderedSame})

if (aboutLocation) {
    self.startLocationServices()
}
当我尝试按如下方式将代码放在它自己的方法中时,它会给出错误消息:调用中的无关参数标签“where”,并建议我删除该单词

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

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

为什么一种方法与另一种方法不同?错误是误导性的

在函数中,参数newmessage是非可选的,因此无论如何,您都必须删除感叹号和圆括号(也在if条件周围)

let aboutLocation = self.locationWords.contains(where: {$0.caseInsensitiveCompare(newmessage) == .orderedSame})
if aboutLocation { ...
但您确实可以使用尾随闭包语法省略where参数标签

let aboutLocation = locationWords.contains{ $0.caseInsensitiveCompare(newmessage) == .orderedSame }

首先,您试图强制展开它本身通常是一件坏事,newmessage,它甚至不是可选的。当我调用此函数时,我从一个展开的变量开始。如果newmessage可以安全地强制展开,那么函数的声明就可以了。否则,是否将newmessage参数声明为字符串?并添加一条警戒线Swift编译器的错误消息通常很糟糕。你必须记住翻译编译器对Derp说的任何内容?有点不对劲。你自己想出来。在某些方面,这样做会更好,因为您收到的错误消息通常非常具体、非常技术性,并且完全错误。