mercredi 11 mai 2016

swift reflections: how to construct a new struct instance based on reflections?

My example consists of:

  • protocol with read-only properties
  • struct implementing that protocol
  • "+" operator function

I'd like the "+" operator to be able to work for all implementations of the protocol by creating a new instance of the specific type that implements that protocol.

As you can see in the source code below, the operator accepts parameters of type "Aable" (the protocol). Using "dynamicType" on one of the parameters to determine the actual type to construct a new instance fails with the error "'Aable' cannot be constructed because it has no accessible initializers". However, the dynamicType of both parameters is "A" (in this example).

Is that even possible?

Could it be achieved using reflections or some sort of introspection?

protocol Aable {
    var name: String { get }
}

enum AableError: ErrorType {
    case OperatorTypesNotEqual
}

func +(left: Aable, right: Aable) throws -> Aable {
    guard left.dynamicType == right.dynamicType else {
        throw AableError.OperatorTypesNotEqual
    }

    let leftType = left.dynamicType
    //error: 'Aable' cannot be constructed because 
    //       it has no accessible initializers
    return leftType(name: left.name + right.name)
}

struct A: Aable {
    let name: String
}

let a1 = A(name: "A #1")
let a2 = A(name: "A #2")

try a1 + a2





Aucun commentaire:

Enregistrer un commentaire