cisco21 cisco21 - 1 month ago 5
Swift Question

Swift app for solving factors of numbers and display

i'm new the forum and also new to the swift language. I've been playing around with xcode and wanted to create an app that uses a fenceloop to display the factors of a number as a "solution." The app currently uses a label to display, a text for input, and a button to initiate. I have what i think to be functioning code but i can't see to get it to work because from what i understand, i have to convert the input that's a string into an int. If anyone has any ideas how to get this working; since i feel like i've done what i can.

The problem in particular i am getting is it is saying that "Cannot convert value of type 'UITextField!; to expected argument type 'Int'. What i intend to happen is that on the button click, it solves for the factors of whatever is in the text box and displays it as a string in the label. Any help is appreciated!

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.
}


}

Answer

You have a lot of issues and confusion in your printFactors method. Lets split it up and setup things properly.

First, make a separate method to do the math:

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    
}

Now lets setup the button action:

@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
    }
}

Setup your button to use the new factoryAction: method instead of the old printFactors: method.

Comments