I have the following list:
let myList: [(String, Int, Double)] = [("A", 1, 1.5), ("B", 2, 2.5), ("C", 3, 3.5)]
And I am trying to produce the following output
1) A | 1
2) B | 2
3) C | 3
If I delete the 2nd element I want the output to be updated as well, like this
1) A | 1
2) C | 3
I'm new to Swift, so this is a lot to wrap my head around but how would I start something like this? This is my function, but I am not sure if this is the right way to start. And I'm wondering how I can get the extra symbols and keep the numbers in order. ( this value is going to be passed to a UILabel, so I have to keep all the elements together in one variable result
)
func displayString(myList: [(title: String, id: Int, value: Double)]) -> String {
var result = ""
for i in 0..<myList.count {
}
return result
}
CodePudding user response:
If you need the 1)
and 2)
as well on every line, have a look at looping through arrays using enumerated
where you have access to the index as well as the item
It would look something like this:
func displayString(myList: [(title: String,
id: Int,
value: Double)]) -> String
{
var result = ""
// The first iteration, index is 0 and item is ("A", 1, 1.5)
// Second time, index is 1 and item is ("B", 2, 2.5) etc
for (index, item) in myList.enumerated()
{
// Since index starts from 0, you add 1 to start from 1 in the output
result = "\(index 1)) \(item.title) | \(item.id)\n"
}
return result
}
The output would be:
1) A | 1
2) B | 2
3) C | 3
However, I urge you to explore higher order functions like filter, map, reduce
etc which will shorten the code you write to do these things.
For example, you could get a similar result with something like:
func displayStringSwifty(myList: [(title: String,
id: Int,
value: Double)]) -> String
{
return myList.reduce("") { val, item in val "\(item.0) | \(item.1)\n" }
}
The output would be
A | 1
B | 2
C | 3
As a challenge and practice, you could try to use the second option to create the output similar to the first with the 1), 2) etc added as well
CodePudding user response:
let myList: [(String, Int, Double)] = [
("A", 1, 1.5),
("B", 2, 2.5),
("C", 3, 3.5)]
myList.enumerated().forEach { (index, element) in
print( "\(index 1)) \(element.0) | \(element.1)" )
}
gives you
1) A | 1
2) B | 2
3) C | 3