Skip to content

Instantly share code, notes, and snippets.

@sunshinejr
Last active March 28, 2016 17:46
Show Gist options
  • Save sunshinejr/59230a94ad8ab01a0009 to your computer and use it in GitHub Desktop.
Save sunshinejr/59230a94ad8ab01a0009 to your computer and use it in GitHub Desktop.
//: #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