Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift array of struct types conforming to protocol

I have a series of several structs conforming to MyProtocol. I need an array of these structs' types (because they have a static method declared in MyProtocol that I need to be able to access). I have tried all kinds of things but I can't make Xcode like it.

Also, before this is marked as dupe – I tried this, but all I got was:

//Foo and Bar are structs conforming to MyProtocol

let MyStructArray: Array<MyProtocol.self> = [Foo.self, Bar.self]
//Protocol 'MyProtocol' can only be used as a generic constant because it has Self or associated type requirements
like image 720
Garrett Avatar asked Jan 08 '23 09:01

Garrett


2 Answers

How about this?:

protocol MyProtocol {
    static func hello()
}

struct Foo: MyProtocol {
    static func hello() {
        println("I am a Foo")
    }
    var a: Int
}

struct Bar: MyProtocol {
    static func hello() {
        println("I am a Bar")
    }
    var b: Double
}

struct Baz: MyProtocol {
    static func hello() {
        println("I am a Baz")
    }
    var b: Double
}

let mystructarray: Array<MyProtocol.Type> = [Foo.self, Bar.self, Baz.self]

(mystructarray[0] as? Foo.Type)?.hello()  // prints "I am a Foo"

for v in mystructarray {
    switch(v) {
    case let a as Foo.Type:
        a.hello()
    case let a as Bar.Type:
        a.hello()
    default:
        println("I am something else")
    }
}

// The above prints:
I am a Foo
I am a Bar
I am something else
like image 147
vacawama Avatar answered Jan 15 '23 18:01

vacawama


I found the problem. My protocol was inheriting from RawOptionSetType. Not sure why that caused an issue, but commenting that inheritance out made it work. Weird.

like image 31
Garrett Avatar answered Jan 15 '23 19:01

Garrett