简体   繁体   中英

missing return in a function expected to return swift

I want to make a button that makes the background switch between red and green but I get this error:

missing return in a function expected to return UIView

I'm pretty new to coding, I've googled a bit but I didn't find anything.

Language:Swift

my code:

var timeLeft = 0
import UIKit

class ViewController: UIViewController {

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

    var buttonColor: UIView! {

        timeLeft = 1
    }

    func update() {
        if timeLeft > 0 {
            view.backgroundColor = UIColor.greenColor()
        }
        else {

            view.backgroundColor = UIColor.redColor()
        }
        timeLeft = timeLeft - 1

    }
}

thanks for helping

You declare buttonColor as a computed property which in its body requires you to return a UIView instance (since its type is UIView ).

Read here or here about computed property and make sure it fits your needs as posted in your case

Hi and welcome to stackoverflow

Remember to make an action connecting your UIButton to the code. Otherwise your code will not run when you click on the button. Also, consider using a Bool (true/false) variable to keep track of the background color.

Try the following code (remember to connect the 'click'-function to the button via the storyboard):

import UIKit

class ViewController: UIViewController {

    var isGreen = true

    @IBAction func click() {
        if isGreen {
            view.backgroundColor = UIColor.redColor()
            isGreen = false
        } else {
            view.backgroundColor = UIColor.greenColor()
            isGreen = true
        }
    }
}

var buttonColor: UIView! { get() { return (Object of UIView) } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM