Reputation:
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
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
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
Reputation: 42143
Have you tried this ?
label.text = arrayOfInt.map { "car \($0)" }.joined(separator:"\n")
Upvotes: 6