Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 809
zs2020 Avatar asked Jun 30 '16 18:06

zs2020


People also ask

How do you create a dictionary using keys and values?

To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.

Can we use integer as key in dictionary?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.

Can a dictionary have numbers as keys?

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

Which one creates a dictionary with a key type of integer and value of string?

The Key type of the dictionary is Int , and the Value type of the dictionary is String . To create a dictionary with no key-value pairs, use an empty dictionary literal ( [:] ). Any type that conforms to the Hashable protocol can be used as a dictionary's Key type, including all of Swift's basic types.


Video Answer


1 Answers

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
    }
}
like image 98
Alexander Avatar answered Oct 17 '22 00:10

Alexander