您需要将%@ 更改为%i 并删除多余的括号:
这里的主要问题是您将Int 放置在期望String 的位置。
这是一个基于post的示例:
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,这可以通过字符串插值 或通过description 的description 属性来实现@ .. 假设:
变化:
let thisPredicate = NSPredicate(format: "age == %i", thisSection)
为
let thisPredicate = NSPredicate(format: "age == %@", thisSection.description)
或
let thisPredicate = NSPredicate(format: "age == %@", "\(thisSection)")
当然,你总是可以绕过这一步,选择更硬编码(但也是正确的)的东西:
let thisPredicate = NSPredicate(format: "sectionNumber == \(thisSection)")
但是考虑到一些奇怪的原因
字符串插值(这种结构:"\(thisSection)")导致保持循环,如here所述