[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

相关推荐
00后程序员张14 小时前
iOS App 混淆与资源保护:iOS配置文件加密、ipa文件安全、代码与多媒体资源防护全流程指南
android·安全·ios·小程序·uni-app·cocoa·iphone
咕噜签名分发冰淇淋16 小时前
内测分发是什么?
ios
2501_9160074720 小时前
Transporter App 使用全流程详解:iOS 应用 ipa 上传工具、 uni-app 应用发布指南
android·ios·小程序·https·uni-app·iphone·webview
白玉cfc21 小时前
【OC】单例模式
开发语言·ios·单例模式·objective-c
Digitally1 天前
比较 iPhone:全面比较 iPhone 17 系列
android·ios·iphone
2501_915909061 天前
HTTPS 错误解析,常见 HTTPS 抓包失败、443 端口错误与 iOS 抓包调试全攻略
android·网络协议·ios·小程序·https·uni-app·iphone
HarderCoder2 天前
在同步代码里调用 async/await:Task 就是你的“任意门”
swift
他们都不看好你,偏偏你最不争气2 天前
【iOS】UIViewController
开发语言·macos·ios·objective-c·cocoa
前端小超超2 天前
如何配置capacitor 打包的ios app固定竖屏展示?
前端·ios·web app
HarderCoder2 天前
Swift 三目运算符指南:写法、场景与避坑
swift