Skip to content

Instantly share code, notes, and snippets.

//: #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
protocol CurrencyProtocol { }
extension CurrencyProtocol {
typealias Currency = Double
}
struct ReallyImportantCurrencyStruct {
typealias Currency = Double
}
protocol CurrencyProtocol {
typealias Currency = Double
}
struct ReallyImportantCurrencyStruct: CurrencyProtocol {
func currencyFunction() -> ReallyImportantCurrencyStruct.Currency {
return 2.0
}
}
let currency = ReallyImportantCurrencyStruct()
print(currency.currencyFunction())
let currencies = [CurrencyProtocol]()
//: #typealias & associatedtype magic
//: ##Let's make a protocol without typealias (now associatedtype)
protocol Testable {
}
//: ##And another one with typealias
//: You could think, that the below typealias is just making
//: a typealiast for Int. In fact, we actually created a
struct LazyType {
lazy var soomethingLazy: String = {
return "Test lazy instance method"
}()
}
struct LazyType {
// Normal usage
lazy var soomethingLazy: String = {
return "Test lazy instance method"
}()
// Lazy in statics
static var somethingLazy: String = {
return "Test lazy static method"
// swift-tools-version:4.0