Nathanael Tse
Nathanael Tse

Reputation: 1

override func in class swift

I am quite new to swift and I have a question regarding the definition of functions in a class. I want to generate several items and give each of them a special function so I can run them by itemxy.useitem()

class item {
   var name = "test"
   func useitem(){
   print("test")
   }
}

let staff = item()

staff.name = "Staff"

staff.useitem() // prints: test

*override staff.useitem() = {print("this is a staff")}*

staff.useitem() // prints: this is a staff

how can I align a new function to my item staff?

Upvotes: 0

Views: 420

Answers (1)

Oliver Atkinson
Oliver Atkinson

Reputation: 8029

These are not entirely swift related and are more general programming, you wont get your answers to such problems here. You should read up on basic programming principles before you tackle things further.

Having said that your problem is easily solved with Inheritance or Protocols.

Inheritance

class Item {

  var name: String

  init(name: String) {
    self.name = name
  }

  func use() {
    print("using a \(name)")
  }

}

class Hat: Item {

  override func use() {
    print("I put on a \(name)")
  }

}

class Pen: Item {

  init() {
    super.init(name: "Pen")
  }

}

let pen = Pen()
pen.use()

let hat = Hat(name: "Beanie")
hat.use()

Protocol

protocol Item {

  var name: String { get set }
  func use()

}

extension Item {

  func use() {
    print("using a \(name)")
  }

}

struct Pen: Item {
  var name: String

  init() {
    self.name = "Pen"
  }

}

struct Hat: Item {

  var name: String

  func use() {
    print("I put on a \(name)")
  }

}

let pen = Pen()
pen.use()

let hat = Hat(name: "Beanie")
hat.use()

Upvotes: 2

Related Questions