我有这个简单的课程:
import UIKit
let builtIn = MyClass(n1: 1)
print("DeviceA: \(builtIn.n1)") // DeviceA Optional(1)
class MyClass: NSObject {
var n1: Int!
init(n1: Int) {
super.init()
self.n1 = n1
}
}
为什么DeviceA Optional(1)
在n1
不可选时在控制台上显示为print("DeviceA: \(builtIn.n1!)")
?
我可以通过Optional
解决这个问题。但我不明白为什么func addTextField() {
let txtUserName = UITextField(frame: CGRect(x: 30, y: 70, width: 320, height: 45))
let txtPassword = UITextField(frame: CGRect(x: 30, y: 140, width: 320, height: 45))
txtUserName.backgroundColor = UIColor.black
txtPassword.backgroundColor = UIColor.black
txtUserName.alpha = 0.35
txtPassword.alpha = 0.35
let imgUser = UIImageView(frame: CGRect(x: 5, y: 5, width: 35, height: 35))
let imgKey = UIImageView(frame: CGRect(x: 5, y: 5, width: 35, height: 35))
let imgEye = UIImageView(frame: CGRect(x: txtPassword.frame.size.width - 40, y: 5, width: 35, height: 35))
imgUser.image = UIImage(named: "user")
imgKey.image = UIImage(named: "key")
imgEye.image = UIImage(named: "eye")
txtUserName.addSubview(imgUser)
txtPassword.addSubview(imgKey)
txtPassword.addSubview(imgEye)
view.addSubview(txtUserName)
view.addSubview(txtPassword)
}
在那里。
谢谢,
答案 0 :(得分:1)
您已将n1声明为隐式解包的可选项:
var n1: Int!
这意味着n1仍然是可选的,但你承诺它将是非零的代码。为了避免可选状态,您需要声明为:
var n1: Int
在这种情况下,你需要确保在init()函数中初始化它,或者像这样提供一个默认的init:
var n1: Int = 0
答案 1 :(得分:0)