首页 > 解决方案 > 在 swift 5 中,图像文字数组得到“表达式类型不明确,没有更多上下文”

问题描述

我是编码新手,正在尝试学习 Swift。我正在制作一个简单的“石头剪刀布”应用程序来练习使用 MVC。

我有一个数组(让 imagesArray = [图像文字,图像文字,图像文字]

当我在控制器中有图像数组时,它工作正常,但是当我尝试将它移动到模型时,我得到一个“表达式类型不明确,没有更多上下文”错误。模型中不允许使用图像数组吗?我的理解是数据应该保存在模型中,所以这就是我试图把它放在那里的原因。

任何想法将不胜感激:)

struct GameBrain {
    
    let images = [ #imageLiteral(resourceName: "rock"), #imageLiteral(resourceName: "paper"), #imageLiteral(resourceName: "scissors")]
    
    func playGame() -> Int {
        let choices = [0,1,2]
        let choice = choices.randomElement()
        return choice!
    }
    
    mutating func getWinner(choice: Int?) {
        
    }
}
class ViewController: UIViewController {
    
    var gameBrain = GameBrain()
    
    @IBOutlet weak var imageViewLeft: UIImageView!
    @IBOutlet weak var imageViewRight: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func goButton(_ sender: UIButton) {
        imageViewLeft.image = images[gameBrain.playGame()]
        imageViewRight.image = images[gameBrain.playGame()]
    }
}

标签: swiftmodel-view-controller

解决方案


如果您images进入模型,则必须调整参考

@IBAction func goButton(_ sender: UIButton) {
    imageViewLeft.image = gameBrain.images[gameBrain.playGame()]
    imageViewRight.image = gameBrain.images[gameBrain.playGame()]
}

显然不需要索引,所以这更简单

var playGame : UIImage { 
   return images.randomElement()! 
}

@IBAction func goButton(_ sender: UIButton) {
    imageViewLeft.image = gameBrain.playGame
    imageViewRight.image = gameBrain.playGame
}

推荐阅读