protocol in swift

23
Protocol in Swift

Upload: yusuke-kita

Post on 05-Aug-2015

198 views

Category:

Engineering


3 download

TRANSCRIPT

Protocol in Swift

What's protocol?

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or

piece of functionality.

The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of

those requirements.

Examples

struct Int• Equatable

• Comparable

• IntegerArithmeticType, _IntegerArithmeticType

• SignedIntegerType, _SignedIntegerType

• IntegerType, _IntegerType

protocol Equatable {

func ==(lhs: Self, rhs: Self) -> Bool}

protocol Comparable : Equatable {

func <(lhs: Self, rhs: Self) -> Bool func <=(lhs: Self, rhs: Self) -> Bool func >=(lhs: Self, rhs: Self) -> Bool func >(lhs: Self, rhs: Self) -> Bool}

protocol IntegerArithmeticType : _IntegerArithmeticType, Comparable {

func +(lhs: Self, rhs: Self) -> Self func -(lhs: Self, rhs: Self) -> Self func *(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self func %(lhs: Self, rhs: Self) -> Self

func toIntMax() -> IntMax}

struct Array<T>• CollectionType

• SequenceType

• _CollectionDefaultsType

• _CollectionGeneratorDefaultsType

• MutableCollectionType

• Sliceable, _Sliceable

• _DestructorSafeContainer

protocol CollectionType : SequenceType, _CollectionDefaultsType, _CollectionGeneratorDefaultsType { subscript (position: Self.Index) -> Self.Generator.Element { get }

var isEmpty: Bool { get }

var count: Self.Index.Distance { get }}

protocol SequenceType {

typealias Generator : GeneratorType

func generate() -> Self.Generator

func underestimateCount() -> Int

func map<T>(@noescape transform: (Self.Generator.Element) -> T) -> [T]

func filter(@noescape includeElement: (Self.Generator.Element) -> Bool) -> [Self.Generator.Element]}

protocol MutableCollectionType : CollectionType { subscript (position: Self.Index) -> Self.Generator.Element { get set }}

protocol Sliceable : _Sliceable {

typealias SubSlice : _Sliceable subscript (bounds: Range<Self.Index>) -> Self.SubSlice { get }}

Take a look inside Swift module for

more detail

Apple introduced Swift 2 in WWDC

2015

Protocol-oriented programming in Swift

Protocol extensionThis allows you to define behavior on protocols

themselves, rather than in each type’s individual conformance or in a global function.

protocol CustomStringConvertible {

var description: String { get }}

extension CustomStringConvertible {

var capitalizedDescription: String { return self.description.capitalizedString } var uppercaseDescription: String { return self.description.uppercaseString } var lowercaseDescription: String { return self.description.lowercaseString }}

Demo

Protocols > Superclasses

Protocol extensions = magic(almost)

Thank you