How to declare the array type in swift -


so in swift playground file, trying execute following closure:

var list = [5, 4, 3]  var arraymultiplier = {(list:array) -> array in      value in list {         value*2         return list     } }  arraymultiplier(list) 

when though, error saying generic type array must referenced in <..> brackets, when put brackets, error.

what's right way declare array type input , return?

array generic type, meaning expects see actual type of members of array specified within < > following array:

var arraymultiplier = {(list: array<int>) -> array<int> in      // whatever want here } 

or, in case of arrays, there convenient syntax uses [ ] characters , omits need array reference @ all:

var arraymultiplier = {(list: [int]) -> [int] in      // whatever want here } 

i'm not sure original code sample trying do, looks might have been trying build new array each item multiplied 2. if so, might like:

let inputlist = [5, 4, 3]  let arraymultiplier = { (list: [int]) -> [int] in      var results = [int]()                         // instantiate new blank array of `int`     value in list {                           // iterate through array passed         results.append(value * 2)                 // multiply each `value` `2` , add `results`     }     return results                                // return results }  let outputlist = arraymultiplier(inputlist) 

or, obviously, efficiently achieve similar behavior using map function:

let outputlist = inputlist.map { $0 * 2 } 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -