首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Swift:如何创建一个带有Int值的谓词?

Swift:如何创建一个带有Int值的谓词?
EN

Stack Overflow用户
提问于 2015-08-08 03:00:04
回答 3查看 18.1K关注 0票数 27

我在以下语句中收到一个EXC-BAD-ACCESS错误:

代码语言:javascript
复制
var thisPredicate = NSPredicate(format: "(sectionNumber == %@"), thisSection)

thisSection的Int值为1,当我将鼠标悬停在它上面时会显示值1。但在调试区域,我看到了以下内容:

代码语言:javascript
复制
thisPredicate = (_ContiguousArrayStorage ...)

另一个使用字符串的谓词显示为ObjectiveC.NSObject为什么会发生这种情况?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-08-08 03:18:30

如果您的数据是安全的或经过清理的,您可以尝试使用字符串插值Swift Standard Library Reference。它看起来像这样:

代码语言:javascript
复制
let thisSection = 1
let thisPredicate = NSPredicate(format: "sectionNumber == \(thisSection)")
票数 34
EN

Stack Overflow用户

发布于 2015-08-08 03:20:29

您需要更改%i%@并删除多余的圆括号:

这里的主要问题是,您将一个Int放在它需要一个String的地方。

下面是一个基于此post的示例

代码语言:javascript
复制
class Person: NSObject {
    let firstName: String
    let lastName: String
    let age: Int

    init(firstName: String, lastName: String, age: Int) {
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }

    override var description: String {
        return "\(firstName) \(lastName)"
    }
}

let alice = Person(firstName: "Alice", lastName: "Smith", age: 24)
let bob = Person(firstName: "Bob", lastName: "Jones", age: 27)
let charlie = Person(firstName: "Charlie", lastName: "Smith", age: 33)
let quentin = Person(firstName: "Quentin", lastName: "Alberts", age: 31)
let people = [alice, bob, charlie, quentin]


let thisSection = 33
let thisPredicate = NSPredicate(format: "age == %i", thisSection)

let _people = (people as NSArray).filteredArrayUsingPredicate(thisPredicate)
_people

另一种解决方法是将thisSection的值设为String,这可以通过String Interpolation或通过Intdescription属性来实现。

更改:

代码语言:javascript
复制
let thisPredicate = NSPredicate(format: "age == %i", thisSection)

代码语言:javascript
复制
let thisPredicate = NSPredicate(format: "age == %@", thisSection.description)

代码语言:javascript
复制
let thisPredicate = NSPredicate(format: "age == %@", "\(thisSection)")

当然,您总是可以绕过这一步,使用更硬编码(但也正确)的方法,如下所示:

代码语言:javascript
复制
let thisPredicate = NSPredicate(format: "sectionNumber == \(thisSection)")

但考虑到出于某种奇怪的原因,字符串插值(这种结构:"\(thisSection)")导致保留声明的循环here

票数 35
EN

Stack Overflow用户

发布于 2020-01-10 23:03:10

在64位架构上,Int映射到Int64,如果它的值大于2,147,483,648,%i将溢出。

您需要将%@更改为%ld,并删除多余的圆括号。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31884863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档