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

Calling a function of an Object that takes a function as it's 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)