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!
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.
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.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With