在 Swift 中使用谓词

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

我正在为我的第一个应用完成教程(学习 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 中使用谓词

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

发布评论

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

>www.elefans.com

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