Infinite Possibilities Infinite Possibilities - 1 year ago 116
Swift Question

Swift 3.0 Protocol instantiation

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

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

is a protocol and the
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 Source

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 {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download