我正在为我的第一个应用完成教程(学习 Swift):www.appcoda/search-bar-tutorial-ios7/
I'm working through the tutorial here (learning Swift) for my first app: www.appcoda/search-bar-tutorial-ios7/
我被困在这部分(Objective-C 代码):
I'm stuck on this part (Objective-C code):
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText]; searchResults = [recipes filteredArrayUsingPredicate:resultPredicate]; }谁能建议如何在 Swift 中为 NSPredicate 创建等效项?
Can anyone advise how to create an equivalent for NSPredicate in Swift?
推荐答案这实际上只是一个语法转换.好的,所以我们有这个方法调用:
This is really just a syntax switch. OK, so we have this method call:
[NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];在 Swift 中,构造函数跳过了blahWith..."部分,只使用类名作为函数,然后直接进入参数,所以 [NSPredicate predicateWithFormat: ...] 将变成 NSPredicate(格式:……).(再举个例子,[NSArray arrayWithObject: …] 会变成 NSArray(object: …).这是 Swift 中的常规模式.)
In Swift, constructors skip the "blahWith…" part and just use the class name as a function and then go straight to the arguments, so [NSPredicate predicateWithFormat: …] would become NSPredicate(format: …). (For another example, [NSArray arrayWithObject: …] would become NSArray(object: …). This is a regular pattern in Swift.)
所以现在我们只需要将参数传递给构造函数.在 Objective-C 中,NSString 文字看起来像 @"",但在 Swift 中,我们只对字符串使用引号.所以这给了我们:
So now we just need to pass the arguments to the constructor. In Objective-C, NSString literals look like @"", but in Swift we just use quotation marks for strings. So that gives us:
let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)事实上,这正是我们在这里所需要的.
And in fact that is exactly what we need here.
(顺便说一句,您会注意到其他一些答案使用格式字符串,如 "name contains[c] (searchText)".这是不正确的.使用字符串插值,这与谓词格式不同,通常不适用于此.)
(Incidentally, you'll notice some of the other answers instead use a format string like "name contains[c] (searchText)". That is not correct. That uses string interpolation, which is different from predicate formatting and will generally not work for this.)
更多推荐
在 Swift 中使用谓词
发布评论