Oliver-R Oliver-R - 1 year ago 63
Swift Question

Calling a function of an Object that takes a function as its parameter

Say I have the following code:

import Foundation

enum Operation {
case BinaryOperation ((Double, Double) -> Double)

var multiply = Operation.BinaryOperation({$0 * $1})

//Error: Cannot call value of non-function type 'Operation'

How would I call the function multiply here?

Answer Source

Your function is the associated value of an enum value, so you have to extract it first before calling it. One way to do that is to use pattern matching:

if case let .BinaryOperation(function) = multiply {
    function(3.0, 2.0)

This can also be written as:

if case .BinaryOperation(let function) = multiply {
    function(3.0, 2.0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download