2017-03-24 37 views
1

我知道這是新手問題,但我無法在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是讓:

let

這是currentUser變量的屏幕截圖時currentUser是VAR:

enter image description here 預先感謝您!

+0

你需要使用'let'。這解決了你的直接問題。現在澄清你的意思是「我不能設置任何屬性」。 – rmaddy

+0

@rmaddy我的意思是,當我寫「let currentUser:VKUserProfile = VKUserProfile()」,然後設置變量像「currentUser.userId = user [」id「]爲?NSNumber」我的currentUser仍然是空的。變量未設置。沒有任何數據存儲在currentUser中。我將這個對象傳遞給我的UIViewController並且不能使用它(因爲currentUser沒有數據)。 –

+1

你確定'user'對於給定的鍵有一個值,它的值是給定的類型嗎?你真的需要[編輯]你的問題來解決設置屬性的問題,而不是使用'let/var'。 – rmaddy

回答

3

看來,當你使用:

var currentUser = VKUserProfile() 

你的代碼的其餘部分正確填寫currentUser,你可以看到的值當您打印currentUser

但使用var會發出警告,因爲您從未實際重新指定currentUser

所以你理所當然地將var更改爲let並且不做任何其他更改。但是現在當您打印currentUser時,您看不到與您在使用var時所做的輸出相同的輸出,如您在問題中發佈的屏幕截圖所示。

看來這是Xcode調試器的問題。

打印currentUser的單個屬性顯示預期的輸出。

所以最後,這只不過是Xcode調試器中的一個bug。即使將var更改爲let後,您的代碼仍可以正常使用。

+0

謝謝你的幫助! –