ios - Add an element to an array in Swift -


suppose have array, example:

var myarray = ["steve", "bill", "linus", "bret"] 

and later want push/append element end of said array, get:

["steve", "bill", "linus", "bret", "tim"]

what method should use?

and case want add element front of array? there constant time unshift?

you had couple of options appending element array. in betas, use += operator append individual element, no longer case. can still use append function.

anarray.append("this string") 

if you're looking append more elements different array array, can still use += operator, or extend method.

anarray += ["moar", "strings"] anarray.extend(["moar", "strings"]) 

to insert single object @ beginning of array, can use insert method.

anarray.insert("this string", atindex: 0) 

to insert contents of different array @ beginning of array, can use splice method.

anarray.insertcontentsof(["so", "many", "strings"], at: 0) 

in case of insert , insertcontentsof, seconds argument can valid index of receiving array.

more information can found in "collection types" chapter of "the swift programming language", starting on page 110.


as of swift 3, above examples must written follows.

to add new element end of array.

anarray.append("this string") 

to append different array end of array.

anarray += ["moar", "strings"] anarray.append(contentsof: ["moar", "strings"]) 

to insert new element array.

anarray.insert("this string", at: 0) 

to insert contents of different array array.

anarray.insert(contentsof: ["moar", "strings"], at: 0) 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -