swift – 字典,字符串为键,通用类为值

我有插座和插头,插头是任何通用类型.现在我想将任何类型的插件存储到字典中.我试图以我能想到的各种方式声明字典中插件的可能类型.没有用.我只找到传递任何Value T的解决方案,但不是任何泛型类的类.此外,我担心在所有情况下我使用的单词都不对.我说错了什么?

示例将清除事情.
那么我怎么能将这个插件存储到套接字的字典“插件”中:

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

最佳答案 创建一个所有Plug类将派生自的基类(我们称之为BasePlug).让您的词典存储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
点赞