gpt4 book ai didi

swift - Swift 中的条件语句

转载 作者:行者123 更新时间:2023-11-28 05:32:05 25 4
gpt4 key购买 nike

我正在快速构建一个计算空间面积的简单应用程序。如果用户未在文本框中输入宽度或高度,条件语句将返回一条消息,我遇到了问题。

//
// ViewController.swift
// areaCalculator
//
//
// Copyright (c) 2014 Dandre Ealy. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var widthTxt: UITextField!
@IBOutlet weak var heightTxt: UITextField!

@IBOutlet weak var area: UILabel!

@IBAction func buttonPressed(sender: AnyObject) {

var width = widthTxt.text.toInt()
var height = heightTxt.text.toInt()

var areaPressed = width! * height!

if ((width) && (height) != nil){
area.text = "The area is \(areaPressed)"
} else {
area.text = "Enter the width and the height"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

最佳答案

这个说法是错误的:

if ((width) && (height) != nil)

你必须单独明确地检查 not nil:

if width != nil && height != nil

不过还有另一个错误,它会生成运行时异常:

var areaPressed = width! * height!

如果 widthheight 为 nil。您应该将其移动到 if 正文中:

if width != nil && height != nil {
var areaPressed = width! * height!
area.text = "The area is \(areaPressed)"
} else {
area.text = "Enter the width and the height"
}

原因是强制解包运算符 ! 要求应用它的可选变量包含非 nil 值 - 解包 nil 会导致运行时异常。

关于swift - Swift 中的条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27573035/

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