swift - 在 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()]
}
}
解决方案
如果您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
}
推荐阅读
- windows - 命令提示符中没有时间戳
- android - mapbox 层 minzoom/maxzoom 有时不起作用
- c# - PageIndexChanging 问题
- javascript - 错误:第一个参数必须是 File 或 Blob 对象
- pandas - 来自pandas数据框的区域海拔分布直方图,python
- c++ - 如何在 C++ 中动态输入数组?
- php - 在 symfony 4.2 中按值动态获取服务
- amazon-web-services - 如何将角色分配给作为 Auto-Scaling 的一部分启动的 EC2 实例
- mysql - 重命名多个 MySQL 表的前缀
- airflow - 如何在 HttpSensor 运算符中拉取 xCom