我是论坛新手,也是 Swift 语言新手。我一直在玩 xcode,并想创建一个应用程序,使用 fenceloop 来显示数字的因子作为“解决方案”。该应用程序当前使用标签来显示、文本用于输入以及按钮来启动。我有我认为有效的代码,但我看不到让它工作,因为根据我的理解,我必须将字符串输入转换为整数。如果有人有任何想法如何让它发挥作用;因为我觉得我已经尽力了。
我遇到的特别问题是它说“无法将类型'UITextField!的值转换为预期的参数类型'Int'。我想要发生的是,在单击按钮时,它解决了因素文本框中的任何内容并将其显示为标签中的字符串。如有任何帮助,我们将不胜感激!
import UIKit
class ViewController: UIViewController {
@IBOutlet var input1 : UITextField!
@IBOutlet var label : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func printFactors(n: Int) {
var result: String = ""
for i in 1...n {
guard n % i == 0 else {continue}
result += i == 1 ? "1" : " and \(i)"
}
print(result)
let outputText = printFactors(n: input1)
label.text = outputText
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最佳答案
您的 printFactors
方法存在很多问题和困惑。让我们把它分开并正确设置。
首先,创建一个单独的方法来进行数学计算:
func calculateFactors(n: Int) -> String {
var result: String = ""
for i in 1...n {
guard n % i == 0 else {continue}
result += i == 1 ? "1" : " and \(i)"
}
print(result)
return result
}
现在让我们设置按钮操作:
@IBAction func factorAction(sender: UIButton) {
if let text = input1.text {
if let num = Int(text) {
let factor = calculateFactors(n: num)
label.text = factor
} else {
// Show the user that the entered text isn't a number
}
} else {
// There's no text
}
}
将按钮设置为使用新的 factoryAction:
方法而不是旧的 printFactors:
方法。
关于ios - 用于求解数字因数和显示的 Swift 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40183917/