iOS 展开 SystemSound

iOS unwrapping SystemSound

我在 UserDefaults 中存储了一个 Int。 Int 将作为 audioOptionsList 的索引,一个对象数组,每个对象都有一个 SystemSoundID 属性.

这会因错误而崩溃:Could not cast value of type 'NSTaggedPointerString' (0x7fff87b33c28) to 'NSNumber' (0x7fff87bf4e00).

    var soundToPlay = SystemSoundID(1322)

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if UserDefaults.standard.value(forKey: "timerSoundSelection") != nil {
            
            let storedIndex = UserDefaults.standard.value(forKey: "timerSoundSelection")!
            print("stored index is: \(storedIndex)") //prints a non-optional int as expected.
            soundToPlay = audioOptionsList[storedIndex as! Int].sound //crashes with error
            
        } else {
            soundToPlay = SystemSoundID(1322)
        }

您的密钥存储为 String 而不是 Int ,使用 string(forKey: 然后转换它

if let stored = UserDefaults.standard.string(forKey: "timerSoundSelection") 
 , let value = Int(stored) { }