简体   繁体   中英

How to declare protocol constrainted generic variable in Swift?

I need to create a dictionary variable where my value will be of SomeOtherClass class and conforms to SomeProtocol . This equals to the following declaration in Objective-C:

NSMutableDictionary<SomeClass *, SomeOtherClass<SomeProtocol> *> *someOtherBySome;

So, is it possible to do it in the same simple way using Swift?

I need it because I can create func with signature:

func someFunc<T: SomeOtherClass where T: SomeProtocol>(param: T, otherParam: String)

and I want to get values for param parameter from Dictionary without type casting.

Short answer

In Swift you cannot declare a variable of a given class and conform to a protocol .

Possible solution (?)

However given the definitions you already have

class SomeClass: Hashable {
    var hashValue: Int { return 0 } // your logic goes here
}

func ==(left:SomeClass, right:SomeClass) -> Bool {
    return true // your logic goes here
}

class SomeOtherClass {}
protocol SomeProtocol {}

maybe you can solve your problem simply making SomeOtherClass conform to SomeProtocol

extension SomeOtherClass: SomeProtocol { }

Now you can simply

var dict : [SomeClass: SomeOtherClass] = [SomeClass(): SomeOtherClass()]

let someProtocolValue: SomeProtocol = dict.values.first!

Does it help you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM