gpt4 book ai didi

Swift:将类型作为参数发送并将变量的类型与其进行比较

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

我想实现这样一个功能:

protocol Base {
var value: Int { get set }
}
class ObjectTypeA: Base {
var value: Int = 0
}
class ObjectTypeB: Base {
var value: Int = 1
}

var objects: [Base] = [ObjectTypeA(), ObjectTypeB()]
func updatePropertyForType(type: Base.Type, value: Int) {
objects.filter({ $0 is type }).forEach { // <<< ERROR IS HERE
var object = $0
object.value = value
}
}
updatePropertyForType(ObjectTypeB.self, value: 10)

但是有一个错误:

'type' is not a type

请帮我解决一下。

最佳答案

参见 this answer :

protocol Base: AnyObject {
var value: Int { get set }
}
class ObjectTypeA: Base {
var value: Int = 0
}
class ObjectTypeB: Base {
var value: Int = 1
}

var objects: [Base] = [ObjectTypeA(), ObjectTypeB()]
func updatePropertyForType(type: Base.Type, value: Int) {
objects.filter({let item = $0; return type === item.dynamicType }).forEach {
$0.value = value
}
}

调用它:

updatePropertyForType(ObjectTypeA.self, value: 3)

关于Swift:将类型作为参数发送并将变量的类型与其进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38049467/

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