Question about addNewItem func in chapter 11

#1

I have been following the book’s code but adapting it to a list of players of a team.
When I try the code to add a new row to the UITableView which creates a new player from the Store it gives me the error: “Instance member ‘createPlayer’ cannot be used on type ‘PlayerStore’; did you mean to use a value of this type instead?”

I am wondering what I am doing wrong within the code…

Here is my ViewController File:

import UIKit

class PlayerViewController: UITableViewController {

var playerStore: PlayerStore!

@IBAction func addNewPlayer(_ sender: UIButton) {
    let newPlayer = PlayerStore.createPlayer()
    
    if let index = playerStore.allPlayers.index(of: newPlayer) {
    let indexPath = IndexPath(row: index, section: 0)
    
    tableView.insertRows(at: [indexPath], with: .automatic)
    }
}

This is my Store File:

import UIKit

class PlayerStore{

var allPlayers = [Player]()

@discardableResult func createPlayer() -> Player {
    let newPlayer = Player()
    
    allPlayers.append(newPlayer)
    
    return newPlayer
    
}
#2

createPlayer is a member function, not a static or class function, of PlayerStore.

Therefore, invoke it on the instance of PlayerStore, not on PlayerStore.

var playerStore: PlayerStore!

@IBAction func addNewPlayer(_ sender: UIButton) {
    let newPlayer = playerStore.createPlayer()
    ...
1 Like