Generics
Deciding the type later (🐚)
If you write 🐚Name Constraint🍆 after a type's name, the type used inside can be decided when the type is used.
🐇 🎁 🐚T ⚪️🍆 🍇
🖍🆕 content T
🆕 🍼 content T 🍇🍉
❗️ 📤 ➡️ T 🍇
↩️ content
🍉
🍉
🏁 🍇
🆕🎁🐚🔡🍆 🔤secret🔤❗️ ➡️ textBox
🆕🎁🐚🔢🍆 42❗️ ➡️ numberBox
😀 📤 textBox❗️❗️
😀 🔡 📤 numberBox❗️ ➕ 1❗️❗️
🍉secret 43
🎁🐚🔡🍆 is “a box that holds a string,” and 🎁🐚🔢🍆 is “a box that holds an integer.” The return type of 📤 becomes 🔡 and 🔢 respectively. Lists (🍨🐚🔢🍆) and dictionaries are built with this same mechanism.
⚪️ is the constraint, and it means “any type is fine.”
Adding a constraint
If you write a protocol as the constraint, only types that conform to that protocol are accepted. In return, you can call that protocol's methods inside.
🐊 🏷 🍇
❗️ 🔡 ➡️ 🔡
🍉
🕊 🍎 🍇
🐊 🏷
🆕 🍇🍉
❗️ 🔡 ➡️ 🔡 🍇
↩️ 🔤apple🔤
🍉
🍉
🐇 📦🐚T 🏷🍆 🍇
🖍🆕 items 🍨🐚T🍆
🆕 🍇
🆕🍨🐚T🍆❗️ ➡️ 🖍items
🍉
❗️ 📥 item T 🍇
🐻 items item❗️
🍉
❗️ 📋 🍇
🔂 item items 🍇
😀 🔤- 🔡 item❗️🔤❗️
🍉
🍉
🍉
🏁 🍇
🆕📦🐚🍎🍆❗️ ➡️ box
📥 box 🆕🍎❗️❗️
📥 box 🆕🍎❗️❗️
📋 box❗️
🍉- apple - apple
How to make only a method take a type argument is covered in More on Classes.