gpt4 book ai didi

swift - 如何确保在数据加载之前我不会访问数据?

转载 作者:行者123 更新时间:2023-11-30 12:03:08 25 4
gpt4 key购买 nike

我是编程新手,我的代码收到错误: fatal error :在解包可选值时意外发现 nil2017-10-27 16:06:16.755817+0200 Inspireme1.0[836:85307] fatal error :在展开可选值时意外发现 nil(lldb)

新错误: fatal error :索引超出范围2017-10-27 19:08:05.488502+0200 Inspireme1.0[1262:771572] fatal error :索引超出范围(lldb)

我已经在这里查找过,但我不知道如何将其应用于我的情况:如何确保在加载 socket 之前我不会访问它们

这是我的代码:

  var quotes: RandomItems! = RandomItems([
"Jonas",
"Mary",
"Michael",
"Jeff",
"Sarah",
])



@IBAction func PresentText(_ sender: Any) {


PresentingLabel.text = quotes.next() //<-- Error


}


struct RandomItems: Codable
{
var items : [String]
var seen = 0

init(items:[String], seen: Int)
{
self.items = items
self.seen = seen
}

init(_ items:[String])
{ self.init(items: items, seen: 0) }


mutating func next() -> String
{
let index = Int(arc4random_uniform(UInt32(items.count - seen)))
let item = items.remove(at:index) //<--Error
items.append(item)
seen = (seen + 1) % items.count
return item
}
func toPropertyList() -> [String: Any] {
return [
"items": items,
"seen": seen
]
}


}

var randomItems: RandomItems?

override func viewDidAppear(_ animated: Bool) {
// Code to load the struct again after the view appears.
let defaults = UserDefaults.standard
quotes = defaults.codable(RandomItems.self, forKey: "quotes")
}

override func viewWillDisappear(_ animated: Bool) {
// Code to save struct before the view disappears.
let defaults = UserDefaults.standard
if let quotes = quotes {
defaults.set(codable: quotes, forKey: "quotes")
}
}
}

最佳答案

引号不应是可选的。

您需要处理 viewDidAppear 中的可选结果,而不是假设引号始终会展开。

quotes = defaults.codable(RandomItems.self, forKey: "quotes") ?? 随机项([])

在viewDidLoad中:

defaults.set(codable: quotes, forKey: "quotes")

关于swift - 如何确保在数据加载之前我不会访问数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46979934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com