gpt4 book ai didi

ios - 开关允许两个相同的情况?

转载 作者:搜寻专家 更新时间:2023-11-01 06:52:24 24 4
gpt4 key购买 nike

测试 View :

class TestView: UIView{

override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}

func commonInit(){
addSubview(stackView)
setConstraints()
}
func setConstraints() {
let constrains = [
stackView.topAnchor.constraint(equalTo: topAnchor),
stackView.leadingAnchor.constraint(equalTo: leadingAnchor),
stackView.bottomAnchor.constraint(equalTo: bottomAnchor),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor)
]

NSLayoutConstraint.activate(constrains)

}

public let accept: UIButton = {
let v = UIButton()
v.backgroundColor = .blue
v.setTitle("Hello", for: .normal)
v.setTitleColor(.white, for: .normal)
v.setTitleColor(UIColor.white.withAlphaComponent(0.5), for: [.highlighted,.selected])
return v
}()


public let deny: UIButton = {
let v = UIButton()
v.backgroundColor = .red
v.setTitle("Deny", for: .normal)
v.setTitleColor(.white, for: .normal)
v.setTitleColor(UIColor.white.withAlphaComponent(0.5), for: [.highlighted,.selected])
return v
}()

public lazy var stackView: UIStackView = {
let v = UIStackView(arrangedSubviews: [accept,deny])
v.alignment = .fill
v.axis = .vertical
v.spacing = 8
v.distribution = .fillEqually
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
}

测试 View Controller

class TestViewController: UIViewController{
var myView: TestView{return view as! TestView}
unowned var accept: UIButton {return myView.accept}
unowned var deny: UIButton {return myView.deny}
override func loadView() {
view = TestView()
}

override func viewDidLoad() {
super.viewDidLoad()
accept.addTarget(self, action: #selector(didSelect), for: .touchUpInside)
deny.addTarget(self, action: #selector(didSelect), for: .touchUpInside)
}

@objc func didSelect(_ sender: UIButton){
switch sender{
case accept:
print("Accept button clicked")
case deny:
print("Deny button clicked")
case accept:
print("Accept button case again")
default:
break
}
}
}

上面的代码在 Xcode 10.2.1 中编译良好查看 didSelect 方法。它有一个带有两个相同外壳的开关 block 。只是好奇它不应该抛出编译时错误。该程序也成功运行,没有任何运行时错误。当我点击接受按钮时,第一个案例被执行。

问题:为什么这段代码没有编译时/运行时错误?

输出:

result

最佳答案

sender 的类型是 UIButton,编译器无法像对枚举类型那样进行检查。

由于 switch 的工作方式与 if/else if 语句完全相同,因此它只执行第一个。

相当于:

if sender == accept {
print("Accept button clicked")
}
else if sender == deny {
print("Deny button clicked")
}
else if sender == accept {
print("Accept button case again")
}
else {
break
}

关于ios - 开关允许两个相同的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56272963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com