gpt4 book ai didi

swift - 协议(protocol)数组元素是按值传递还是按引用传递?

转载 作者:行者123 更新时间:2023-12-03 23:40:51 24 4
gpt4 key购买 nike

我知道在 Swift 中结构是按值传递的,类是按引用传递的。
我想知道我是否创建了一个提供协议(protocol)的数组存储元素。这些元素是通过值还是引用传递?
它是基于模型一个类或结构的定义吗?

class ClassA: ProtocolA {
// something
}

struct StructA: ProtocolA {
// something
}

var arr: [ProtocolA] = [ClassA(), StructA()]

exampleFunction(arr[0]) // is it passed by reference
exampleFunction(arr[1]) // is it passed by value

最佳答案

协议(protocol)应该被视为值类型,因为您需要通过将其定义为符合 AnyObject(所有类都符合)来明确告诉编译器它是引用类型
所以如果你有

protocol ProtocolB: AnyObject
那么任何符合 ProtocolB 的类型都将通过引用发送,否则不发送。
这是一个简化的例子
protocol ProtocolA {
var x: Int { get set }
}

protocol ProtocolB: AnyObject {
var y: Int { get set }
}

class ClassA: ProtocolA, ProtocolB {
var x = 0
var y = 0
}

func exampleFunction(_ object: ProtocolA) {
object.x += 2 // <-- This will generate a compilation error
}

func exampleFunction(_ object: ProtocolB) {
object.y += 2 // This is fine
}

关于swift - 协议(protocol)数组元素是按值传递还是按引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65954527/

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