You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

斯坦福课程仿做Concentration游戏遇代码错误求助

Fixing "Instance member 'cardButtons' cannot be used on type 'ViewController'" in Your Concentration Game

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 with static or class, you can't access instance properties like cardButtons inside 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 cardButtons collection 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:15:13