简体   繁体   English

swift类作为没有.self的参数

[英]swift class as parameter without .self

I've wrote some functions (Swift 2.1, XCode 7.1.1): 我写了一些函数(Swift 2.1,XCode 7.1.1):

public func test1<T:UIView>(type: T.Type) -> T {
    print(type.dynamicType)
    return type.init()
}

public func test2<T:UIView>(type: T.Type)(_ n: Int) -> T {
    print(type.dynamicType)
    return type.init()
}

public func test3<T1:UIView, T2:UIView>(type1: T1.Type, _ type2: T2.Type) {
    print(type1.init())
    print(type2.init())
}

public func test4<T:UIView>(type: T.Type, _ n: Int) {
    print(type.init())
    print(n)
}

public func test5<T:UIView>(n: Int,_ type: T.Type) {
    print(type.init())
    print(n)
}

And call them with: 并打电话给他们:

test1(UIButton)
test1(UIButton.self)

test2(UIButton)(1)
test2(UIButton.self)(1)

test3(UIButton.self, UITextField.self)

test4(UIButton.self, 1)

test5(1, UIButton.self)

As you can see, when a type is the only parameter, it can omit the ".self". 如您所见,当一个类型是唯一的参数时,它可以省略“.self”。 But for all functions that not have only a type parameter, they require the ".self". 但对于所有不具有类型参数的函数,它们都需要“.self”。

I want to know: 我想知道:

  1. Why is That? 这是为什么?
  2. And how to declare a function with multiple parameters that doesn't need ".self" where using it? 以及如何声明一个具有多个参数的函数,这些参数在使用它时不需要“.self”?

Coincidentally, this just came up on swift-evolution. 巧合的是,这恰好出现在迅速演变中。 The ability to omit .self when the Type is the only argument, has been reported as a bug in Swift. 当Type是唯一的参数时,省略.self的能力已被报告为Swift中的错误

The relevant quote from Apple: Apple的相关报价:

It's a bug. 这是一个错误。 .self is supposed to be required everywhere. .self都应该要求自己。 Unfortunately, we've had the bug for a while, so I'm not sure how much code we'd break by changing it. 不幸的是,我们已经有了一段时间的错误,所以我不确定通过更改它会破坏多少代码。 If we wanted to remove the requirement, that would be considered a language change and would have to go through the Swift Evolution Process. 如果我们想要删除该要求,那将被视为语言更改,并且必须通过Swift Evolution Process。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM