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

标签 ios swift string contains

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

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

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

if (aboutLocation) {
    self.startLocationServices()
}

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

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 }

关于ios - 包含在 Swift 中放置在自己的方法中时语法不同的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52932556/

相关文章:

objective-c - 在 ios 延迟后启动 UIActivityIndi​​cator

ios - 在 Swift 中使用 MagicalRecord 实例化的向下转换 CoreData 实体

ios - 如何将 Parse SDK 与 Xcode 7 和 iOS 9 结合使用

Java 代码到 Swift 转换器

c++ - 我如何告诉 gcc 警告我字符串被分配了一个整数值?

objective-c - 无法启动iOS应用

ios - 结合 Cocoapods 和 Carthage

r - 如何将 dplyr 操作与列名的字符串列表一起使用

linux - 如何在 unix 操作系统中搜索文件中不包含特定字符串的行?

ios - 通过应用程序 ID 启动 iOS 应用程序?