我正在尝试显示数组的随机项目,我有此文件:
//VerseModel.swift
import Foundation
struct VerseModel {
var verse = ""
var reference = ""
var date = Date()
}
此文件:
//VersesMock.swift
import Foundation
struct VersesMock {
var verses: Array<VerseModel> = [
VerseModel(verse: "Teste 1", reference: "Mt 13:2", date: Date()),
VerseModel(verse: "Teste 2", reference: "Mt 14:2", date: Date()),
VerseModel(verse: "Teste 3", reference: "Mt 15:2", date: Date()),
VerseModel(verse: "Teste 4", reference: "Mt 16:2", date: Date()),
VerseModel(verse: "Teste 5", reference: "Mt 17:2", date: Date()),
VerseModel(verse: "Teste 6", reference: "Mt 18:2", date: Date()),
VerseModel(verse: "Teste 7", reference: "Mt 19:2", date: Date()),
VerseModel(verse: "Teste 8", reference: "Mt 20:2", date: Date()),
VerseModel(verse: "Teste 9", reference: "Mt 21:2", date: Date())
]
}
这是
import UIKit
final class HomeViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var verseLbl: UILabel!
var user = UserMock()
var verses = VersesMock().verses
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = user.name
verseLbl.text = verseModel
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我正在尝试做这样的事情,但是它说
“无法将类型'[VerseModel]'的值分配为类型'字符串?'”
是的,我知道我不能分配它们,因为它们来自不同类型,那么如何分配它们呢?
答案 0 :(得分:1)
在HomeViewController
类中,您可以尝试使用verseLbl
向Int.random
分配随机值,例如,而不是分配verseModel
,您应该分配{{ 1}}类,例如
VersesMock
答案 1 :(得分:0)
您可以使用在 Swift 4.2 中引入的randomElement()
。
verseLbl.text = verses.randomElement()?.verse