我收到错误" 预期声明"在尝试将值添加到字典tablesBooked的最后一行时。
class BookingSystem {
var tablesBooked = Dictionary<Int, String>()
var table = Table(tableID: 1 , tableCapacity: 2, status: "A")
var bookings = [Booking]()
tablesBooked.setValue(table.status, forKey: table.tableID)
}
答案 0 :(得分:0)
使用init方法:
class BookingSystem {
var tablesBooked = Dictionary<Int, String>()
var table = Table(tableID: 1 , tableCapacity: 2, status: "A")
var bookings = [Booking]()
init() {
tablesBooked.setValue(table.status, forKey: table.tableID)
}
}
答案 1 :(得分:0)
您收到此错误的原因是您的行setValue 不能只是在您的类中居住,而不是在方法中。当然,这实际上取决于你想要完成什么(以及如何),但你可以将它放在init()
类的BookingSystem
方法中,或者你可以构建自己的自定义{{1} }。
以下是它的样子:
init()
我故意在这里添加了 import Foundation
class Booking {
// Some interesting things here
}
class Table : NSObject {
// MARK: Properties
var tableID: Int
var tableCapacity: Int
var status: String
// MARK: Initializers
init(tableID: Int, tableCapacity: Int, status: String) {
self.tableID = tableID
self.tableCapacity = tableCapacity
self.status = status
}
}
class BookingSystem {
// MARK: Properties
var tablesBooked = [Int: String]()
var table = Table(tableID: 1 , tableCapacity: 2, status: "A")
var bookings = [Booking]()
// MARK: Initializers
init() {
// I am not sure what you are trying to do here, but anyway you should add it in a custom method or your init. If I were to use the code in your example, you would add this here:
tablesBooked[table.tableID] = table.status
}
// ...
}
课程,只是为了向您展示如何创建自己的自定义初始化的示例。
此外,此处值得一提的另一件事是Table
没有Swift Dictionaries
方法。相反,要将对象添加到setValue:forKey:
,您应该使用:
Dictionary
希望它有所帮助,如果您有任何问题,请随意询问:)