代码之家  ›  专栏  ›  技术社区  ›  Evgeniy Kleban

了解swift字典语法

  •  0
  • Evgeniy Kleban  · 技术社区  · 8 年前

    我使用遗留代码,发现以下代码:

    let actions = [PrinterReportType.z: {
                            printer.printZReport($0)
                            DeviceFabric.lifehubTerminal().reconciliation()
                        }, .x: printer.printXReport, .openSession: printer.openSession}]
    

    “操作”的声明如下:

    let actions: [PrinterReportsModel.PrinterReportType : ((String?) -> ()) -> ()]
    

    关键是枚举值,但我不知道这里的值是什么。 我有新的枚举类型 PrinterReportsModel.PrinterReportType ,我只是想给这本字典增加新的价值。我想这是某种函数。所以,我想声明那个函数,把它添加到这里,但我不知道怎么做。我不知道是什么类型- ((String?) -> ()) -> ()

    1 回复  |  直到 8 年前
        1
  •  2
  •   rob mayoff    8 年前

    String 是字符的集合。

    String? 表示与相同 Optional<String> ,所以 Optional.none Optional.some(String)

    (String?) -> () 是采用 一串 不返回任何内容( () 也称为 Void ,零元素元组)。我们把这叫做 一串 -消费者 :需要 一串 确实如此 某物 用它。也许它只是 一串 离开也许它会打印出来。也许它存储了 一串 或通过网络发送。

    您可以定义 一串 -消费者关闭方式如下:

    let action: (String?) -> () = { (_ s: String?) -> () in
        print(s ?? "(none)")
    }
    

    (我完全指定了上面的类型,但您可以省略一些类型,让编译器推断出来。)

    您可以定义 一串 -消费者功能如下:

    func test(_ s: String?) -> () { print(s ?? "(none)" }
    

    然后像这样传递:

    let action: (String?) -> () = test
    

    您可以定义 一串 -类(或结构)中的使用者方法如下:

    class MyObject {
        func test(_ s: String?) -> () { print(s ?? "(none)") }
    }
    

    然后像这样传递:

    let myObject = MyObject()
    let action: (String?) -> () = myObject.test
    

    ((String?) -> ()) -> () 是采用 一串 -消费者,不返回任何内容。你可以把这看作 一串 -消费者消费者。也许它会 一串 -消费者离开。也许它存储了 一串 -消费者在以后的变量中。也许它叫 一串 -消费者一次,或十次,或对于字符串数组中的每个元素一次。也许它会给 一串 -每秒消费一次,直到程序退出。

    您可以定义 一串 -消费者-消费者关闭如下:

    let action: ((String?) -> ()) -> () = { (_ sc: (String?) -> ()) -> () in
        sc("hello")
        sc(nil)
        sc("world")
    }
    

    你可以这样称呼结束语:

    action({ (_ s: String?) -> () in print(s ?? "(none)")}
    

    或者像这样:

    let printString: (String?) -> () = { print($0) }
    action(printString)
    

    您可以定义 一串 -消费者消费者功能如下:

    func test(_ sc: (String?) -> ()) -> () {
        sc("hello")
        sc(nil)
        sc("world")
    }
    

    然后像这样传递:

    let action: ((String?) -> ()) -> () = test
    

    您可以定义 一串 -类(或结构)中的consumer-consumer方法如下:

    class MyObject {
        func test(_ sc: (String?) -> ()) -> () {
            sc("hello")
            sc(nil)
            sc("world")
        }
    }
    

    然后像这样传递:

    let myObject = MyObject()
    let action: ((String?) -> ()) -> () = myObject.test