Loading

Swift Charts 报错:Initializer ... requires that .. conform to ‘Identifiable‘

1. 问题描述

在运行Swift Charts官方折线图示例时,出现了如下错误。

Initializer ‘init(_:content:)’ requires that ‘ContentView.MonthlyHoursOfSunshine’ conform to ‘Identifiable’

官方文档中的示例程序如下所示。

import SwiftUI
import Charts


struct ContentView: View {
    struct MonthlyHoursOfSunshine {
        var date: Date
        var hoursOfSunshine: Double

        init(month: Int, hoursOfSunshine: Double) {
            let calendar = Calendar.autoupdatingCurrent
            self.date = calendar.date(from: DateComponents(year: 2020, month: month))!
            self.hoursOfSunshine = hoursOfSunshine
        }

    }

    var data: [MonthlyHoursOfSunshine] = [
        MonthlyHoursOfSunshine(month: 1, hoursOfSunshine: 74),
        MonthlyHoursOfSunshine(month: 2, hoursOfSunshine: 99),
        // ...
        MonthlyHoursOfSunshine(month: 12, hoursOfSunshine: 62)

    ]

    var body: some View {
        Chart(data) {
            LineMark(
                x: .value("Month", $0.date),
                y: .value("Hours of Sunshine", $0.hoursOfSunshine)
            )
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2. 解决办法

解决办法是将MonthlyHoursOfSunshine结构修改为Identifialbe,修改后的代码如下所示。

import SwiftUI
import Charts


struct ContentView: View {
    struct MonthlyHoursOfSunshine:Identifiable {
    	id = UUID()
        var date: Date
        var hoursOfSunshine: Double

        init(month: Int, hoursOfSunshine: Double) {
            let calendar = Calendar.autoupdatingCurrent
            self.date = calendar.date(from: DateComponents(year: 2020, month: month))!
            self.hoursOfSunshine = hoursOfSunshine
        }

    }

posted @ 2023-03-23 21:56  realXuan  阅读(16)  评论(0编辑  收藏  举报  来源