Celebrating 200 Daily Coding Tips 🎉 all tutorials will be free to all this week!
(Even though the 200th Daily Coding Tip isn’t until tomorrow 😁)
You’re probably familiar with creating a string from a literal like this:
let myString = "this is my string"
A literal is a value that exists without ever having been given an explicit type. Instead of passing a value to a type’s initializer, they literally are that value.
They exist for Booleans and numerical types too, and they can be used in all sorts of places.
You can think of this as a shorthand for creating a type like String
, as Swift will infer the type from the literal and do the work for you.
When creating a colour from red, green and blue components, it can be difficult to know what that colour looks like:
Color(red: 0.1373188794, green: 0.3591549993, blue: 0.513671279)
There is one solution for this of course.
A Color Set can be created in Assets.xcassets, where a preview is shown along with many other settings that make the colour work across light and dark appearances.
But what if there was a literal that made it possible to set colours inside your code?
There is!
Try typing this:
extension UIColor {
static let backgroundColour = #colorLiteral()
}
When you type the first opening bracket after #colorLiteral
, the part that says #colorLiteral
will disappear and be replaced with an image icon. Remember to still add the closing bracket after the icon appears, or Xcode will complain.
Now you should be able to double click on the icon and get this colour picker:
Selecting any colour will get dismiss the error that Xcode otherwise displays about not having the right parameters. It’s pretty cool that it’s possible to create a UIColor
, but what about a SwiftUI Color
? Unfortunately Apple hasn’t made it possible to create a SwiftUI Color
directly from a colorLiteral
, so for now we’ll have to make do with passing it to the Color
initializer.
Let’s create a background and foreground colour inside an extension:
I was wondering if it’s possible to create a version of foregroundColor
that takes a colorLiteral
.
It’s possible, but the results are slightly disappointing:
Yes it’s possible, but unfortunately Xcode doesn’t provide the usual colour picker when passing a colorLiteral
as a parameter to a function.
The version here takes a UIColor
, as this is what #colorLiteral
ends up being, but it also works if you pass a _ColorLiteralType
.
This is an internal type that Apple doesn’t want you using, as indicated by the underscore.
Your app will not pass App Store review with any mention of a type like this.