gpt4 book ai didi

ios - Swift - 闭包模式

转载 作者:可可西里 更新时间:2023-11-01 00:51:17 26 4
gpt4 key购买 nike

我正在阅读有关 Swinject 的文档,但我不明白这段代码中的两件事:

let container = Container()
container.register(AnimalType.self) { _ in Cat(name: "Mimi") }
container.register(PersonType.self) { r in
PetOwner(pet: r.resolve(AnimalType.self)!)
}

两个闭包如何独立存在而不嵌入方法调用中?闭包没有返回任何对象,我没有看到任何“返回”。那么容器如何获得“Cat”实例呢? (还有 PetOwner 实例)。

谢谢

最佳答案

  1. “两个闭包是独立的,没有嵌入到方法调用中”

这就是所谓的“尾随闭包”:

If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is a closure expression that is written outside of (and after) the parentheses of the function call it supports...

来源:Apple's documentation

  1. “闭包没有返回任何对象,我没有看到任何‘返回’”

该功能称为“隐式返回”:

Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration...

来源:Apple's documentation

关于ios - Swift - 闭包模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37989088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com