在Swift中使用谓词 [英] Using Predicate in Swift

查看:138
本文介绍了在Swift中使用谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习这个教程(学习Swift)我的第一个应用程序:
http ://www.appcoda.com/search-bar-tutorial-ios7/

I'm working through the tutorial here (learning Swift) for my first app: http://www.appcoda.com/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(对象:...)。这是一个常规的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中使用谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆