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
}
}
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 ofNSObjectProtocol
, not a method.- Its Swift view returns a
String
, notNSString
. - 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
Take Screenshot of Host App Using iOS Share/Action Extensions
Querying in Firebase by Child of Child
Swift: Google Maps Draw Waypoint Polyline
Swift:Difference in '!' and '' in Swift
Get the String Up to a Specific Character
[_Nscftimer Copywithzone:]: Unrecognized Selector Sent to Instance
Swift: How to Create a Predicate with an Int Value
How to Add Documentation to Enum Associated Values in Swift
No Designated Init for Skshapenode(Circleofradius: Radius)
Swift: Dictionaries Inside Array
Swiftui - Show the Data Fetched from Firebase in View
Crash When Running on Device After Second Launch
How, Exactly, Do I Render Metal on a Background Thread
Way to Purge All But One Object Types (Models) in a Realm
Swift Firebase Storage How to Retrieve Image with Unknow Name(Nsuuid)
Swiftui: How to Set Position of Scrollview to Top Left? (Both Scrolls Is Enabled)