我知道這是新手問題,但我無法在stackoverflow或google上找到答案。Xcode警告 - 變量從未發生變異
我開始用Swift 3語言編寫項目。這裏是我的模型類:
class VKUserProfile: NSObject {
var userId: NSNumber?
var userName: String?
var userEmail: String?
var userMobilePhone: String?
var userPictureUrl: URL?
}
然後,我用它在另一個類:
private func convert(user: Dictionary<String, Any>) -> VKUserProfile {
var currentUser: VKUserProfile = VKUserProfile()
currentUser.userId = user["id"] as? NSNumber
return currentUser
}
的Xcode警告我上線 「變種currentUser:VKUserProfile = VKUserProfile()」。好吧,但是當我將其更改爲「let currentUser:VKUserProfile = VKUserProfile()」時 - 我無法設置任何屬性(對象爲空)。那麼有人可以描述我這個過程,爲什麼Xcode會發出警告,我該如何解決這個問題。
UPDATE: 這裏是currentUser變量的屏幕截圖時currentUser是讓:
這是currentUser變量的屏幕截圖時currentUser是VAR:
你需要使用'let'。這解決了你的直接問題。現在澄清你的意思是「我不能設置任何屬性」。 – rmaddy
@rmaddy我的意思是,當我寫「let currentUser:VKUserProfile = VKUserProfile()」,然後設置變量像「currentUser.userId = user [」id「]爲?NSNumber」我的currentUser仍然是空的。變量未設置。沒有任何數據存儲在currentUser中。我將這個對象傳遞給我的UIViewController並且不能使用它(因爲currentUser沒有數據)。 –
你確定'user'對於給定的鍵有一個值,它的值是給定的類型嗎?你真的需要[編輯]你的問題來解決設置屬性的問題,而不是使用'let/var'。 – rmaddy