Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

ios - swift class as parameter without .self

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)

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".

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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

The relevant quote from Apple:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...