Home > other >  Cannot use instance member 'generateRandomNumbers' within property initializer; property i
Cannot use instance member 'generateRandomNumbers' within property initializer; property i

Time:02-26

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView1: UITableView!
var array = generateRandomNumbers(size: 1000)
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    tableView1.delegate = self
    tableView1.dataSource = self

// var array = self.generateRandomNumbers(size: 1000) // lazy var array = generateRandomNumbers(size: 1000)

// print(array) }

func generateRandomNumbers(size: Int) -> [Int] {
    guard size > 0 else {
        return [Int]()
    }
    let result = Array(0..<size).shuffled()
    return result
    
}

CodePudding user response:

You are asking var array to receive a "default" value from the function generateRandomNumbers(). The "default" value is set during the initialisation of the instance of your view controller, so before the instance exists, so before the generateRandomNumbers() function exists. The compiler doesn't know how to give a value to array before the instance has finished being created.

A workaround is to set a dummy default value, then change it during initialisation, like this:

@IBOutlet weak var tableView1: UITableView!
var array = [Int]()    // This is an empty array, the compiler can create it before the generateRandomNumbers() is available
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    tableView1.delegate = self
    tableView1.dataSource = self
    ...

    array = generateRandomNumbers(size: 1000)     // Now that all variables are initialised, you can change their values

CodePudding user response:

Well, the basic answer is the concept of understanding.

var array = generateRandomNumbers(size: 1000)

When the code is compiled, it first tries to compile the variables first. So at that time, self isn't initiated. So, therefore, it doesn't recognize the method generateRandomNumbers. You get the error.

The best possible solution is actually using

lazy var array = generateRandomNumbers(size: 1000)

When you use lazy it doesn't try to initialize until it is needed. So they are skipped for the first time compilation.

If you don't need lazy simply you have to declare it in the viewDidLoad()

var array = [Int]()

override func viewDidLoad() {
   super.viewDidLoad()
   array = generateRandomNumbers(size: 1000)
}
  • Related