在Swift中使用谓词

编程入门 行业动态 更新时间:2024-10-11 19:14:03
本文介绍了在Swift中使用谓词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在学习这个教程(学习Swift)我的第一个应用程序: http ://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(对象:...)。这是一个常规的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中使用谓词

本文发布于:2023-11-30 14:37:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:谓词   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!