swift - 执行被中断,原因:信号 SIGABRT
问题描述
我正在按照我正在关注的教程在操场上工作,并且我正在使用他们给我的文件(不更改它)。不幸的是,我收到此错误“执行被中断,原因:信号 SIGABRT”。
这是我的代码,错误出现在people.filtered(using: allAge61)
class APerson: NSObject { // Must inherit from NSObject or NSPredicate will fail at runtime
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
// description lets you pretty print this class' instances in the sidebar
override var description: String {
return self.name + " - \(self.age) years old"
}
}
/*:
and a bunch of People
*/
let groucho = APerson(name: "Groucho", age: 50)
let chicco = APerson(name: "Chicco", age: 61)
let harpo = APerson(name: "Harpo", age: 45)
let zeppo = APerson(name: "Zeppo", age: 61)
let people: NSArray = [groucho, chicco, harpo, zeppo]
// using a NSArray here because predicates work with them, not with regular Swift Arrays
/*:
we can get __all people of age == 61__ with a simple predicate
*/
let allAge61 = NSPredicate(format: "age = 61")
people.filtered(using: allAge61)
解决方案
NSPredicate 引用字符串“age”,但该类不符合“age”属性的键值编码。如果你这样上课:
class APerson: NSObject {
@objc let name: String
@objc let age: Int
然后你可以让它工作。KVC 是 Obj-C 运行时的特性,它可以让您从像“age”这样的字符串转到实际的年龄 getter/setter 方法,当它试图解析字符串“age = 61”并将“age”转换为“年龄函数”,因为该属性未标记为@objc
或者全部 Swifty:
struct Person: CustomStringConvertible {
let name: String
let age: Int
var description: String {
"\(name) - \(age) years old"
}
}
let groucho = Person(name: "Groucho", age: 50)
let chicco = Person(name: "Chicco", age: 61)
let harpo = Person(name: "Harpo", age: 45)
let zeppo = Person(name: "Zeppo", age: 61)
let people = [groucho, chicco, harpo, zeppo]
people.filter { $0.age == 61 }
推荐阅读
- ios - 重用的自定义 CollectionViewCells 保留旧的大小属性
- wordpress - 使用代码更改 woocommerce 网站上的文本
- python - 在网站上运行 Python 脚本(在后台)
- python - Python 'print' 函数 'sep' 参数未按预期工作
- python - pysyft torch.jit. 脚本 RuntimeError:未定义的值 _Reduction
- git - gitlab让加密http_authorization错误
- python - Python 找不到某些 Windows 可执行文件
- php - 是否有解决方案可以使用我添加的数据库中的选择选项重定向页面,并添加输入字段?
- c++ - C++ 中项目的 Xcode 11 完成行为
- python-3.x - 使用 BeautifulSoup 时迭代失败