Reputation: 173
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
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
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
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