Swift: Override Object Method

Swift: Override object method

You cannot create anonymous classes in this manner in Swift, instead you must derive a new class:

class AnotherPerson: Person {
override func speak(phrase: String) {
NSLog("\(phrase) overidden!")
}
}

The closest to anonymous instantiations that override particular methods is to make speak a function property:

class Person {
var speak: (String)->() = { (phrase: String) in
println(phrase)
}
}

let person = Person()
person.speak("Frank") // => Frank
person.speak = { (phrase: String) in println("Hi, \(phrase)") }
person.speak("Frank") // => Hi, Frank

If you don’t want random consumers to be able to modify speak, you can make it a let property set via the initializer:

class Person {
let speak: (String)->()

init(speaker: (String)->() = println) {
speak = speaker
}
}

Person().speak("Frank") // => Frank
Person({ println("Hi, \($0)") }).speak("Frank") // => Hi, Frank

let person = Person()
person.speak = { println($0) } // error: cannot assign to speak

Here we set the default to println which thus preserves the original default behavior.

Swift: Override function during initialization (See what I mean in Java example)

What you are referring in Java is called anonymous inner class - you are actually declaring a one-time derived class inline.

Unfortunately Swift doesn't have this feature.

But you can consider passing a closure to the instance.

Lets say that your Card class have a var getCardFunction:

Class Card {
var getCardFunction : () -> Int
}

Now you can pass the function you desire after initialising:

var card = Card()
card.getCardFunction = {
return 6
}

Note: you can even have a default value for the getCardFunction function:

Class Card {
var getCardFunction : () -> Int = {
return 3
}
}

How to override function only on specific object in Swift?

Create custom subclass of UIScrollView. and override touchesShouldCancelInContentView there

class YourClass: UIScrollView {

override func touchesShouldCancelInContentView(view: UIView) -> Bool {

return false
}
}

Or if you want to give same class to both scrollview you can create @IBInspectable property. it is also accessible from the identity inspector.

class MyScrollView: UIScrollView {

@IBInspectable var touchCanceled: Bool = true

override func touchesShouldCancelInContentView(view: UIView) -> Bool {
return self.touchCanceled
}

}

Sample Image

Swift function overriding Objective-C method

The point of overriding is that the subclass method is called instead of the superclass method when the receiver is an instance of the subclass. Therefore, the subclass method's parameters must handle at least all the parameters the superclass method can handle. So the subclass method's parameters' types must be the same or more general than the parameters' types for the superclass method it overrides.

Swift - class method which must be overridden by subclass

You have two options:

1. Use a Protocol

Define the superclass as a Protocol instead of a Class

Pro: Compile time check for if each "subclass" (not an actual subclass) implements the required method(s)

Con: The "superclass" (protocol) cannot implement methods or properties

2. Assert in the super version of the method

Example:

class SuperClass {
func someFunc() {
fatalError("Must Override")
}
}

class Subclass : SuperClass {
override func someFunc() {
}
}

Pro: Can implement methods and properties in superclass

Con: No compile time check

Overriding description method in NSObject on swift

  • description is a (computed) property of NSObjectProtocol, not a method.
  • Its Swift view returns a String, not NSString.
  • Since you are overriding a property of a superclass, you must specify override explicitly.

Together:

// main.swift:
import Foundation

class Rectangulo: NSObject {

var ladoA : Int
var ladoB : Int
var area: Int {
get {
return ladoA*ladoB
}
}

init (ladoA:Int,ladoB:Int) {

self.ladoA = ladoA
self.ladoB = ladoB
}

override var description : String {
return "El area es \(area)"
}
}

let r = Rectangulo(ladoA: 2, ladoB: 3)
print(r) // El area es 6

How to override NSObject's default comparison in Swift

As of Swift 3, the isEqual method of NSObject takes an Any?
parameter, so you are not overriding the correct method, that's
why it is never called.

You should also override var hash: Int (equal objects must have the same hash) – otherwise the object will behave wrongly in hashable collections (sets, dictionaries):

class Player: NSObject {
let id: String

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

override func isEqual(_ object: Any?) -> Bool {
if let other = object as? Player {
return self.id == other.id
} else {
return false
}
}

override var hash: Int {
return id.hashValue
}
}

Some tests:

let p1 = Player(id: "a")
let p2 = Player(id: "a")

print(p1 == p2) // true
print(p1 != p2) // false

// Native Swift set:
let set = Set([Player(id: "x"), Player(id: "y"), Player(id: "z")])
print(set.contains(Player(id: "y"))) // true

// Foundation set:
let nsset = NSSet(objects: Player(id: "x"), Player(id: "y"), Player(id: "z"))
print(nsset.contains(Player(id: "y"))) // true

Swift, can I override a method with a more specific derived parameter type

Since PlaingCard inherits from Card you are not permitted to override the method in this way.

Consider what would happen if you tried to call match with an instance of PlayingCard. Which of the two methods would it call? It would be ambiguous and so is not allowed.

In this case one solution is to change the name of the method that takes the more specific type. e.g.

 func matchPlayingCard(othercards : [PlayingCard]) ->  Int {
return 2
}


Related Topics



Leave a reply



Submit