Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Calling a Swift class factory method with leading dot notation?

In a recent question, the poster had this interesting line of code:

self.view.backgroundColor = .whiteColor()

I was surprised to see this. I've only ever seen the leading dot notation used for enum values. In this case, backgroundColor is of type UIColor? and whiteColor is a class method on UIColor that returns a UIColor.

Why does this work? It this a legitimate way to call a factory method?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This feature is called "Implicit Member Expression"

An implicit member expression is an abbreviated way to access a member of a type, such as an enumeration case or a class method, in a context where type inference can determine the implied type. It has the following form:

.member name


But, as of right now, I advise you should not use this feature in Optional or ImplicitlyUnwrappedOptional context.

Although this works:

// store in Optional variable
let col: UIColor?
col = .redColor()

// pass to function
func f(arg:UIColor?) { println(arg) }
f(.redColor())

This crashes the compiler :(

func f(arg:UIColor?, arg2:Int) { println(arg) }
//                 ^^^^^^^^^^ just added this.
f(.redColor(), 1)

The compiler has some bugs. see: does swift not allow initialization in function parameters?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...