user7961001
user7961001

Reputation:

how to get array entry to print on new line each time (swift3)

When my array is being printed the entries are bing printed on the same line. I have tried \n command in a couple of ways but I have not gotten it to work. I just want to print 1 array entry on 1 line then move to the next line. pic of array printed out

var arrayOfInt = [Int]()


 let cars = arrayOfInt.map { "car \($0)" }
  label.text =  String(describing: cars)

Upvotes: 2

Views: 3738

Answers (4)

yoodu
yoodu

Reputation: 112

try this

arrayOfInt.forEach{print($0)}

Upvotes: 6

Womble
Womble

Reputation: 5290

An extension to list out the elements of an array, along with their respective indices.

extension Array
{
    /// Prints self to std output, with one element per line, prefixed by
    /// the element's index in square brackets.

    public func printByIndex(delimiter: String = " ")
    {
        for (index, value) in self.enumerated()
        {
            print("[\(index)]\(delimiter)\(value)")
        }
    }
}

Usage:

["Foo", "Bar", "Baz"].printByIndex()

// [0] Foo
// [1] Bar
// [2] Baz


["Foo", "Bar", "Baz"].printByIndex(delimiter: " = ")

// [0] = Foo
// [1] = Bar
// [2] = Baz

Upvotes: 0

Edison
Edison

Reputation: 11987

Alain's answer is sweet. Thank you so much. I used it everywhere lol.

I am adding another version with JSON array objects and decoding with JSONDecoder. You might have 100 objects and it's very difficult to read each object separately in the console.

calendarObject = try JSONDecoder().decode(Array< CalendarObject >.self, from: data)
let objs = calendarObject.map { "objs \($0)" }.joined(separator:"\n")
print(objs)

// objs calendarObject(event: "aaa", where: "xmarksthespot", from: "1:00", to: "2:00")
// objs calendarObject(event: "bbb", where: "ymarksthespot", from: "2:00", to: "3:00")
// objs calendarObject(event: "ccc", where: "zmarksthespot", from: "3:00", to: "4:00")

Upvotes: 0

Alain T.
Alain T.

Reputation: 42143

Have you tried this ?

label.text = arrayOfInt.map { "car \($0)" }.joined(separator:"\n")

Upvotes: 6

Related Questions