There is a very interesting writing method in Swift that allows us to not use instances to call methods on this instance directly, but to use the type to retrieve the signature of an instance method of this type, and then pass the instance to get the actual method that needs to be called. For example, we have this definition:
Copy the codeThe code is as follows:
class MyClass {
func method(number: Int) -> Int {
return number + 1
}
}
If you want to call the method method, the most common way to use it is to generate an instance of MyClass and then use .method to call it:
Copy the codeThe code is as follows:
let object = MyClass()
let result = (1)
// result = 2
This limits that we can only decide on the object instance and the corresponding method call when compiling. In fact, we can also use the method mentioned just now to rewrite the above example as:
Copy the codeThe code is as follows:
let f =
let object = MyClass()
let result = f(object)(1)
This syntax may seem strange, but it is not complicated in fact. The syntax in Swift can be used directly to generate a curable method. If we observe the type of f (Alt + click), we can know that it is:
Copy the codeThe code is as follows:
f: MyClass -> (Int) -> Int
In fact, for such a value statement, I've just
Copy the codeThe code is as follows:
let f =
What you do is a literal conversion similar to the following:
Copy the codeThe code is as follows:
let f = { (obj: MyClass) in }
It is not difficult to understand why the above call method is valid.
This method is only applicable to instance methods, and similar writing methods cannot be used for getters or setters of attributes. Also, if we encounter a name conflict with typed methods:
Copy the codeThe code is as follows:
class MyClass {
func method(number: Int) -> Int {
return number + 1
}
class func method(number: Int) -> Int {
return number
}
}
If there is no change, the type method will be obtained. If we want to take an instance method, we can explicitly add a type declaration to distinguish it. This approach not only works here, but it solves the problem well in most other names with ambiguity:
Copy the codeThe code is as follows:
let f1 =
// version of class func method
let f2: Int -> Int =
// Same as f1
let f3: MyClass -> Int -> Int =
// Curry version of func method