Mastering Development

SwiftUI – How to set a non static var from a static function

I’m currently following a series of lectures from Stanford to learn Swift (Code is from lectures 1-4 plus the homework I’m trying to complete) and am having an issue with setting an instance var(non-static) from a static function. I have gotten this to work but I would like it to be able to have different instances of the game have different themes

class EmojiMemoryGame: ObservableObject {
    //Create the model in the viewController
    @Published private var cardGame = EmojiMemoryGame.createMemoryGame()
    static let themesArray = [
        theme(name: "Halloween", color:, emojiArray: ["💀","🕷","👻","🎃","👽","🍬","🌑"])
        theme(name: "Aqua", color:, emojiArray: ["🏴‍☠️","🐬","💧","⚓️","🏝","🐚","⛵️","🦑","🐡","🐠"]) {Int.random(in: 5...7)},
        theme(name: "Animals", color: Color.gray, emojiArray: ["🦜","🐈","🐓","🦝","🐇","🐖","🐎","🦌"])
            {Int.random(in: 3...4)}
    static var selectedTheme: theme?
    //Public Static Function
    //Input: None
    //Output: MemoryGame<String> struct
    //Usage: Return the card game with emoijs inited
    static func createMemoryGame() -> MemoryGame<String> {
        //Want to get a random theme from the themes array and assign it to an instance of this class but get an error beceause the function is static
        selectedTheme = themesArray[Int.random(in: 0..<themesArray.count)]
        let emojisArray = selectedTheme!.emojiArray
        //Create the actual MemoryGame
        return MemoryGame<String>(numberOfPairsOfCards: selectedTheme!.numberOfCards(), cardContentFactory: { cardPairIndex in
    //Struct Theme
    struct theme {
        let name: String
        let color: Color
        let emojiArray: [String]
        let numberOfCards: () -> Int

I want to be able to get a random theme from themesArray but let selectedTheme be an instance var. Can anyone give me some advice?

Leave a Reply

Your email address will not be published. Required fields are marked *