Antonija
Antonija

Reputation: 173

How can UIColor be a type in Swift?

I am learning Swift and this basic piece of code is confusing to me. Here is the code:

var newBackgroundColor : UIColor

I practiced with : Int or : String... Never this "custom" ones. My question is: is UIColor a class or a type? And if it is a class why don't we use this code:

var newBackgroundColor = UIColor

Upvotes: 0

Views: 492

Answers (3)

0x416e746f6e
0x416e746f6e

Reputation: 10136

If you Cmd-click the UIColor in your code you will be brought to the header-file of UIKit framework, straight to UIColor public interface, where you can see that yes, it's a class. Alternatively, you can look it up in Apple's documentation.

Reason why you can't do just

var newBackgroundColor = UIColor

... is that = is a shorthand for initialisation here. You not only indicate the type of a property/variable but also specify its initial value. I.e. for this to work you need to specify which exactly color should it be. E.g.

var newBackgroundColor = UIColor.blackColor()

Otherwise, if you really only need to declare the type, but initialisation will happen later, then you should use:

var newBackgroundColor : UIColor

Upvotes: 1

Rob
Rob

Reputation: 437422

First, yes, UIColor is a class. It's part of UIKit. See UIColor Class Reference.

Second, you asked why you can't do:

var newBackgroundColor = UIColor

You can't do that because it's not syntactically correct. You can't just say = where the righthand expression is just the name of a class. It would have to be an instance of the class, e.g.:

var newBackgroundColor = UIColor.redColor()

That defines a UIColor variable and initializes it with a particular instance. That's actually shorthand for:

var newBackgroundColor: UIColor = UIColor.redColor()

Upvotes: 2

rob mayoff
rob mayoff

Reputation: 385500

UIColor is both a class and a type. All classes are types.

The declaration

var newBackgroundColor: UIColor

declares newBackgroundColor to hold a reference to an instance of class UIColor.

Upvotes: 1

Related Questions