![](/img/trans.png)
[英]What protocol should be adopted by a Type for a generic function to take any number type as an argument in Swift?
[英]How to take a function of any number of parameters of any type as a parameter in swift
這基本上就是我要做的事情:
可以接受具有任意數量的參數和返回類型的任何函數的函數
那有可能嗎?
func fun1(x: Int,y: String){
}
func fun2(c: Float){
}
func thefunction(function,parameters) {
function(parameters[0],parameters[1]...)
}
thefunction(fun1,3,"hi")
thefunction(fun2,4.5)
Swift具有以下類型,允許使用任何類型的參數:
AnyObject
此外,您可以在參數列表的末尾創建一個參數,該參數允許傳遞動態數量的參數。 我直接從Apple文檔中提取了此信息以供參考:
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
您可以在此處查看條目。 進行一點點研究將令人驚訝。
就是說,我實際上不建議這樣做。 它使您的代碼很難為他人所理解。 如果您需要使函數如此通用以至於它可以從字面上接受任何對象並返回任意數量的任何對象,則可能有更好的方法來執行此操作。
Swift沒有apply
函數。 但是您可以使用通用函數:
func fun1(x: Int, y: String){
print(x, y)
}
func fun2(c: Float){
print(c)
}
func apply<Arg1, Return>(function: (Arg1) -> Return,_ arg: Arg1) -> Return {
return function(arg)
}
func apply<Arg1, Arg2, Return>(function: (Arg1, Arg2) -> Return, _ arg1: Arg1, _ arg2: Arg2) -> Return {
return function(arg1, arg2)
}
apply(fun1, 1, "foo")
apply(fun2, 3.1)
不利的一面是,您需要為每個Arity apply
通用apply
。 好處是,如果使用錯誤的參數調用函數,則會出現編譯器錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.