swift - 数组错误

标签 swift macos

我正在尝试从 .txt 文件读取记录并将它们存储为结构集合,但我正在努力修复此错误:

"Missing argument for parameter 'year' in call

这是我的代码:

struct DataSet: CustomStringConvertible {

var year: Int
var month: Int
var tmax: Double
var tmin: Double
var airfrost: Int
var rain: Double
var sun: Double

var description: String {

    return "\(year) + \(month) + \(tmax) + \(tmin) + \(airfrost) + \(rain) +  \(sun)"

}
}


let path = "/Users/sc16hsm/Desktop/CW2/data/bradford.txt"

 var data = [DataSet]()
var temp = DataSet()

if let contents = try? String(contentsOfFile: path) {

let filtered = contents.components(separatedBy: "\n")

for line in filtered {
    let x = line.components(separatedBy: " ").filter{$0 != ""}

    let x = line.components(separatedBy: " ")

    temp.year = Int(x[0])
    temp.month = Int(x[1])
    temp.tmax = Double(x[2])
    temp.tmin = Double(x[3])
    temp.airfront = Int(x[4])
    temp.rain = Double(x[5])
    temp.sun = Double(x[6])
    data.append(temp)
    print(x)
}

任何帮助将不胜感激。

最佳答案

如果结构体的成员没有初始值,则必须使用成员初始化器。默认初始化程序不起作用。

你必须在循环内编写

   let temp = DataSet(year: Int(x[0])!,
                       month:  Int(x[1])!,
                       tmax:  Double(x[2])!,
                       tmin: Double(x[3])!,
                       airfrost: Int(x[4])!,
                       rain: Double(x[5])!,
                       sun: Double(x[6])!)
    data.append(temp)

请使用代码完成来获取完整的语法。

关于swift - 数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48988700/

相关文章:

ios - 如何阻止 UIView 与 tableview 一起滚动?

swift - 如何解码可以是 String 或 NSNumber 的 JSON 值?

ios - 在 UISearchController 中隐藏搜索栏上的取消按钮

ios - 在 Objective-C 框架中使用 Swift 闭包

swift - 我的 API 请求代码产生了一个我无法调试或理解的错误

cocoa - Apple 红外 Remote 编程

c++ - 调整 native 窗口大小

macos - 如何让OpenGlView的init函数运行?

objective-c - 渲染/快照 SpriteKit 场景到 NSImage

macos - 为什么在 iTerm2 中 OSX 上的 emacs 看不到 C-S-<up>?