swift类作为没有.self的参数 [英] swift class as parameter without .self

查看:98
本文介绍了swift类作为没有.self的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些函数(Swift 2.1,XCode 7.1.1):

I've wrote some functions (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)

如您所见,当一个类型是唯一的参数时,它可以省略.self。但对于所有不具有类型参数的函数,它们都需要.self。

As you can see, when a type is the only parameter, it can omit the ".self". But for all functions that not have only a type parameter, they require the ".self".

我想知道:


  1. 为什么?

  2. 如何使用多个参数声明一个不需要.self的函数?


推荐答案

巧合的是,这只是出现了迅速进化。当Type是唯一参数时,省略 .self 的能力已被报告为 bug

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.

Apple的相关报价:

The relevant quote from Apple:


这是一个错误。 .self 应该在任何地方都是必需的。
不幸的是,我们已经有了一段时间的错误,所以我不确定通过更改它会破坏多少
代码。如果我们想要删除
要求,那将被视为语言更改,并且将通过Swift Evolution Process获得

It's a bug. .self is supposed to be required everywhere. 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类作为没有.self的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆