generics - Instantiate array of associated type in Swift -


i'm going through "guided tour" playground comes swift 2.2. in chapter on generics, extraordinarily cumbersome function declaration dumped on you:

func anycommonelements <t: sequencetype, u: sequencetype     t.generator.element: equatable,     t.generator.element == u.generator.element>     (lhs: t, _ rhs: u) -> bool {    lhsitem in lhs {       rhsitem in rhs {           if lhsitem == rhsitem {               return true           }       }   }  return false  } anycommonelements([1, 2, 3], [3]) 

the function returns whether or not 2 sequences have elements in common, simple enough.

the exercise chapter modify function return array of common elements between 2 sequences. function needs have return type like

(lhs: t, _ rhs: u) -> [t.generator.element] 

which seems simple enough, make array , put common elements in it, return it. nothing in book far has taught me how make new array of type [t.generator.element], don't know how proceed. naturally assumed work:

var result = [t.generator.element]() 

but yeah, doesn't compile. how solve exercise? (and isn't little advanced first introduction of generics?)

you're correct, should work. doesn't a known bug in swift compiler. have several options workaround:

  • var result: [t.generator.element] = []

  • var result = [] [t.generator.element]

  • var result = array<t.generator.element>()

(the trick give compiler enough context knows it's trying parse type name there. in [t.generator.element]() syntax incorrectly parses bracketed portion array literal.)


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -