uinavigationcontroller

uinavigationcontroller

本文介绍了在Swift中,调用UINavigationController()与UINavigationController.init()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,调用UINavigation()UINavigation.init()有什么区别?它们似乎都返回UINavigationController的有效实例.

In Swift, what's the difference between calling UINavigation() vs UINavigation.init()? They both seem to return valid instance of UINavigationController.

推荐答案

对于某些给定类型(例如UINavigationController),对UINavigationController()UINavigationController.init()调用之间没有区别,但是在我们要使用闭包(或引用闭包)的上下文中,当引用某种给定类型的初始化程序(例如Foo)时,后一种语法(无需()调用)很有用.拥有

For some given type (e.g. UINavigationController), there is no difference between a call to UINavigationController() or UINavigationController.init(), but the latter syntax can (without the () call) be useful when referencing an initializer of some given type, say Foo, in contexts where we want to make use of a closure (or reference to a closure) which is to have

  • 零个或多个参数,以及
  • 返回类型Foo

例如(Int, Double) -> Foo.在这些情况下,使用语法Foo.init可能被证明是有用的:与其明确地让闭包反复调用一个已知的初始化程序(将闭包的参数插入初始化程序),我们不如使用(引用)初始化程序直接作为闭包.如果Foo的初始值设定项的参数没有歧义,则在某些给定的闭包类型上下文中对Foo.init的引用将使用类型推断将解析为正确的初始值设定项.

e.g., (Int, Double) -> Foo. In these contexts, using the syntax Foo.init may prove useful: rather than explicitly letting a closure repeatedly call a known initializer (piping the closure's arguments to the initializer), we may use (a reference to) the initializer direcly as the closure instead. If there's no ambiguity in the argument of the initializers of Foo, a reference to Foo.init in some given closure type context will resolve, using type inference, to the correct initializer.

例如,考虑以下示例

struct Foo {
    let foo: Int

    // (Int) -> Foo
    init(foo: Int) {
        self.foo = 2*foo
    }

    // (Int, Int) -> Foo
    init(foo: Int, bar: Int) {
        self.foo = foo + bar
    }

    // () -> Foo
    init() {
        self.foo = 42
    }
}

let arr = [1, 2, 3]
let fooArr1 = arr.map { Foo(foo: $0) }
let fooArr2 = arr.map(Foo.init)
                 /* map operation expects a single argument of type (Int) -> Foo, 
                    which we generally supply as a trailing closure. In this context,
                    Swift can, without ambiguity (since we have none, is this example), 
                    find the correct overload among the initializers of Foo */
print(fooArr1.map { $0.foo }, fooArr2.map { $0.foo }) // [2, 4, 6] [2, 4, 6]

let emptyTupArr = [(), (), ()]
let fooArr3 = emptyTupArr.map(Foo.init) // inferred to be the '() -> Foo' initializer
print(fooArr3.map { $0.foo }) // [42, 42, 42]

这篇关于在Swift中,调用UINavigationController()与UINavigationController.init()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 00:42