斯坦福课程仿做Concentration游戏遇代码错误求助
Hey there! Let's break down why you're hitting this error and how to fix it—it's a common gotcha when working with lazy properties and IBOutlets in Swift.
What's Causing the Error?
This message means you're trying to access the cardButtons instance property directly on the ViewController class itself, not on an actual, initialized instance of ViewController. Instance properties like your @IBOutlet collection only exist once a view controller is created and loaded; you can't reference them from the class level without specifying which instance you're targeting.
From your code snippet, the error is almost certainly in your lazy var game initialization. If you wrote something like this:
lazy var game = Concentration(numberOfPairsOfCards: cardButtons.count / 2)
Swift gets confused: it thinks you're trying to access a static cardButtons property on the ViewController type, not the instance's cardButtons outlet.
The Simple Fix
Just add self. to explicitly tell Swift you're referring to the current instance's cardButtons property:
import UIKit class ViewController: UIViewController { @IBOutlet var cardButtons: [UIButton]! // Add self. to reference the instance's cardButtons lazy var game = Concentration(numberOfPairsOfCards: self.cardButtons.count / 2) // Rest of your game code... }
Even though lazy properties are initialized after the instance exists, Swift requires this explicit self. in this context to avoid ambiguity between instance members and other identifiers.
Other Quick Checks
If that doesn't resolve the issue, verify these:
- No class methods using
cardButtons: If you have a method marked withstaticorclass, you can't access instance properties likecardButtonsinside it—class methods belong to the class itself, not any single instance. - Valid IBOutlet connections: Make sure all your buttons are properly linked to the
cardButtonscollection in Interface Builder. A broken connection won't cause this exact error, but it's good to rule out.
Why Did the Lecturer's Code Work?
It's likely a Swift version difference. Older versions of Swift were more lenient about omitting self. in lazy property initializers, but newer versions enforce it to prevent confusion. The lecturer's code might have been written with an older compiler that allowed the shorthand.
内容的提问来源于stack exchange,提问作者Samyu Ravikumar

