How to resolve the algorithm Send an unknown method call step by step in the Swift programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Send an unknown method call step by step in the Swift programming language
Table of Contents
Problem Statement
Invoke an object method where the name of the method to be invoked can be generated at run time.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Send an unknown method call step by step in the Swift programming language
Source code in the swift programming language
import Foundation
class MyUglyClass: NSObject {
@objc
func myUglyFunction() {
print("called myUglyFunction")
}
}
let someObject: NSObject = MyUglyClass()
someObject.perform(NSSelectorFromString("myUglyFunction"))
@dynamicCallable
protocol FunDynamics {
var parent: MyDynamicThing { get }
func dynamicallyCall(withArguments args: [Int]) -> MyDynamicThing
func dynamicallyCall(withKeywordArguments args: [String: Int]) -> MyDynamicThing
}
extension FunDynamics {
func dynamicallyCall(withKeywordArguments args: [String: Int]) -> MyDynamicThing {
if let add = args["adding"] {
parent.n += add
}
if let sub = args["subtracting"] {
parent.n -= sub
}
return parent
}
}
@dynamicMemberLookup
class MyDynamicThing {
var n: Int
init(n: Int) {
self.n = n
}
subscript(dynamicMember member: String) -> FunDynamics {
switch member {
case "subtract":
return Subtracter(parent: self)
case "add":
return Adder(parent: self)
case _:
return Nuller(parent: self)
}
}
}
struct Nuller: FunDynamics {
var parent: MyDynamicThing
func dynamicallyCall(withArguments args: [Int]) -> MyDynamicThing { parent }
}
struct Subtracter: FunDynamics {
var parent: MyDynamicThing
func dynamicallyCall(withArguments args: [Int]) -> MyDynamicThing {
switch args.count {
case 1:
parent.n -= args[0]
case _:
print("Unknown call")
}
return parent
}
}
struct Adder: FunDynamics {
var parent: MyDynamicThing
func dynamicallyCall(withArguments arg: [Int]) -> MyDynamicThing {
switch arg.count {
case 1:
parent.n += arg[0]
case _:
print("Unknown call")
}
return parent
}
}
let thing =
MyDynamicThing(n: 0)
.add(20)
.divide(2) // Unhandled call, do nothing
.subtract(adding: 10, subtracting: 14)
print(thing.n)
You may also check:How to resolve the algorithm Remove duplicate elements step by step in the C programming language
You may also check:How to resolve the algorithm Zero to the zero power step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Hash from two arrays step by step in the D programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Almost prime step by step in the Erlang programming language