如何从viewcontroller发送变量以由另一个viewcontroller修改?
我已经尝试在performSegue中设置变量,但它没有被修改。
示例代码:
class VC1: ViewController{
var myVar: MyVar
....
prepare(for segue:...) {
let nextVC = segue.destination as! VC2
nextVC.var = myVar
}
....
}
class VC2: ViewController {
var var: MyVar
....
override func viewDidLoad() {
super.viewDidLoad()
var = MyVar("newValue")
}
}
执行此代码后,VC1中myVar
的值不会更改为新值。我相信它只会得到myVar
的浅层副本,而不是深层副本。
我想要在swift中实现什么?
答案 0 :(得分:3)
Swift中的类是通过引用传递的,而结构是按值传递的。假设MyVar是一个类,您需要修改类的属性,即:
myVar.property = "xyz"
而不是像你在问题中那样定义一个新的类实例。
答案 1 :(得分:0)
设置var
时,会将新实例分配给# extract the part that interest us
grok {
match => {
"message" => "%{GREEDYDATA}Metrics :\[%{GREEDYDATA:Metrics}\]"
}
}
# divide each event in multiple events, depending on the contents of the Metrics field
split {
field => "Metrics"
terminator => "], Metric ["
target => "metric"
}
# removing things left behind when splitting the Metrics field.
mutate {
gsub => ["metric", "Metric \[", "",
"metric", "\]", ""]
}
# apply the kv filter, extracting key-value pairs from the metric field
kv {
source => "metric"
field_split => ","
}
。
答案 2 :(得分:0)
在游乐场中检查以下代码的结果。它应该让您更深入地了解您应该期待什么,而不会出现segue和控制器的复杂性。
class Variable {
var name:String
init(_ nameString:String) {
name = nameString
}
}
class Sender {
var myVar = Variable("Start name")
func showChanges() {
let receiver = Receiver(myVar)
print(myVar.name)
receiver.modify()
print(myVar.name)
receiver.replace()
print(myVar.name)
}
}
class Receiver {
var received: Variable
init(_ variable:Variable) {
received = variable
}
func modify() {
received.name = "Changed name"
}
func replace() {
received = Variable("New variable")
}
}
let s = Sender()
s.showChanges()