Updated 29 October 2021
In this blog we will see what is callAsFunction and what is callable objects. Let first see callAsFunction with an example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Employee { var empId:String var designation:String init(empId:String,designation:String) { self.empId = empId self.designation = designation } func callAsFunction(_ salary:Double){ print("EmpId: \(empId) Designation:\(designation) Salary:\(salary)") } } |
In the above example, we have created a class named Employee, in this class, we have created a method callAsFunction. Now we can call this method by following ways
1 2 3 4 5 6 |
let emp = Employee(empId: "111", designation: "Eng") emp(100.0) // EmpId: 111 Designation:Eng Salary:100.0 emp.callAsFunction(200)// EmpId: 111 Designation:Eng Salary:200.0 Employee(empId: "111", designation: "Eng").callAsFunction(150)// EmpId: 111 Designation:Eng Salary:150.0 |
By using callAsFunction method we can call instances of any type as a method. You can use callAsFunction with argument or without argument. Let see one small example of it using without argument.
1 2 3 4 5 6 7 8 9 |
struct Test { func callAsFunction(){ print("callAsFunction without argument") } } let test1 = Test() test1() // callAsFunction without argument |
In the above example, we have created a struct name Test, in which there is callAsFunction method which takes no argument. We have called the instance of Test as a method using these swift features. So, far we have seen two examples of callAsFunction now we will understand what is callable objects. So, Any object which has callAsFunction method can call as a method, such object is called callable objects.
I hope you have gotten a basic idea of Callable Objects and callAsFunction in iOS Swift. You can also check other blogs from here. If you have any issues, query or suggestions then you can leave your issues/query/suggestion in the comment section.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.