Xcode中Swift代码`if`语句报‘expected declaration’错误求解决
Hey there! Let's work through that "Expected Declaration" error you're hitting in your Swift code for Xcode.
What's causing the error?
There are two main issues here, plus a small Swift best practice to clean things up:
- Code placement mistake: Your
if (Donestate == true)line is sitting directly at the top level of yourViewControllerclass. Swift only allows declarations (like properties, methods, initializers) in the class scope—you can't put executable logic likeifstatements here. All runtime code needs to live inside a method, closure, or initializer. - Variable name typo: You declared a property called
Done1State, but yourifstatement referencesDonestate(note the lowercase 's' and missing '1'). Swift is case-sensitive, so these are treated as completely different variables. - Bonus cleanup: In Swift, you don't need to explicitly check
== truefor boolean values—you can just use the boolean variable directly in theifcondition.
Fixed code example
Here's how to adjust your code to fix the error, using viewDidLoad() as a common place to put setup logic (or you could move this to an IBAction if it's triggered by a user action):
class ViewController: UIViewController { let grayColor = UIColor.gray var Done1State: Bool = false @IBOutlet weak var Name1: UILabel! @IBOutlet weak var Name2: UILabel! @IBOutlet weak var Name3: UILabel! @IBOutlet weak var Name4: UILabel! @IBOutlet weak var Name5: UILabel! @IBOutlet weak var Name6: UILabel! @IBOutlet weak var Time1: UILabel! @IBOutlet weak var Time2: UILabel! // Add any other missing IBOutlets here override func viewDidLoad() { super.viewDidLoad() // Move your if logic inside this method (or another appropriate method) if Done1State { // Add your desired logic here, e.g.: Name1.textColor = grayColor } } // Example: If this logic is triggered by a button tap @IBAction func toggleDoneState(_ sender: UIButton) { Done1State = !Done1State if Done1State { // Update UI or perform actions when state is true } else { // Handle false state } } }
Quick recap
- Move all executable code (like
ifstatements) into a method (e.g.,viewDidLoad(), an IBAction) - Fix the variable name typo to match your declared property (
Done1Stateinstead ofDonestate) - Simplify boolean checks by removing
== truefor cleaner Swift code
This should resolve the "Expected Declaration" error and get your code running smoothly.
内容的提问来源于stack exchange,提问作者GoopieGoogpie
相关产品推荐
相关产品推荐

