The Swift Programming Language (Swift 2) -7 Generics
21 September 2015
//: ## Generics//://: Write a name inside angle brackets to make a generic function or type.//:funcrepeatItem<Item>(item:Item,numberOfTimes:Int)->[Item]{varresult=[Item]()for_in0..<numberOfTimes{result.append(item)}returnresult}repeatItem("knock",numberOfTimes:4)//: You can make generic forms of functions and methods, as well as classes, enumerations, and structures.//:// Reimplement the Swift standard library's optional typeenumOptionalValue<Wrapped>{caseNonecaseSome(Wrapped)}varpossibleInteger:OptionalValue<Int>=.NonepossibleInteger=.Some(100)//: Use `where` after the type name to specify a list of requirements—for example, to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass.//:funcanyCommonElements<T:SequenceType,U:SequenceTypewhereT.Generator.Element:Equatable,T.Generator.Element==U.Generator.Element>(lhs:T,_rhs:U)->Bool{forlhsIteminlhs{forrhsIteminrhs{iflhsItem==rhsItem{returntrue}}}returnfalse}anyCommonElements([1,2,3],[3])//: > **Experiment**://: > Modify the `anyCommonElements(_:_:)` function to make a function that returns an array of the elements that any two sequences have in common.//://: Writing `<T: Equatable>` is the same as writing `<T where T: Equatable>`.//://: [Previous](@previous)