Im quite new to programming, so hopefully someone can explain this to me in plain english.. Im trying to build an app in Swift that tells you wether the number inputted is a prime number or not. If it isn't prime, it should also tell you the factors of the numbers, e.x. if the user inputs 6, it tells you that 6 isn't a prime number, and apart from being divisible by 0, 1 and itself, its also divisible by 2 and 3. The code written until now is as follows:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var outputMessage: UILabel!
@IBAction func checkButton(sender: AnyObject) {
var isPrime = true
var inputNumber = textField.text.toInt()
var multiples:Int
if (inputNumber != nil) {
if (inputNumber <= 0) {
outputMessage.text = "Neither 0 nor negative numbers are considered prime numbers!"
textField.resignFirstResponder()
} else {
if (inputNumber == 1) {
outputMessage.text = "1 isn't a prime number!"
textField.resignFirstResponder()
}
else {
for var i = 2; i < inputNumber; ++i {
if (inputNumber! % i == 0) {
// Number is not prime
isPrime = false
multiples = i
}
}
}
if (isPrime == true) {
outputMessage.text = "Yup, that's a prime number!"
textField.resignFirstResponder()
} else {
outputMessage.text = "That number isn't prime. Apart from 1, 0 and itself, the number is also divisible by \(multiples) "
textField.resignFirstResponder()
}
}
} else {
outputMessage.text = "Please enter a number!"
textField.resignFirstResponder()
}
}
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.
}
}
Towards the end, where the output message says "That isn't a prime. Apart from 0, 1 and itself, the number is divisible by (multiples)" The code crashed here - it says Variable 'multiples' used before being initialized. Can anyone help?
Thanks a lot!!
Error messages in Swift are frequently misleading. The real issue is that
multiples
is not initialized when you declare it.In general, in Swift, variables need to be initialized when they are declared. There are a couple of exceptions: 1) optionals don't need to be initialized as they are
nil
if they are not explicitly initialized, 2) variables declared in a class can be initialized in the initializer.To fix the error, assign
multiples
an initial value:This will only show you 1 multiple of the number. If you want all of them, make
multiples
an array:Then append the values to the array when you have a new multiple: