[swift-users] How to store ref to any kind of function, and call with it argument list?

C. Keith Ray keithray at mac.com
Fri Nov 3 16:21:09 CDT 2017


In the code below, I'm trying to store a reference to a function with any number of arguments, with any return type. And I want to be able to invoke it. 

Help?

See the comments with "*******"

typealias Void = ()

func equalTypes(_ me: [Any.Type], _ other: [Any.Type]) -> Bool {
    guard me.count == other.count else { return false }
    
    for i in 0 ..< me.count {
        if me[i] != other[i] { return false }
    }
    return true
}

struct Function {
    var returnType: Any.Type
    var argTypes: [Any.Type]
    var function: Any // ******* any function *******
    
    func perform(_ args: [Any]) -> Any {
        // ******* call function() with args, return result *******
        return 0
    }
    
    func isCompatible(_ other: Function) -> Bool {
        return self.returnType == other.returnType &&
            equalTypes(argTypes, other.argTypes)
    }
}

func vToV() {
    print("vToV")
}

func intToInt(_ i: Int) -> Int {
    print("intToInt")
    return 4
}

let f = Function(returnType: Void.self,
                 argTypes: [],
                 function: vToV)
let r = f.perform([])
print(r)

let f2 = Function(returnType: Int.self,
                 argTypes: [Int.self],
                 function: intToInt)
let r2 = f2.perform([12])
print(r2)

assert(f.isCompatible(f))
assert(!f.isCompatible(f2))


--
C. Keith Ray
Senior Software Engineer / Trainer / Agile Coach
* http://www.thirdfoundationsw.com/keith_ray_resume_2014_long.pdf



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20171103/db65b69e/attachment.html>


More information about the swift-users mailing list