zsong zsong - 5 months ago 8
Swift Question

How to declare dictionary with functions as values and keyed by integer?

struct Test {
func isOk () -> Bool{
return true
}

var mapping: [Int: () -> Bool] = [
1: isOk
]

func test() -> Bool {
return mapping[1]()
}
}


I got this error:

Cannot convert value of type '(Test) -> () -> Bool' to expected dictionary value type '() -> Bool'


Any idea? Thanks!

Answer

You're seeing this weird type ((Test) -> () -> Bool) because Swift instance methods are curried functions.

If making isOk into a static method is acceptable, you can do this:

struct Test {
    static func isOk() -> Bool { //Make it static
        return true
    }

    var mapping: [Int : () -> Bool] = [
        1 : Test.isOk // Static method must be qualified by its parent type
    ]

    func test() -> Bool { //Bool return value necessary
        //TODO: remove force unwrapping.
        return mapping[1]!() //subscripting a Dict might return nil
    }
}

If isOk must remain as an instance method, you can do this:

struct Test {
    func isOk() -> Bool {
        return true
    }

    var mapping: [Int : (Test) -> () -> Bool] = [ //change type
        1 : isOk
    ]

    //the instance method received from the dict needs an instance to act on
    func test(instance: Test) -> Bool { //Bool return value necessary
        //TODO: remove force unwrapping.
        return mapping[1]!(instance)() //curried function call
    }
}