cisco21 cisco21 - 1 month ago 5
Swift Question

Print evens app error help - cannot convert to type string

I've been trying to make an app that takes a number and counts and displays the evens in a string. I think I have everything with the code working but I'm having trouble with getting it to display on the label.

There error I'm getting is on the

label.text = factor
line.
The error is:


"cannot assign value of type '()' to type 'string?'


I was wondering if anyone had any idea how to fix this or improve my code. And if you could, explain to me what I did wrong to do this? I know that's a lot, but still kinda new to Swift.

import UIKit

class ViewController: UIViewController {
@IBOutlet var input1 : UITextField!
@IBOutlet var label : UILabel!

@IBAction func factorAction(sender: UIButton) {
if let text = input1.text {
if let num = Int(text) {
// text to int
let factor = getEvens(<#T##input: Int##Int#>)
label.text = factor
} else {
// Show the user that the entered text isn't a number
}
} else {
// There's no text
}
}

// notifies user when no text or if a non number string/whole integer has been entered.
// recycled code from factor application because it was useful
func getEvens(_ input: Int){
var output: String = ""
for i in 0 ... input {
if (i % 2 == 0){
output += String(i) + ","
}
}
output.remove(at: output.index(before: output.endIndex))
print(output);
} // returns result

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}

Answer

Your getEvens() function prints a string to the console, but does not return anything. (More precisely, its return type is Void or (), and that is where type '()' in the error message

"cannot assign value of type '()' to type 'string?'

comes from.)

What you probably want is

func getEvens(_ input: Int) -> String { // <-- Return type is `String`
    var output: String = ""
    for i in 0 ... input {
        if (i % 2 == 0){
            output += String(i) + ","
        }
    }
    output.remove(at: output.index(before: output.endIndex))
    return output // <-- The returned value
}

Note that you can achieve the same result with

func getEvens(_ input: Int) -> String {
    let output = stride(from: 0, through: input, by: 2)
        .map(String.init)
        .joined(separator: ",")
    return output
}

which may be a bit more "Swifty":

  • stride(from: 0, through: input, by: 2) gives a sequence of the even numbers from 0 to input,
  • map(String.init) converts each number to a String, and
  • joined(separator: ",") concatenates the results to a single string, adding a comma between the elements.