Started to learn Swift and got stuck...

Hello

I started learning Swift through "Develop in Swift Fundamentals" version for Xcode 12 by Apple Books. Everything more or less went smoothly for first few chapters until I got stuck on Guided Project: Light. It's the part talking about using Refactor > Extract to Method. No matter what I try, Extract to Method is greyed out in the Editor menu, or, if I try with right click on selected code it just making clicking notification sound... If I run app in simulator it works fine, but my understanding is that Refactor is important part of Swift, so I guess it would be nice if it would work.

I'm using Xcode 12.5.1 on Big Sur 11.5.1

I also tried uninstall / install Xcode, and even tried with the latest beta and nothing different.

Code I have is the following:

import UIKit

class ViewController: UIViewController {

@IBOutlet var lightButton: UIButton!
var lightOn = true

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func buttonPressed(_ sender: Any) {
   
    lightOn.toggle()
    if lightOn {
        view.backgroundColor = .white
    }
    else
    {
        view.backgroundColor = .black
    }
}

}

Instructions are to highlight:

lightOn.toggle() if lightOn { view.backgroundColor = .white } else { view.backgroundColor = .black }

And use Refactor > Extract to Method from the Editor menu. That is greyed out. I tried to select more code, but same result...

Any help would be greatly appreciated.

Answered by PauliJr in 684217022

Hello Claude

Thanks for your help. Tried everything and nothing... Then I tried the same exercise on my MacBook and it worked. So I found an article on how to completely remove Xcode from the computer. Did that and installed it again and now it works great on my iMac too. So it was completely issue with my computer.

Anyway, thanks for your help again - I appreciate it

Paul

In my Xcode 12.5.1 (Big Sur 11.4), it works perfectly as expected. Do you think of anything special for your environment? Have you checked you can successfully build your project before trying Refactor > Extract to Method?

A possible reason is that your selection in the source file is not correct.

You need to select precisely what I marked in green.

If you select also the next line (with }) or forget the last line in green, you get the problem.

Note: it is usually better to explicit the type of sender :

@IBAction func buttonPressed(_ sender: UIButton) {
Accepted Answer

Hello Claude

Thanks for your help. Tried everything and nothing... Then I tried the same exercise on my MacBook and it worked. So I found an article on how to completely remove Xcode from the computer. Did that and installed it again and now it works great on my iMac too. So it was completely issue with my computer.

Anyway, thanks for your help again - I appreciate it

Paul

Thanks for the feedback. Don’t forget to close your thread.

Started to learn Swift and got stuck...
 
 
Q