swift2 - Associated Types in Swift -


what associated types in swift programming language? used for?

as per swift programming language book:

when defining protocol, it useful declare 1 or more associated types part of protocol’s definition. associated type gives placeholder name (or alias) type used part of protocol. actual type use associated type not specified until protocol adopted. associated types specified typealias keyword.

the above text not clear me. lot if can explain associated types example.

also, why useful declare associated type part of protocol definition?

you have protocol defines methods , perhaps properties implementing type must provide. of methods/properties use or return objects of different type type implementing protocol. so, instance, if have protocol defines types of collections of objects, might define associated type defines elements of collection.

so let's want protocol define stack, stack of what? doesn't matter, use associated type act place holder.

protocol stack {     // typealias element - swift 1     associatedtype element // swift 2+     func push(x: element)     func pop() -> element? } 

in above element type of whatever objects in stack. when implement stack, use typealias specify concrete type of stack elements.

class stackofint: stack {     typealias element = int // not strictly necessary, can inferred     var ints: [int] = []      func push(x: int)     {         ints.append(x)     }      func pop() -> int?     {         var ret: int?         if ints.count > 0         {             ret = ints.last             ints.removelast()         }         return ret     } } 

in above, have defined class implements stack , says that, class, element int. frequently, though, people leave out typealias because concrete type of element can inferred method implementations. e.g. compiler can @ implementation of push() , realise type of parameter element == int in case.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -