swift - 使用重载函数作为一等公民

标签 swift first-class-functions

假设我们在一个类中有多个重载函数:

func appendToABC(string s: String) -> String {
    return "ABC \(s)"
}

func appendToABC(duplicatedString s: String) -> String {
    return "ABC \(s)\(s)"
}

我们有一些 API 可以作为参数运行:

func printString(function: (String) -> String) {
    print(function("ASD"))
}

我们如何将 appendToABC 函数之一作为参数传递给 printString 函数?

我想过用一个闭包来包裹这个函数,但它看起来不太好

printString { appendToABC(duplicatedString: $0) }

最佳答案

这是 Swift 中的一个已知限制。有一个 open proposal解决它。目前唯一的解决方案是关闭。

请注意,Swift 中的许多事情都是如此。您也不能将属性直接作为函数引用,即使它们的行为类似于函数。您必须使用闭包。甚至一些自由函数也不能直接传递(print 是最常见的例子)。

关于swift - 使用重载函数作为一等公民,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34678056/

相关文章:

swift - 使用归并排序计算反转,Swift

PHP支持一流的函数,是什么意思

function - F# 函数组合,其中第一个函数的元数 >1

Swift 闭包和一流函数之间有什么区别?

ios - 我返回的 UILabel 高度从来不准确

ios - 如何测量iOS系统键盘上的触摸压力(击键)?

ios - 从一个函数访问另一个 Swift 函数的变量

ios - 您可以在 iOS 8 (w/Swift) 中以编程方式切换“请勿打扰”模式吗?

methods - 使用函数名作为参数

c# - 在 OOP 中覆盖方法与分配方法委托(delegate)/事件