如何修复“线程1:致命错误:在展开可选值时意外发现nil".在斯威夫特 [英] How can I fix "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" in Swift

查看:90
本文介绍了如何修复“线程1:致命错误:在展开可选值时意外发现nil".在斯威夫特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将音乐添加到我创建的游戏中.但是我得到了错误:

I am trying to add music to a game I created. But I am getting the error:

线程1:致命错误:展开一个可选值时意外发现nil.

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

我在堆栈溢出(),但我不知道这对我的代码有何作用.

I found another post on Stack Overflow (What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?), but I do not understand how this applies to my code.

这是我的代码:

import UIKit
import SpriteKit
import GameplayKit
import AVFoundation

class GameViewController: UIViewController {
    var player:AVAudioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            let audioPath = Bundle.main.path(forResource: "HomeSoundtrack", ofType: "m4a")
            try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
        }
        catch {
        }

        let session = AVAudioSession.sharedInstance()

        do {
            try session.setCategory(AVAudioSessionCategoryPlayback)
        }
        catch {
        }

        player.play()

        if let view = self.view as! SKView? {
            // Load the SKScene from 'GameScene.sks'
            if let scene = SKScene(fileNamed: "GameScene") {
                // Set the scale mode to scale to fit the window
                scene.scaleMode = .aspectFill

                // Present the scene
                view.presentScene(scene)
            }

            view.ignoresSiblingOrder = true

            view.showsFPS = false
            view.showsNodeCount = false
        }
    }

    override var shouldAutorotate: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            return .allButUpsideDown
        } else {
            return .all
        }
    }
}

推荐答案

可选值是可能包含nil的值,如果要获取其值,则必须将其包装

Optional value is value that may be contain nil if you want to get its value you have to wrapping it

但是使用安全包装而不是强制包装!

but use safe wrapping not force wrapping !

选中此行

let audioPath = Bundle.main.path(forResource: "HomeSoundtrack", ofType: "m4a")

audioPath是一个Optional,因此它可能包含nil值,前提是您编写了HomeSoundtrack错误或找不到文件,则audioPath将为空

audioPath is An Optional so it may contain nil value assume that you write HomeSoundtrack Wrong or file not found then audioPath will be nil

然后您强行包装!它.在此行中,如果audioPathnil,它将崩溃

then you force wrapping ! it . in this line if audioPath is nil then it will crash

try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)

可以安全地完成

  let audioPathURL =  Bundle.main.url(forResource: "HomeSoundtrack", withExtension: "m4a")
        {
            do {
                player = try AVAudioPlayer(contentsOf:  audioPathURL)
            }  catch {
                print("Couldn't load HomeSoundtrack file")

            }
        }

这篇关于如何修复“线程1:致命错误:在展开可选值时意外发现nil".在斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆