[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_9159214321 小时前
iOS 应用上架多环境实战,Windows、Linux 与 Mac 的不同路径
android·ios·小程序·https·uni-app·iphone·webview
Cyclic10011 天前
IOS购买订阅通知信息解析说明Java
java·开发语言·ios
00后程序员张1 天前
iOS 应用上架常见问题与解决方案,多工具组合的实战经验
android·ios·小程序·https·uni-app·iphone·webview
HarderCoder2 天前
我们真的需要 typealias 吗?——一次 Swift 抽象成本的深度剖析
swift
HarderCoder2 天前
ByAI-Swift 6 全览:一份面向实战开发者的新特性速查手册
swift
HarderCoder2 天前
Swift 中 let 与 var 的真正区别:不仅关乎“可变”与否
swift
HarderCoder2 天前
深入理解 Swift 6.2 并发:从默认隔离到@concurrent 的完整指南
swift
2501_916007472 天前
iOS App 上架实战 从内测到应用商店发布的全周期流程解析
android·ios·小程序·https·uni-app·iphone·webview
wjm0410062 天前
ios八股文 -- Objective-c
开发语言·ios·objective-c
麦兜*2 天前
Swift + Xcode 开发环境搭建终极指南
开发语言·ios·swiftui·xcode·swift·苹果vision pro·swift5.6.3