How can I populate a dynamically sized 2D array in Swift 3.0 to be an X by 4 two-D array? -


i want write function in swift 3.0 populate 2d array of string arrays, meaning {{"mr.", "john", "q.", "public"} {"ms.", "jane", "e.", "doe"}...}

in program, titles in array of own, first, while middle initial , last names in own arrays together.

so far, have:

func build2dstringarray() -> [[string]]{     var col = 0     var row = 0     var string2darray = [[string]]()      title in titles{         string2darray[col][row].append(title){         firstname in firstnames{             string2darray[col][row].append(firstname){                 lasttwo in lasttwo{                     string2darray[col][row].append(middleinit)                     string2darray[col][row].append(lastname)                     col += 1                     row += 1                 }             }         }     } } return string2darray } 

but when run it, "index out of range." how can need. of now, need have 150 sets of 4 strings, altho cannot hardcode numbers. i've tried looking documentation , poor kind of thing. hence why come here.

one issue you're initializing [[string]] need append [string] every column. issue happens if 1 of arrays longer rest?

here's way number of [string]:

func zipintoarray<t>(arrays: [t]...) -> [[t]] {   var result = [[t]]()   var index = 0   while true {     var current = [t]()     array in arrays {       guard array.indices.contains(index) else { return result }       current.append(array[index])     }     result.append(current)     index += 1   } }  let = ["one a", "two a", "three a", "four a"] let b = ["one b", "two b", "three b"] let c = ["one c", "two c", "three c"] let d = ["one d", "two d", "three d"]  let big = zipintoarray(arrays: a, b, c, d)  print(big) // [["one a", "one b", "one c", "one d"], ["two a", "two b", "two c", "two d"], ["three a", "three b", "three c", "three d"]]  print(big[0][1]) // 2 b 

when function encounters end of of arrays returns. in way each row has same number of elements.

this doesn't follow addressing of "[col][row]" , instead used "[row][col]" feel that's minor detail, since latter paradigm followed many programmers. rows tend group of associated data , each group contained in single array. better might away array , instead use struct named properties.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -