gpt4 book ai didi

快速修改结构的通用属性

转载 作者:行者123 更新时间:2023-11-28 15:23:53 24 4
gpt4 key购买 nike

我有一个结构,它有一个通用属性,对自定义协议(protocol)有类型约束。这个协议(protocol)是空的,它的唯一目的是确保只有特定类型的元素可以存储在这个通用变量中:

protocol MyProtocol {}

struct TypeA: MyProtocol {
someProperty: String
}

struct TypeB: MyProtocol {
someOtherProperty: Int
}

var a = TypeA(someProperty: "text")
var b = TypeB(someOtherProperty: 5)

// The following is the actual struct in question:

struct Item {
var something: Int
var elementOfTypeAorB: MyProtocol
}

var firstItem = Item(something: 10, elementOfTypeAorB: a)
var secondItem = Item(something: 3, elementOfTypeAorB: b)

当我想访问我的“基础”结构 TypeA 或 TypeB 的属性时,我必须将它们转换为它们的原始类型:

print((secondItem.elementOfTypeAorB as! TypeB).someOtherProperty)  // 5

我现在想要一个函数来检查属性是否属于 TypeB,如果是,则更改值,这样函数体可以读取:

if type(of: secondItem.elementOfTypeAorB) == TypeB.self {
(firstItem.elementOfTypeAorB as! TypeB).someOtherProperty+=5
}

但我收到一条错误消息:变异运算符的左侧具有不可变类型“Int”

如果我将 TypeA 和 TypeB 结构更改为类,我可以这样做:

if type(of: secondItem.elementOfTypeAorB) == TypeB.self {
var modify = (secondItem.elementOfTypeAorB as! TypeB)
modify.someOtherProperty+=5
}

由于类是引用类型,secondItem... 的原始 someOtherProperty 将被更改,但即使是 a.someOtherProperty 也会更改(后者无关紧要,因为这里的 a 和 b 只是辅助变量。

但是如果我想留在结构域中,我发现改变通用 elementOfTypeAorB 属性的唯一方法是将它们向下转换为一个新变量,更改此变量并将整个变量写回到更高的 -级别结构,例如:

secondItem.elementOfTypeAorB = modify

这很好用,但在我的实际项目中,TypeA 和 TypeB 结构不仅包含一个属性,因此每次我只想更改其中一个时,必须复制整个结构,然后再次替换这个修改过的副本的整个结构对我来说似乎相当昂贵。

那么,是否有另一种方法可以更改我尚未遇到的通用结构的属性?

最佳答案

你必须执行一个可选的转换:

if var elementA = elementOfTypeAorB as? TypeA {
elementA.someProperty = ...
elementOfTypeAorB = elementA
} else if var elementB = elementOfTypeAorB as? TypeB {
elementB.someOtherProperty = ...
elementOfTypeAorB = elementA
}

另外,不要使用 type(of: value) == Type 检查类型,您应该使用 value is Type

或者,考虑使用具有关联值的枚举。它更适合您的用例,因为协议(protocol)应该用于定义可用于与实例交互的接口(interface)。

enum AorB {
case a(TypeA)
case b(TypeB)
}

这允许您将变量的类型限制为 TypeA 和 TypeB。

然后您可以使用 switch caseif case 语句来解包值:

switch elementOfTypeAorB {
case .a(var elementA):
elementA.someProperty = ...
elementOfTypeAorB = .a(elementA)
case .b(var elementB):
elementB.someOtherProperty = ...
elementOfTypeAorB = .b(elementB)
}

关于快速修改结构的通用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45556553/

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