如何将值分配给Swift中另一个结构中使用的结构中的变量?

ogsagwnx  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(99)

我正在学习Swift,刚刚发现了结构体。我有这个代码:

struct Time {
  var hour: Int
  var minute: Int
}

struct Class {
  var title: String //name of class
  var room: Int //room number
  var building: String
  var teacher: String //name of teacher
  var block: Character
  var startTime: Time
  var endTime: Time
}

var math = Class(title: "Math", room: 801, building: "Math Building", teacher: "Ms. Teacher", block: 'G', startTime: Time, endTime: Time)

如何以这种方式为小时和分钟变量赋值,或者是否有更好的方法?任何帮助都很感激。

gt0wga4j

gt0wga4j1#

你必须初始化(子)结构,然后将其传递给构造函数。

let startTime = Time(hour: 0, minute: 0)
let endTime = Time(hour: 12, minute: 60)
let math = Class(title: "Math", 
                 room: 801, 
                 building: "Math Building", 
                 teacher: "Ms. Teacher", 
                 block: "G", 
                 startTime: startTime, 
                 endTime: endTime)

或者,您也可以在我们将其作为参数传递时进行初始化,以使其简洁

let math = Class(title: "Math", 
                 room: 801, 
                 building: "Math Building", 
                 teacher: "Ms. Teacher", 
                 block: "G", 
                 startTime: Time(hour: 0, minute: 0), 
                 endTime: Time(hour: 12, minute: 60))

相关问题