我正在为我的第一个应用完成教程(学习 Swift): http://www.appcoda.com/search-bar-tutorial-ios7/
我被困在这部分(Objective-C 代码):
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
searchResults = [recipes filteredArrayUsingPredicate:resultPredicate];
}
谁能建议如何在 Swift 中为 NSPredicate 创建等效项?
最佳答案
这实际上只是一个语法切换。好的,所以我们有这个方法调用:
[NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
在 Swift 中,构造函数跳过“blahWith...”部分,只使用类名作为函数,然后直接进入参数,因此 [NSPredicate predicateWithFormat: ...]
将变为 NSPredicate(格式:…)
。 (再举一个例子,[NSArray arrayWithObject: …]
会变成 NSArray(object: …)
。这是 Swift 中的常规模式。)
所以现在我们只需要将参数传递给构造函数。在 Objective-C 中,NSString 字面量看起来像 @""
,但在 Swift 中,我们只是为字符串使用引号。所以这给了我们:
let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)
事实上,这正是我们所需要的。
(顺便说一句,您会注意到其他一些答案使用格式字符串,例如 "name contains[c]\(searchText)"
。这是不正确的。使用字符串插值,这与谓词格式不同,通常不适用于此。)
关于ios - 在 Swift 中使用谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24176605/