Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show all the elements of an array in swift?

Tags:

xcode

ios

swift

I have an array like this: var array = ["Chinese", "Italian", "Japanese", "French", "American"]

I want to print out all separate elements on a new line.

How can I do this?

like image 680
user3725848 Avatar asked Jun 10 '14 11:06

user3725848


People also ask

How do I filter an array in Swift?

To filter an array in Swift: Call the Array. filter() method on an array. Pass a filtering function as an argument to the method.


2 Answers

My personal favorite for debugging purposes is dump() which also prints which index the element has. Perfect if you have arrays within an array too.

var array = ["Chinese", "Italian", "Japanese", "French", "American"] dump(array) 

This will generate the following output

▿ 5 elements   - [0]: Chinese   - [1]: Italian   - [2]: Japanese   - [3]: French   - [4]: American 
like image 177
Viktor Nilsson Avatar answered Sep 29 '22 14:09

Viktor Nilsson


You can simply iterate through the array like this and print out all elements on a new line:

for element in array {   println(element) } 

UPDATE

For Swift 2 and Swift 3:

for element in array {   print(element) } 

Or if you want it on the same line:

for element in array {   print(element, terminator: " ") } 
like image 29
Bas Avatar answered Sep 29 '22 14:09

Bas