[SwiftUI 开发] @dynamicCallable 与 callAsFunction:将类型实例作为函数调用

在 Swift 中,@dynamicCallable 和 callAsFunction 提供了两种将类型实例作为函数调用的方式。

1. callAsFunction

对于 callAsFunction,只需实现名为 callAsFunction 的方法,参数和返回值可自行任意定义。

例如,考虑一个ShapeCalculator结构体:

Swift 复制代码
struct ShapeCalculator {
    func callAsFunction(length: Int, width: Double) -> Double {
        return Double(length) * width
    }
    func callAsFunction(radius: Double) -> Double {
        return 3.14 * radius * radius
    }
    func callAsFunction(side: Double) -> Double {
        return side * side
    }
}
使用示例
Swift 复制代码
func runTest() -> Void {
    let calculator = ShapeCalculator()
    print("Area: \(calculator(length: 5, width: 3.0))")
    print("Area: \(calculator(radius: 2.0))")
    print("Area: \(calculator(side: 4.0))")
}
输出结果如下:
Swift 复制代码
Area: 15.0
Area: 12.56
Area: 16.0

2:@dynamicCallable

当使用 @dynamicCallable 时,需要将此属性应用于类、结构、枚举或协议,使其类型的实例可被视为可调用函数。这要求必须实现dynamicallyCall(withArguments:)dynamicallyCall(withKeywordArguments:)其中一个或两个方法。

例如,我们创建一个StringManipulator结构体:

Swift 复制代码
@dynamicCallable struct StringManipulator {
    func dynamicallyCall(withArguments args: [String]) -> String {
        var result = ""
        for string in args {
            result += string.uppercased()
        }
        return result
    }
    func dynamicallyCall(withKeywordArguments pairs: KeyValuePairs<String, String>) -> String {
        var result = ""
        for (key, value) in pairs {
            result += "\(key): \(value.uppercased())\n"
        }
        return result
    }
}
使用示例
Swift 复制代码
func runTest() -> Void {
    let manipulator = StringManipulator()
    print("Result: \(manipulator("hello", "world"))")
    print("Result: \(manipulator(name: "John", age: "30"))")
}
输出结果为:
Swift 复制代码
Result: HELLO WORLD
Result: NAME: JOHN
AGE: 30

两者的区别

1. 参数类型要求

@dynamicCallable实现的方法调用,参数类型必须一致, 参数数量可以不一样

callAsFunction 参数类型可以不一致, 参数数量固定的

2. 方法命名要求

@dynamicCallable必须实现一个名为dynamicallyCall的方法,参数标签名称必须是withArguments或withKeywordArguments;callAsFunction必须实现一个名为callAsFunction的方法,并且参数标签可以自定义,因此callAsFunction具有更灵活的参数标签命名

3. 相同点

两者实现的方法都支持方法重载,但对于@dynamicCallable,重载方法的参数标签必须是withArguments或withKeywordArguments

相关推荐
2501_9159184114 小时前
如何在iPad上找到并打开文件夹的完整指南
android·ios·小程序·uni-app·iphone·webview·ipad
2501_915918411 天前
Wireshark、Fiddler、Charles抓包工具详细使用指南
android·ios·小程序·https·uni-app·iphone·webview
TheNextByte11 天前
如何将文件从Android无线传输到 iPad
android·ios·ipad
2501_915106322 天前
如何在iPad上高效管理本地文件的完整指南
android·ios·小程序·uni-app·iphone·webview·ipad
2501_915106322 天前
iOS 成品包加固,在只有 IPA 的情况下,能做那些操作
android·ios·小程序·https·uni-app·iphone·webview
Free Tester2 天前
在iPhone上显示点击屏幕点击的方法
功能测试·ios·iphone
AALoveTouch2 天前
某麦APP抢票技术解析实现
android·ios
2501_915909062 天前
苹果iOS应用上架详细流程与注意事项解析
android·ios·小程序·https·uni-app·iphone·webview
莫桐2 天前
微信小程序-ios环境下webview打开的h5页面replace跳转方式不生效问题
ios·微信小程序·小程序
搜狐技术产品小编20232 天前
iOS OOM治理
macos·ios·objective-c·cocoa