gpt4 book ai didi

swift - 对于 Swift 语言,初始化结构和初始化类有什么区别? (我对编程还很陌生)

转载 作者:可可西里 更新时间:2023-11-01 00:51:30 25 4
gpt4 key购买 nike

我正在使用 Swift 编程语言。这是代码:

class CalculatorBrain9iOS{

***bunch of code***
***bunch of code***

private var accumulator = 0.0
private var pending: PendingBinaryOperationInfo?

private struct PendingBinaryOperationInfo {
var binaryFunction: (Double, Double) -> Double
var firstOperand: Double
}

func ...(...) {
if let operation = ... {
switch operation {
case ...
case RandomFunction.ThisCase(let function):
pending = PendingBinaryOperationInfo(binaryFunction:
function,
firstOperand: accumulator)

}
}
}
***bunch of code***
}

我想将私有(private)结构 (PendingBinaryOperationInfo) 更改为一个类。它不需要继承,所以我想我可以用“类”替换“私有(private)结构”。但是我一直在该行收到初始化程序错误消息。严格来说是因为那个新类是嵌套类吗?还是有其他因素影响?

我想我的另一个大问题是:除了继承和值/引用之外,类和结构之间还存在哪些其他差异,以至于我不能只用类替换结构并仍然让程序运行完全没问题?

最佳答案

struct 会自动为您生成一个初始化程序来初始化所有属性。 class 不会为您合成构造函数,除非您为所有属性赋予初始值(或使用自动为 nil 的 Optionals)。在您的情况下,您需要编写自己的初始化程序:

class PendingBinaryOperationInfo {
var binaryFunction: (Double, Double) -> Double
var firstOperand: Double

init(binaryFunction: (Double, Double) -> Double, firstOperand: Double) {
self.binaryFunction = binaryFunction
self.firstOperand = firstOperand
}
}

您应该小心地将 struct 替换为数据的 class。它可能会导致意外结果,因为 class 是一个 reference 类型,而 struct 是一个 value 类型。

考虑这个例子:

class Coord {
var x = 0
var y = 0
}

// Create an array with 5 Coords
var coords = [Coord](count: 5, repeatedValue: Coord())

coords[0].x = 13
print(coords[1].x) // prints "13"

在这种情况下,数组 coords 包含 5same Coord 对象的引用。所以更新一个更新它们。

如果将 class 更改为 struct,则数组中将有 5 个不同的值,结果将打印 0

关于swift - 对于 Swift 语言,初始化结构和初始化类有什么区别? (我对编程还很陌生),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36955163/

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