【问题标题】:Can I use an operator as default function argument in Swift?我可以在 Swift 中使用运算符作为默认函数参数吗?
【发布时间】:2018-01-21 22:25:03
【问题描述】:

我正在尝试使用运算符 > 作为默认函数参数:

Playground execution failed: error: StackSorting.playground:27:63: 
error: expected expression after unary operator
func sort<T>(..., compare: (T, T) -> Bool = >) where T: Comparable { }
                                            ^

我解决了,但是...有人知道更短的方法吗?

func sort<T>(..., compare: (T, T) -> Bool = { $0 > $1 }) where T: Comparable { }

【问题讨论】:

    标签: swift function closures operators default


    【解决方案1】:

    您可以使用运算符作为参数的默认值, 您只需将其括在括号中:

    func sort<T>(..., compare: (T, T) -> Bool = (>)) where T: Comparable { }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多