How to declare a dictionary with functions as values ​​and using integers?

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? Thank!

+4
source share
2 answers

You see this strange type ( (Test) -> () -> Bool), because Swift instance methods are exact functions .

If accepting isOkinto a static method is valid, 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 you isOkmust 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
    }
}
+4
source

@AMomchilov , . (, mapping ) - - , , , self ( self ).

, isOk , mapping [Int : () -> Bool], lazy. isOk mapping, , () -> Bool.

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

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

    mutating func test() -> Bool {
        // you need to think about situations where mapping[1] returns nil
        // and deal with it in a more proper way than force unwrapping
        return mapping[1]!()
    }
}

, test() mutating - lazy , , .

( ), ( ) . mapping -, test mutating.

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

    init() {
        mapping[1] = isOk
    }

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

    func test() -> Bool {
        // you need to think about situations where mapping[1] returns nil
        // and deal with it in a more proper way than force unwrapping
        return mapping[1]!()
    }
}

, , , , () -> Bool.

+1

All Articles