簡體   English   中英

無法在Swift中訪問可編碼的結構值

[英]Unable to access codable struct values in Swift

我從服務中獲取用戶數據作為json並解碼為Codable User結構。 我可以在獲取響應的地方訪問該屬性,但是我想在其他地方訪問該User struct屬性,例如在另一個類,函數等中訪問。

我對此並不陌生,我認為理想的方法是“在獲取數據時,將數據存儲到Core DataUser Defaults ,然后相應地更新我的視圖。

請提出最佳和適當的方法是什么,否則是否有任何方法可以直接訪問可編碼的結構值。

這是我的可編碼結構-

struct User: Codable {
let name : String?

enum CodingKeys: String, CodingKey {
    case name = "Name"
}

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    name = try values.decodeIfPresent(String.self, forKey: .name)
  }
}

我在某些函數中訪問struct的錯誤方式是-

UserInfo.CodingKeys.name.rawValue
//Output is the key string - 'Name'

您可以嘗試使用單例引用

struct User: Codable {

    let name : String?

    enum CodingKeys: String, CodingKey {
        case name = "Name"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decodeIfPresent(String.self, forKey: .name)
        User.shared = self
    }
}

創建另一個保存引用的類。 User

final class AppGlobalManager  {
       static let sharedInstance = AppGlobalManager()

       var currentUser: User? // Initialise it when user logged in   

       private init()

}

然后,您可以按以下方式訪問任何用戶數據

AppGlobalManager.sharedInstance.currentUser.name

我認為static可以幫助您

struct User: Codable {
 let name : String?

 private enum CodingKeys: String, CodingKey {
  case name = "Name"
 }
}

假設在這里獲取數據

class FetchingClass{
  static var user: User?

 func fetchData(){
  //After Url request success
  do {
  //assign directly to static varibale user
  FetchingClass.user = try JSONDecoder().decode(User.self, from: data)
} catch _ {
   }
  }
}

在不使用coreDataUserDefaults情況下,在任何需要的地方使用

class AnotherClass{
 func anotherClassFunc(){
 //use if let or guard let
  if let user = FetchingClass.user{
  print(user.name)
 }
 //or
 if let FetchingClass.user != nil {
  print(FetchingClass.name)
  }
 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM