Cannot use instance member 'retreiveFromArrayOfMeme' within property initializer

I have the following code in my class MemeMeViewModel which is an ObservableObject :

@Published var memes: [MemeMeModel.Meme] = retreiveFromArrayOfMeme()



    func retreive() -> [(UIImage, String)] {

        var temp = [(UIImage, String)]()

        if let Memes = UserDefaults.standard.object(forKey: "MemesList") as? [[Any]] {

            for Meme in Memes {

                if let image = UIImage(data: Meme[0] as! Data) {

                    temp.append((image, Meme[1] as! String))

                }

            }

        }

        return temp

    }

    

    func retreiveFromArrayOfMeme() -> [MemeMeModel.Meme] {

        var temp = [MemeMeModel.Meme]()

        if let Memes = UserDefaults.standard.object(forKey: "MemesList") as? [[Any]] {

            for Meme in Memes {

                temp.append(MemeMeModel.Meme(pngRepresentation: Meme[0] as! Data, content: Meme[1] as! String))

            }

        }

        return temp

    }

On line 1, I have the following error : "Cannot use instance member 'retreiveFromArrayOfMeme' within property initializer; property initializers run before 'self' is available".

I don't know what to do ... Need help please !

Write an init() where you will set the value.

Get more details in this other thread:

https://developer.apple.com/forums/thread/685605

the following code in my class MemeMeViewModel which is an ObservableObject 

You should better include the class header when you show some parts of a class.

I have the following error : "Cannot use instance member 'retreiveFromArrayOfMeme' within property initializer; property initializers run before 'self' is available".

As the error message is clearly stating, you cannot use the instance method retreiveFromArrayOfMeme within property initializer.

One possible fix would be making it a static method in this case:

    @Published var memes: [MemeMeModel.Meme] = MemeMeViewModel.retreiveFromArrayOfMeme()
    
    static func retreiveFromArrayOfMeme() -> [MemeMeModel.Meme] {
        var temp = [MemeMeModel.Meme]()
        if let memes = UserDefaults.standard.object(forKey: "MemesList") as? [[Any]] {
            for meme in memes {
                temp.append(MemeMeModel.Meme(pngRepresentation: meme[0] as! Data, content: meme[1] as! String))
            }
        }
        return temp
    }

(In Swift, only type names start with Capital letter.)

You may need to find other ways when you want use some other instance members in retreiveFromArrayOfMeme().

Cannot use instance member 'retreiveFromArrayOfMeme' within property initializer
 
 
Q