Infinite Possibilities Infinite Possibilities - 8 days ago 6
Swift Question

Swift 3.0 Protocol instantiation

Here's my declaration of an array of command classes.

var commands: [IPICommand.Type] = [CLoginCommand.self]


IPICommand
is a protocol and the
CLoginCommand
is a class that implements the protocol. In the array now I have only one element, but there can be more.

After this I would like to instantiate one of the elements of the array:

let aCommand = commands[0]()


Currently the instantiation has issues: Cannot call value of non-function type 'IPICommand.Type'

Answer

You're trying to instantiate a IPICommand type, that is a protocol. To make it works, define an init method in your protocol declaration

protocol IPICommand {
    init()
}

In this way you can do commands[0](). I'd prefer to name the init in an another way, but this is up to you.