gpt4 book ai didi

swift - 按值分配变量,而不是按引用

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

复制的最佳方法是什么,而不是struct变量而不引用它的内存位置。

例如

    class Person {
var name: String = ""
var age: Int = 0

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

var mapped: [String: Any] {
return [
"name": self.name,
"age": self.age
]
}
}

var person: Person = Person(name: "Hitchhiker", age: 42)

var personCopy = person

var dictionary: [String: Any] {
return [
"a_person": person.mapped,

"c_personCopy": personCopy.mapped
]
}

print("Original:", dictionary.jsonStringValue)

person.age = 100
person.name = "Guide"

print("\n\n========\n\n")
print("Edit 1:", dictionary.jsonStringValue)

personCopy.age = 200
personCopy.name = "To the Galaxy"

print("\n\n========\n\n")
print("Edit 2:", dictionary.jsonStringValue)

// I have this swift extension to make my logs better, don't mind the implicit unwrapping.
extension Dictionary {
var jsonStringValue: String {
let jsonData = try! JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String(data: jsonData, encoding: String.Encoding.utf8)!
}
}

这将打印如下所示的输出。

Original: {
"a_person" : {
"name" : "Hitchhiker",
"age" : 42
},
"c_personCopy" : {
"name" : "Hitchhiker",
"age" : 42
}
}


========


Edit 1: {
"a_person" : {
"name" : "Guide",
"age" : 100
},
"c_personCopy" : {
"name" : "Guide",
"age" : 100
}
}


========


Edit 2: {
"a_person" : {
"name" : "To the Galaxy",
"age" : 200
},
"c_personCopy" : {
"name" : "To the Galaxy",
"age" : 200
}
}

如果我操纵副本的值,原件也会更新,因为副本是通过引用分配的。

我知道我可以创建类似扩展函数的东西,它制作原始变量的副本,就像这样。

extension Person {
func copy() -> Person {
return Person(name: self.name, age: self.age)
}
}

var person = Person(name: "Jon Snow", age: 0)
var personCopy = person.copy()
personCopy.name = "Jon Targaryen" // this is now a value copy.

但是,如果不为许多不同的模型创建大量样板代码,我如何才能更轻松地做到这一点?

更新:

我知道我可以在这里使用 Swift 协议(protocol),例如

protocol Copying {
init(original: Self)
}

extension Copying {
func copy() -> Self {
return Self.init(original: self)
}
}

我在这个 answer 中看到的,但是我必须将我的模型类子类化为这些类,这可能会导致一些问题,因为我的模型已经是一个子类并且它希望我实现其中一些样板 initializers 我不想这样

最佳答案

类是引用类型。获取副本的唯一方法是定义一个 copy 方法,或者创建一个 init 方法来复制另一个实例(这与你的 copy 方法)。

只要不需要继承,您真的应该考虑将模型类设为 struct 而不是 class。然后您会自动获得复制语义。

关于swift - 按值分配变量,而不是按引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45667521/

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