我知道这是一个旧的帖子,但最近我遇到了类似的情况。可能会对某些人有所帮助。
简而言之
最终,我通过将方法调用包装在闭包中来解决了这个问题,就像这样:
let cancel: (Text) -> Alert.Button = { .cancel($0) }
冗长的解释
当我输入Alert.Button.cancel
(来自SwiftUI框架)时,自动完成会显示以下选项:
cancel(action: (() -> Void)?) // 1
cancel(label: Text) // 2
cancel() // 3
cancel(label: Text, action: (() -> Void)?) // 4
自然地,我认为这段代码应该可以工作:
let cancel: (Text) -> Alert.Button = Alert.Button.cancel(_:)
然而,编译器报错:无法将类型 '((() -> Void)?) -> Alert.Button' 转换为指定类型 '(Text) -> Alert.Button'
。显然,它将该签名翻译成了方法1而不是方法2。
事实证明,方法2实际上并不存在。查看Alert.swift
中的实际声明,我们发现:
public static func cancel(_ label: Text, action: (() -> Void)? = {}) -> Alert.Button
public static func cancel(_ action: (() -> Void)? = {}) -> Alert.Button
所以,
cancel(label:)
是由自动补全从
cancel(_:action:)
中生成的,因为参数
action
有一个默认值。
结论:我犯了一个错误,认为自动补全显示的是单个方法声明。如果编译器告诉你方法签名与你期望的不匹配,请检查方法的声明。