gpt4 book ai didi

swift - 使用 Realm swift 初始化列表值

转载 作者:搜寻专家 更新时间:2023-11-01 06:26:54 25 4
gpt4 key购买 nike

我正在尝试初始化几个对象,其中包括列表对象,但我不确定确切的语义是什么。甚至可以从 Realm 对象中初始化 List 对象,还是我必须以其他方式附加它们?

class ResourcesData: Object {
@objc dynamic var resourceID = UUID().uuidString
@objc dynamic var name = "";

let valueSemantics = List<ValueSemantics>();

convenience init(resourceName: String, semantics: List<ValueSemantics>) {
self.init()
self.name = resourceName
self.valueSemantics = semantics
}

override static func primaryKey() -> String? {
return "resourceID"
}
}

带有初始值设定项的我的列表模型

class ValueSemantics: Object {
@objc dynamic var name = "";
@objc dynamic var value = 0;

convenience init(value: Int, valueName: String) {
self.init()
self.name = valueName
self.value = value
}
}

这是我尝试初始化我的对象的方式,但它抛出以下错误 '<' is not a postfix unary operator

let data: [ResourcesData] = [
ResourcesData(resourceName: "Iron ore",
semantics: List<
ValueSemantics(value: 0, valueName: "None"),
ValueSemantics(value: 1, valueName: "Average")
>
),
ResourcesData(resourceName: "Gold ore",
semantics: List<
ValueSemantics(value: 0, valueName: "None"),
ValueSemantics(value: 1, valueName: "Average")
>
)
];

do {
try realm.write {
realm.add(data);
}
}catch {
print("Error starting Realm! \(error)");
}

我也试过用下面的方式初始化它

ResourcesData(resourceName: "Gold ore",
semantics: List(
ValueSemantics(value: 0, valueName: "None"),
ValueSemantics(value: 1, valueName: "Average")
))

还有

ResourcesData(resourceName: "Gold ore",
semantics: [
ValueSemantics(value: 0, valueName: "None"),
ValueSemantics(value: 1, valueName: "Average")])

最佳答案

List 只有一个空的初始化程序,因此向 List 添加值的唯一方法是使用 append。您最好修改 ResourcesData 的初始化程序以接受 Array 并调用 append(contentsOf:) 将数组的元素添加到列表。

class ResourcesData: Object {
@objc dynamic var resourceID = UUID().uuidString
@objc dynamic var name = ""

let valueSemantics = List<ValueSemantics>()

convenience init(resourceName: String, semantics: [ValueSemantics]) {
self.init()
self.name = resourceName
self.valueSemantics.append(objectsIn: semantics)
}

override static func primaryKey() -> String? {
return "resourceID"
}
}

然后你可以像这样初始化它:

let data: [ResourcesData] = [
ResourcesData(resourceName: "Iron ore",
semantics: [ValueSemantics(value: 0, valueName: "None"),
ValueSemantics(value: 1, valueName: "Average")]
),
ResourcesData(resourceName: "Gold ore",
semantics: [ValueSemantics(value: 0, valueName: "None"),
ValueSemantics(value: 1, valueName: "Average")]
)
]

与您的问题无关,但您不应该在 Swift 中的行尾放置分号,这不是 Objective-C。

关于swift - 使用 Realm swift 初始化列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53121251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com