我有以下串列:
let myList: [(String, Int, Double)] = [("A", 1, 1.5), ("B", 2, 2.5), ("C", 3, 3.5)]
我正在嘗試產生以下輸出
1) A | 1
2) B | 2
3) C | 3
如果我洗掉第二個元素,我希望輸出也能更新,就像這樣
1) A | 1
2) C | 3
我是 Swift 的新手,所以這讓我很頭疼,但是我該如何開始這樣的事情呢?這是我的功能,但我不確定這是否是正確的開始方式。我想知道如何獲得額外的符號并保持數字有序。(這個值將被傳遞給 UILabel,所以我必須將所有元素放在一個變數中result)
func displayString(myList: [(title: String, id: Int, value: Double)]) -> String {
var result = ""
for i in 0..<myList.count {
}
return result
}
uj5u.com熱心網友回復:
如果您在每一行都需要1)and ,請查看使用您可以訪問索引和專案的位置2)回圈遍歷陣列enumerated
它看起來像這樣:
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
}
輸出將是:
1) A | 1
2) B | 2
3) C | 3
但是,我敦促您探索諸如 etc 之類的高階函式filter, map, reduce,這將縮短您為執行這些操作而撰寫的代碼。
例如,您可以獲得類似的結果,例如:
func displayStringSwifty(myList: [(title: String,
id: Int,
value: Double)]) -> String
{
return myList.reduce("") { val, item in val "\(item.0) | \(item.1)\n" }
}
輸出將是
A | 1
B | 2
C | 3
更新
Leo Dabus 在評論中提供了一個更簡潔的版本:
myList.map { "\($0.title) | \($0.id)" }.joined(separator: "\n")
uj5u.com熱心網友回復:
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)" )
}
給你
1) A | 1
2) B | 2
3) C | 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/427954.html
上一篇:如何在函式中呼叫帶引數的閉包
