gpt4 book ai didi

swift - 以字符串为键、通用类为值的字典

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:21 26 4
gpt4 key购买 nike

我有 socket 和插头,插头属于任何通用类型。现在我想将任何类型的插头存储到字典中。我试图以我能想到的所有方式在字典中声明插件的可能类型。没有工作。我只找到传递任何 Value T 的解决方案,而不是任何泛型类型的类。我也担心我的用词在所有情况下都不正确。我说错了什么?

例子会把事情搞清楚。那么我如何将这个 Plugs 存储到 socket 的字典“plugs”中:

import Foundation

class AClass {

}

class BClass {

}

class Plug<T> {
init() {

}
}

class Socket {
var plugs = [ String: Plug ]() // should accept any Plug
init() {

}
func addPlug( plug : Plug ) { // should accept any Plug
self.plugs["A"] = plug // should accept any Plug
}
}

var plugDouble = Plug<Double>()
var plugString = Plug<String>()
var plugAClass = Plug<AClass>()
var plugBClass = Plug<BClass>()

var socket = Socket()
socket.addPlug(plug: plugDouble ); // should accept any Plug
socket.plugs["A"] = plugDouble // should accept any Plug

最佳答案

创建一个基类(我们称它为 BasePlug),所有 Plug 类都将派生自该基类。让你的字典存储 BasePlug 类的项目:

class BasePlug {

}

class AClass {

}

class BClass {

}

class Plug<T> : BasePlug {

}

class Socket {
var plugs = [ String: BasePlug ]() // should accept any Plug
init() {

}
func addPlug( plug : BasePlug ) { // should accept any Plug
self.plugs["A"] = plug // should accept any Plug
}
}

var plugDouble = Plug<Double>()
var plugString = Plug<String>()
var plugAClass = Plug<AClass>()
var plugBClass = Plug<BClass>()

var socket = Socket()
socket.addPlug(plugDouble ); // should accept any Plug
socket.plugs["A"] = plugDouble // should accept any Plug

关于swift - 以字符串为键、通用类为值的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28250294/

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