[英]how to access a member of struct that is a member of array in swift
我有一個名為 items1 的數組,它的成員是一個結構 Team1,有 2 個成員 id:UUID() 和 round:Int 我想創建一個 function 來計算數組的輪成員的總和。 誰能幫我理解我在下面的代碼中做錯了什么:
import Foundation
struct vrb {
static var items1 = [
Team1(id: UUID(), round: 14),
Team1(id: UUID(), round: 20),
Team1(id: UUID(), round: 24),
]
static var total1: Int = 0
}
func Total() -> Int {
var sum = vrb.items1[round.reduce(0, +)]
}
struct Team1: Identifiable {
var id: UUID
var round: Int
}
你有點接近。 你要找的是這個:
func total() -> Int {
vrb.items1.map(\.round).reduce(0, +)
}
Map(“將每個元素”) items1
轉換為其.round
值,然后將它們相加。
(請注意,函數、方法和變量應該有一個前導小寫字母,而像結構這樣的類型應該有一個前導大寫字母。這使得其他 Swift 開發人員更容易理解您的代碼。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.