我知道未解决的标识符在Swift中通常很容易解决,但我仍然在努力解决一些困难。我知道我没有声明我需要的实例或变量,但我不确定这样做的正确方法。这是我的代码:
import UIKit
import Foundation
func setButton(viewInfo:ChemistryViewInfo, inout button:UIButton, index:Int) {
let buttonInfo = viewInfo.buttons[0]
button.titleLabel?.text = buttonInfo.scale
button.backgroundColor = buttonInfo.color
}
class ChemistryMasterViewController: UIViewController {
@IBOutlet weak var chemistryButton0: UIButton!
@IBOutlet weak var chemistryButton1: UIButton!
@IBOutlet weak var chemistryButton2: UIButton!
@IBOutlet weak var chemistryButton3: UIButton!
@IBOutlet weak var chemistryButton4: UIButton!
@IBOutlet weak var chemistryButton5: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if let viewInfo = viewInfo {
setButton(viewInfo, button: &chemistryButton0, index: 0)
setButton(viewInfo, button: &chemistryButton1, index: 1)
setButton(viewInfo, button: &chemistryButton2, index: 2)
setButton(viewInfo, button: &chemistryButton3, index: 3)
setButton(viewInfo, button: &chemistryButton4, index: 4)
setButton(viewInfo, button: &chemistryButton5, index: 5)
}
}
}
和...
import Foundation
import UIKit
let chemistryViewChoice = ["pH":
ChemistryViewInfo(
text: "pH",
description: "Most living things depend on proper pH level to sustain life.",
buttons: [
ChemistryButtonInfo(scale: "6.2", color: UIColor(red: 212, green: 142, blue: 69)),
ChemistryButtonInfo(scale: "6.8", color: UIColor(red: 209, green: 122, blue: 31)),
ChemistryButtonInfo(scale: "7.2", color: UIColor(red: 196, green: 80, blue: 9)),
ChemistryButtonInfo(scale: "7.8", color: UIColor(red: 194, green: 74, blue: 58)),
ChemistryButtonInfo(scale: "8.4", color: UIColor(red: 208, green: 48, blue: 75))]),
"Ammonia":
ChemistryViewInfo(
text: "Ammonia",
description: "",
buttons: [
ChemistryButtonInfo(scale: "0.00", color: UIColor(red: 244, green: 235, blue: 130)),
ChemistryButtonInfo(scale: "0.25", color: UIColor(red: 233, green: 233, blue: 156)),
ChemistryButtonInfo(scale: "0.50", color: UIColor(red: 223, green: 238, blue: 141)),
ChemistryButtonInfo(scale: "1.00", color: UIColor(red: 221, green: 236, blue: 210)),
ChemistryButtonInfo(scale: "3.00", color: UIColor(red: 202, green: 227, blue: 191)),
ChemistryButtonInfo(scale: "6.00", color: UIColor(red: 202, green: 216, blue: 173))])
]
最后:
import Foundation
import UIKit
struct ChemistryButtonInfo{
let scale: String
let color: UIColor
}
struct ChemistryViewInfo {
let text: String
let description: String
let buttons: [ChemistryButtonInfo]
}
extension UIColor {
convenience init(red:Int, green:Int, blue:Int) {
self.init(
red: CGFloat(red)/255.0,
green: CGFloat(green)/255.0,
blue: CGFloat(blue)/255.0,
alpha: 1.0)
}
}
错误发生在if-let语句的第二个viewInfo上。我想知道声明viewInfo的正确方法是什么。
非常感谢任何建议,输入或答案。
提前致谢。
答案 0 :(得分:0)
假设您将在ChemistryMasterViewController类中声明viewInfo实例变量,您可以执行此操作。
var viewInfo:ChemistryViewInfo? //instance property declaration
if let viewInfo = self.viewInfo {
....
....
}