2017-09-23 47 views
0

,當我得到的錯誤在最後一行「有望聲明」試圖值添加到字典中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

你得到這個錯誤,因爲你行的setValue 不能只是住在這裏你的類中沒有被的方法內。當然,這真的取決於你想實現什麼(以及如何),但你可以把它放在你BookingSystem類的init()方法,或者你可以建立自己的自定義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,你應該使用:

yourDictionnary["yourKey"] = yourValue 

希望它能幫助,如果您有任何問題,只是隨意問:)

+0

爲什麼你讓'Table'擴展'NSObject'? – rmaddy

+0

這是這裏只是舉個例子,即使它不是真正相關的問題。但是,如果這個類的內容只限於我寫的內容,那麼你顯然不需要擴展NSObject。 – Alex

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

爲什麼要用'的setValue(_:forKey :) '? – rmaddy