【问题标题】:Store function in array将函数存储在数组中
【发布时间】:2018-11-05 11:44:54
【问题描述】:

我有一个名为 update 的函数,如下所示:

func update(animated: Bool, completion: @escaping (Bool) -> ()) {

}

现在我想在一个数组中对这个函数的多个调用进行排队。我该怎么做?

我需要一个类型的数组:

var queue = [???]()

并追加queue.append(???)之类的函数,但我想不通。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    为了简化如何实现它,只需复制您的函数签名:

    (animated: Bool, completion: @escaping (Bool) -> ())
    

    并用它来声明一个typealias

    typealias Update = (animated: Bool, completion: (Bool) -> ())
    

    你会看到语法错误:

    @escaping 属性只能用在函数参数位置

    建议删除@escaping,这样做:

    typealias Update = (animated: Bool, completion: (Bool) -> ())
    

    此时,您将能够通过使用Update 类型别名来识别适当的类型。

    因此,您可以将 queue 数组声明为:

    var queue = [Update]()
    

    请注意,在声明类型别名时,您可以避免将参数命名为:

    // this is sufficient
    typealias Update = (Bool, (Bool) -> ())
    

    进一步

    要了解 typealias 是什么,您可以查看:When to use typealias?(以及答案中提到的 story

    【讨论】:

    • 在声明一个类型,或者给一个类型加上别名时,不是总是建议使用 UpperCamelCase 吗?
    • @Scriptable true,我只是忘记了这个,答案已编辑。非常感谢:)
    【解决方案2】:

    在发布此内容后,实际上只是解决了我自己的问题。答案是这样的:

    private var queue = [(Bool, (Bool) -> ()) -> ()]()
    

    queue.append(update)

    【讨论】:

      猜你喜欢
      • 2016-02-12
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多