Last active
March 28, 2016 17:46
-
-
Save sunshinejr/59230a94ad8ab01a0009 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: #Default associatedtype & overriding | |
//: Let's make an example of how can you use default associatedtype, to make clear what | |
//: it really does. | |
//: We will create generic protocol for Container, with associatedtype for ItemType. | |
//: Our ItemType will haave a default value of Int. | |
protocol Container { | |
associatedtype ItemType = Int | |
func getItem() -> ItemType | |
func getItems() -> [ItemType] | |
} | |
class Backpack: Container { // because ItemType has default associatedtype, we don't have to specify it | |
func getItem() -> Backpack.ItemType { | |
return 2 | |
} | |
func getItems() -> [Backpack.ItemType] { | |
return [2] | |
} | |
} | |
struct TypedBackpack<TypedItemType: StringLiteralConvertible>: Container { // but we can override current associatedtype quite easily | |
func getItem() -> TypedItemType { // Because ItemType doesn't need to conform to any protocol, we can easily pass our own ItemType | |
return "" | |
} | |
func getItems() -> [TypedItemType] { | |
return [""] | |
} | |
} | |
let backpack1 = Backpack() | |
let backpack2 = TypedBackpack<String>() | |
print(backpack1.getItem()) | |
print(backpack2.getItem()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment