0

I have a problem with following error: Cannot use instance member 'card0' within property initializer; property initializers run before 'self' is available

I am freshman, so I would be very thankful for advices and tips :)

Code: View Controller:

import UIKit

class ViewController: UIViewController {

    let card0: Card = startingcard()
    var pl1: Card = firstplayercard(card0: card0)
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

struct Card {
    var signs: [Int]
    var restSymbols: [Int]
    var matching: Int
}

func startingcard() -> Card {
    let randomChoice = GKRandomDistribution(lowestValue: 0, highestValue: 15)
    var symbols = [Int]()
    for index in 0...15{
        symbols.append(index)
    }
    var card = [Int]()
    var i = 5
    while i >= 0 {
        let a = randomChoice.nextInt()
        let n = symbols[a]
        if n > 0 {
            card.append(n)
            symbols[a] = 0
        }else{
            i += 1
        }
        i -= 1
    }
    print(symbols)
    print(card)
    return Card(signs: card, restSymbols: symbols, matching: 0)
}

func firstplayercard(card0: Card) -> Card{

    let randomChoice = GKRandomDistribution(lowestValue: 0, highestValue: 15)
    let secondRandom = GKRandomDistribution(lowestValue: 0, highestValue: 5)
    var symbols = card0.restSymbols
    
    var playerCard = [Int]()
    var i = 5
    while( i >= 0) {
        let a = randomChoice.nextInt()
        let n = symbols[a]
        if( n != 0){
            playerCard.append(n)
            symbols[a] = 0
        }else{
            i += 1
        }
        i -= 1
    }
    let k = secondRandom.nextInt()
    let l = secondRandom.nextInt()
    playerCard[k] = card0.signs[l]
    //return k to symbols, because it's unused
    symbols[k] = k
    print("Player card:\n")
    print(playerCard)
    print(symbols)
    print(l)
    
    return Card(signs: playerCard, restSymbols: symbols, matching: l )
}
Witek Bobrowski
  • 3,749
  • 1
  • 20
  • 34
kubakorek
  • 11
  • 3

1 Answers1

0

You will need to convert the pl1 stored property to a lazy stored property:

class ViewController: UIViewController {

    let card0: Card = startingcard()
    lazy var pl1: Card = firstplayercard(card0: card0)
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
}

Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete.

You can read more about lazy properties in the official documentation under the "Lazy Stored Properties" chapter.

Witek Bobrowski
  • 3,749
  • 1
  • 20
  • 34