gpt4 book ai didi

Swift:如何存储对 Double、Int 的引用

转载 作者:可可西里 更新时间:2023-11-01 02:19:04 24 4
gpt4 key购买 nike

我想在 Swift 中存储对基本类型 (Double, Int) 的引用,这样我一个变量改变了,另一个也改变了。这是一个例子:

class MyClass {
var value: Double?
}

var myValue = 1.0

var instance = MyClass()
instance.value = myValue // <-- how to set a reference?

myValue = 2.0 // => I want instance.value to change to 2.0
instance.value = 3.0 // => I want myValue to change to 3.0

这可能吗?

最佳答案

你可以使用类持有者:

class Ref<T> {
var value: T

init(_ value: T) {
self.value = value
}
}

或者尝试阅读 In-Out Parameters,也许它能以某种方式帮助您:

In-Out Parameters

Variable parameters, as described above, can only be changed within the function itself. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.

You write an in-out parameter by placing the inout keyword at the start of its parameter definition. An in-out parameter has a value that is passed in to the function, is modified by the function, and is passed back out of the function to replace the original value.

You can only pass a variable as the argument for an in-out parameter. You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified. You place an ampersand (&) directly before a variable’s name when you pass it as an argument to an inout parameter, to indicate that it can be modified by the function.

func swapTwoInts(inout a: Int, inout _ b: Int) {
let temporaryA = a
a = b
b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3"

关于Swift:如何存储对 Double、Int 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32624159/

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