Tutorial by Examples

It is possible to force the type parameters of a generic class to implement a protocol, for example, Equatable class MyGenericClass<Type: Equatable>{ var value: Type init(value: Type){ self.value = value } func getValue() -> Type{ return self....
Generics are placeholders for types, allowing you to write flexible code that can be applied across multiple types. The advantage of using generics over Any is that they still allow the compiler to enforce strong type-safety. A generic placeholder is defined within angle brackets <>. Generic...
A generic class with the type parameter Type class MyGenericClass<Type>{ var value: Type init(value: Type){ self.value = value } func getValue() -> Type{ return self.value } func setValue(value: Type){ self.value = value }...
Generic classes can be inherited: // Models class MyFirstModel { } class MySecondModel: MyFirstModel { } // Generic classes class MyFirstGenericClass<T: MyFirstModel> { func doSomethingWithModel(model: T) { // Do something here } } class MySecondGe...
A function that extends the functionality of the array by creating an object oriented remove function. // Need to restrict the extension to elements that can be compared. // The `Element` is the generics name defined by Array for its item types. // This restriction also gives us access to `index(...
Let's take this example without using generics protocol JSONDecodable { static func from(_ json: [String: Any]) -> Any? } The protocol declaration seems fine unless you actually use it. let myTestObject = TestObject.from(myJson) as? TestObject Why do you have to cast the result to T...
It's possible to specify several type constraints for generics using the where clause: func doSomething<T where T: Comparable, T: Hashable>(first: T, second: T) { // Access hashable function guard first.hashValue == second.hashValue else { return } // Access compa...

Page 1 of 1