Type Values and Casting
Types that hold anything (⚪️ and 🔵)
⚪️ is a type that can hold any value. 🔵 is a type that can hold an instance of any class (value types and numbers do not fit).
🏁 🍇
🆕🍨🐚⚪️🍆❗️ ➡️ 🖍🆕 things
🐻 things 42❗️
🐻 things 🔤string🔤❗️
🐻 things 👍❗️
😀 🔡 📏 things❓❗️❗️
🍉3
Casting (🔲)
To use a value stored in something like ⚪️ as its original type, cast it with 🔲 value type. The result is an optional; if the value is not of that type, you get no value.
🏁 🍇
🍿 42 🔤abc🔤 7 🍆 ➡️ things
🔂 thing things 🍇
↪️ 🔲 thing 🔢 ➡️ n 🍇
😀 🔤Integer 🔡 n❗️🔤❗️
🍉
🙅↪️ 🔲 thing 🔡 ➡️ s 🍇
😀 🔤String s🔤❗️
🍉
🍉
🍉Integer 42 String abc Integer 7
A 🍿 … 🍆 of literals becomes a 🍨🐚⚪️🍆 when the elements have different types.
Using types as values
The name of a class, value type, or enumeration can be used directly as a value. The 🐇Type you write when calling a type method (Classes) is exactly that.
🐇 🌷 🍇
🐇❗️ 🏷 ➡️ 🔡 🍇
↩️ 🔤Tulip🔤
🍉
🍉
🐇 🌹 🌷 🍇
✒️ 🐇❗️ 🏷 ➡️ 🔡 🍇
↩️ 🔤Rose🔤
🍉
🍉
🏁 🍇
😀 🏷🐇🌷❗️❗️
😀 🏷🐇🌹❗️❗️
🍉Tulip Rose
Type methods can also be overridden in a subclass with ✒️.
Creating instances from a type value (⬛️)
You can store a type in a variable and create an instance of that type with 🆕⬛️ variable❗️. So that subclasses can be created this way too, mark the initializer with 🔑 (More on Classes).
🐇 🐾 🍇
🔑 🆕 🍇🍉
❗️ 🏷 ➡️ 🔡 🍇
↩️ 🔤animal🔤
🍉
🍉
🐇 🐕 🐾 🍇
🔑 🆕 🍇 ⤴️🆕❗️ 🍉
✒️ ❗️ 🏷 ➡️ 🔡 🍇
↩️ 🔤dog🔤
🍉
🍉
🏁 🍇
🍿 🐇🐾 🐇🐕 🍆 ➡️ kinds
🔂 kind kinds 🍇
🆕⬛️ kind❗️ ➡️ animal
😀 🏷 animal❗️❗️
🍉
🍉animal dog
When you treat types as values, the compiler warns that runtime type information for type values is not yet complete, but this example works correctly.
Is it the same instance? (😜)
🙌 checks whether values are equal, but 😜 checks whether two things are the very same instance.
🐇 🐟 🍇
🆕 🍇🍉
🍉
🏁 🍇
🆕🐟❗️ ➡️ a
a ➡️ b
🆕🐟❗️ ➡️ c
↪️ a 😜 b 🍇
😀 🔤a and b are the same🔤❗️
🍉
↪️ ❎ a 😜 c❗️ 🍇
😀 🔤a and c are different🔤❗️
🍉
🍉a and b are the same a and c are different
A type combining several protocols (🍱)
🍱Protocol Protocol🍱 represents “a type that conforms to both protocols.”
🐊 🔊 🍇
❗️ 🗣 ➡️ 🔡
🍉
🐊 🏃 🍇
❗️ 🦵 ➡️ 🔡
🍉
🐇 🐕 🍇
🐊 🔊
🐊 🏃
🆕 🍇🍉
❗️ 🗣 ➡️ 🔡 🍇
↩️ 🔤Woof🔤
🍉
❗️ 🦵 ➡️ 🔡 🍇
↩️ 🔤Tap tap tap🔤
🍉
🍉
🐇 🎪 🍇
🐇❗️ 🎤 pet 🍱🔊🏃🍱 🍇
😀 🗣 pet❗️❗️
😀 🦵 pet❗️❗️
🍉
🍉
🏁 🍇
🎤🐇🎪 🆕🐕❗️❗️
🍉Woof Tap tap tap
Saving effort when writing types (📣 and ⚫)
📣 value type specifies the type of a literal. For example, 🍿 🍆 alone does not tell the compiler the type of the empty list, so you write the type with 📣.
🏁 🍇
📣 🍿🍆 🍨🐚🔡🍆 ➡️ 🖍🆕 names
🐻 names 🔤Emoji🔤❗️
😀 🔡 📏 names❓❗️❗️
🍉1
Letting the compiler infer the type (⚫️)
The compiler has a mechanism where you write ⚫️ in place of a type to have it inferred. However, everywhere we tried (assigning to a variable, arguments, return values), it gave the error Cannot infer ⚫️., and we could not find any situation where it works. Neither the official tests nor the standard library use it anywhere.
🏁 🍇
🖍🆕 names 🍨🐚🔡🍆
🆕⚫️❗️ ➡️ 🖍names
🍉Cannot infer ⚫️.