DEV Community

Lareen Melo ✨
Lareen Melo ✨

Posted on

Swift Literals

While working through Day 1 of the 100 Days of SwiftUI challenge, I encountered the following code:

var percentage: Double = 99
Enter fullscreen mode Exit fullscreen mode

Not sure if meme

I understand that this works. There are no warnings and Swift seems to cast that 99 to 99.0 with no problem... But I was not able to explain why it works.

So to fix that, I learned about swift literals.

What are Swift Literals?

Swift Literals represent a value in source code. They don't define a type, like Int or String, but rather values like 32 or "Hello!"

How do Swift Literals work?

When Swift encounters a literal, it tries to infer its type by automatically checking if the type can initialize that literal.

🤔 How?

Some types conform to the literal expressible protocols. This is what allows Swift to check for types that have the required implementation to initialize a literal.

If given context, meaning using type annotation or casting, Swift checks if the type defined conforms to the literal's expressible protocol.

If given no context, meaning

let meaningOfLife = 42 
Enter fullscreen mode Exit fullscreen mode

then Swift will automatically check if any of the Standard Types (Int, Double, String, etc...) is able to initialize this literal.

Looking back

var percentage: Double = 99
Enter fullscreen mode Exit fullscreen mode

Completely works.

When Swift encounters the 99 literal, it will try to infer its type to be Double. The Double type conforms to ExpressibleByIntegerLiteral, making it possible to initialize 99 to Double 🤯.

That's why this

var wholeNumber: Int = 99.0
Enter fullscreen mode Exit fullscreen mode

wouldn't work, because the Int type doesn't conform to the floating-point literal expressible protocol.

South Park cops saying "We're sorry, Ms. Cartman, but we must follow protocol".

What next

Next on the list, will be to work my own custom types and handle literal initialization.

Discussion (0)