[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

相关推荐
杂雾无尘1 小时前
开发者必看:如何在 iOS 应用中完美实现动态自定义字体!
ios·swift·apple
kymjs张涛3 小时前
零一开源|前沿技术周报 #6
前端·ios·harmonyos
与火星的孩子对话19 小时前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
恋猫de小郭2 天前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
点金石游戏出海2 天前
每周资讯 | Krafton斥资750亿日元收购日本动画公司ADK;《崩坏:星穹铁道》新版本首日登顶iOS畅销榜
游戏·ios·业界资讯·apple·崩坏星穹铁道
旷世奇才李先生2 天前
Swift 安装使用教程
开发语言·ios·swift
90后的晨仔2 天前
Xcode16报错: SDK does not contain 'libarclite' at the path '/Applicati
ios
finger244802 天前
谈一谈iOS线程管理
ios·objective-c
Digitally2 天前
如何将大型视频文件从 iPhone 传输到 PC
ios·iphone
梅名智2 天前
IOS 蓝牙连接
macos·ios·cocoa