Calling same property from different classes in Swift? - swift

If I have two explicit classes that both have the same property name, is there a way to call the property without having to define which class I'm using?
class firstClass {
var name = “Name”
init…..
}
class secondClass {
var name = “Another name”
init….
}
now another function can call
//does not work... I get an error saying AnyObject doesn't have property
func printNameOf(object: AnyObject) {
println(object.name)
}
//works but my software has a lot of classes, which means a ton of code
func printNameOf(object: AnyObject) {
if object is firstClass {
println((object as firstClass).name)
}
if object is secondClass {
println((object as secondClass).name)
}
}

You could do this by creating a protocol that both your classes conform to:
protocol NameProtocol {
var name: String {get set}
}
class firstClass: NameProtocol {
var name = "Name 1"
}
class secondCLass: NameProtocol {
var name = "Name 2"
}
func printNameOf(obj: NameProtocol) {
// You know obj has property name
println(a.name)
}

Related

Why is the subclass type not available when an instance property is initialized by a static member?

When the following code is run, the self inside of defaultModuleName is ReactViewController when one would expect it to be FooViewController. Why?
class ReactViewController: UIViewController {
var moduleName: String = defaultModuleName
static var defaultModuleName: String {
let t = String(reflecting: self) // Also tried NSStringFromClass
guard let s = t.split(separator: ".").last else { return "" }
guard let r = s.range(of: "ViewController") else { return "" }
return String(s.prefix(upTo: r.lowerBound))
}
}
class FooViewController: ReactViewController {
override func viewDidLoad() {
super.viewDidLoad();
print(moduleName); // Prints "React"
}
}
This is pretty interesting; it appears that the self available in a property initialiser is merely the type that the property is defined in, rather than the dynamic type of the instance being constructed.
A more minimal example would be:
class C {
static var foo: String { return "\(self)" }
let bar = foo // the implicit 'self' in the call to 'foo' is always C.
}
class D : C {}
print(D().bar) // C
In the property initialiser for bar, the implicit self is C.self, not D.self; despite the fact that we're constructing a D instance. So that's what the call to foo sees as self.
This also prevents class member overrides from being called from property initialisers:
class C {
class var foo: String { return "C" }
let bar = foo
}
class D : C {
override class var foo: String { return "D" }
}
print(D().bar) // C
Therefore I regard this as a bug, and have filed a report here.
Until fixed, a simple solution is to use a lazy property instead, as now self is the actual instance (upon the property being accessed for the first time), which we get can get the dynamic type of with type(of: self).
For example:
class C {
static var foo: String { return "\(self)" }
// private(set) as the property was a 'let' in the previous example.
lazy private(set) var bar = type(of: self).foo
}
class D : C {}
print(D().bar) // D
Applied to your example:
class ReactViewController : UIViewController {
lazy var moduleName = type(of: self).defaultModuleName
static var defaultModuleName: String {
let t = String(reflecting: self) // Also tried NSStringFromClass
guard let s = t.split(separator: ".").last else { return "" }
guard let r = s.range(of: "ViewController") else { return "" }
return String(s.prefix(upTo: r.lowerBound))
}
}
class FooViewController : ReactViewController {
override func viewDidLoad() {
super.viewDidLoad()
print(moduleName) // Prints "Foo"
}
}
You just need to pass self instead of type(of: self), and use the String(describing:) initializer.
class ClassA {
static var className: String {
return String(describing: self)
}
}
class ClassB: ClassA { }
print(ClassB.className) // prints "ClassB"
EDIT: clarification on the var moduleName: String = defaultModuleName update. Suppose I add this line to the above example (same idea):
class ClassA {
// This is a property of ClassA -> it gets implicitly initialized
// when ClassA does -> it uses ClassA.className for its value
var instanceClassName = className
static var className: String {
return String(describing: self)
}
}
class ClassB: ClassA { }
print(ClassB().instanceClassName) // prints "ClassA"
This new instanceClassName is not static, so it is an instance property on ClassA. It is therefore initialized when ClassA is initialized (not when ClassB is initialized). Ergo, a property being set within ClassA, using a reference to className, will print out ClassA.

Accessing Class var on AnyClass variable in Swift 4

In Swift 3.2 this (let id = row.tableViewCellClass?.reuseIdentifier) worked:
class DrillDownTableViewCell {
class var reuseIdentifier: String
{
return String(describing: self)
}
}
class RowViewModel: NSObject
{
var tableViewCellClass: AnyClass?
}
class Foo {
var row : RowViewModel?
func setup() {
row = RowViewModel()
row?.Class = DrillDownTableViewCell.self
}
func doThings() {
let id = row?.tableViewCellClass?.reuseIdentifier
}
}
After my Swift 4 update, it's showing "Instance member 'reuseIdentifier' cannot be used on type 'AnyObject'.
How would I access a class variable on a class who's metaType information is stored in an AnyClass variable?
(I assume you mean to have a ? after row in doThings(). I assume that's a typo and not part of the question. There are several other ? missing here and some other typos that I won't dive into.)
If you expect tableViewCellClass to have a reuseIdentifier class property, then it isn't of type AnyClass. There are many classes that don't have that property. You want classes that conform to a protocol:
protocol Identifiying {
static var reuseIdentifier: String { get }
}
So your model requires an Identifying class:
class RowViewModel: NSObject {
var tableViewCellClass: Identifiying.Type?
}
Then you can use this as you're expecting.

Is there a way to initialize a class in swift by using a variable which contains the name of the class?

Suppose I have a simple factory which returns various subclasses of a custom ModelObject class like:
class func testModelObject(className: String) -> ModelObject
{
let obj = // instance of the subclass of ModelObject specified by className
return obj
}
Is there a way to do this? Will Swift freak out when I try to call any methods of that object? Should I have something else for my return type?
For best type safety, you should let testModalObject to accept a meta-type like:
class ModelObject {
required init() {}
}
class Subclass: ModelObject {
required init() { super.init() }
}
func testModalObject(_ type: ModelObject.Type) -> ModelObject {
return type.init()
}
testModalObject(Subclass.self)
If you really need a string input, you will need to rely on the Objective-C runtime and do some casting (see how to create instance of a class from a string in swift 3):
#objc
class ModelObject: NSObject { // <---
required override init() {}
}
#objc(MOSubclass) // <-- tell ObjC the name is "MOSubclass" instead of "????.Subclass".
class Subclass: ModelObject {
required init() { super.init() }
}
func testModalObject(_ typeName: String) -> ModelObject? {
let cls = NSClassFromString("MO\(typeName)") as? ModelObject.Type
return cls?.init()
}
testModalObject("Subclass")!

How to initialize variables inside subclasses' initializer that will be used in the super class's initializer?

In the following code, my intention is to have repeatNum declared in the base class because it is used in the base class (inside init and other functions). And each subclass should set repeatNum because only the subclass knows its own value.
class Base {
var repeatNum: Int
init() {
for var i=0; i<repeatNum; ++i {
print("*")
}
}
}
class SubClass1 : Base {
override init() {
repeatNum = 10
super.init()
}
}
class SubClass2 : Base {
override init() {
repeatNum = 5
super.init()
}
}
Of course, it prompts some errors:
For the base class:
'self.repeatNum' not initialized
Return from initializer without initiating all stored properties.
For the subclasses:
use of 'self' in property access 'repeatNum' before super.init initializes self
I know I can simply call super.init() before setting repeatNum in the subclasses, but I really need to use repeatNum inside the base's init() in the real case. It becomes a paradox for me here somehow.
I also understand I can change the design to make the errors go away, but I am wondering if it's possible to achieve my original intention with some tweaks? I probably miss something here.
Your current code doesn't even compile, does it? It should complain about trying to use repeatNum before being initialized...
Maybe something like this could be an option for you?
class Base {
var repeatNum: Int
init(repeatNum: Int) {
self.repeatNum = repeatNum
for _ in 0..<repeatNum {
print("*")
}
}
}
class SubClass1 : Base {
init() {
super.init(repeatNum: 10)
}
}
class SubClass2 : Base {
init() {
super.init(repeatNum: 5)
}
}
i don't know what is you want,the following code is that ok
class Base {
var repeatNum: Int?
init() {
}
func printyourneed(){
for var i=0; i<repeatNum; ++i {
print("*")
}
}
}
class SubClass1 : Base {
override init() {
super.init()
self.repeatNum = 10
self.printyourneed()
}
}
class SubClass2 : Base {
override init() {
super.init()
self.repeatNum = 5
self.printyourneed()
}
}
or
class Base {
var _repeatNum:Int?;
var repeatNum: Int?{
get{
return _repeatNum
}
set{
_repeatNum = newValue
printyourneed()
}
}
init() {
}
func printyourneed(){
for var i=0; i<repeatNum; ++i {
print("*")
}
}
}
class SubClass1 : Base {
override init() {
super.init()
self.repeatNum = 10
}
}
class SubClass2 : Base {
override init() {
super.init()
self.repeatNum = 5
}
}

Can you create a Swift base class that requires its subclasses to implement method(s)? [duplicate]

Is there a way to create an abstract class in the Swift Language, or is this a limitation just like Objective-C? I'd like to create a abstract class comparable to what Java defines as an abstract class.
There are no abstract classes in Swift (just like Objective-C). Your best bet is going to be to use a Protocol, which is like a Java Interface.
With Swift 2.0, you can then add method implementations and calculated property implementations using protocol extensions. Your only restrictions are that you can't provide member variables or constants and there is no dynamic dispatch.
An example of this technique would be:
protocol Employee {
var annualSalary: Int {get}
}
extension Employee {
var biweeklySalary: Int {
return self.annualSalary / 26
}
func logSalary() {
print("$\(self.annualSalary) per year or $\(self.biweeklySalary) biweekly")
}
}
struct SoftwareEngineer: Employee {
var annualSalary: Int
func logSalary() {
print("overridden")
}
}
let sarah = SoftwareEngineer(annualSalary: 100000)
sarah.logSalary() // prints: overridden
(sarah as Employee).logSalary() // prints: $100000 per year or $3846 biweekly
Notice that this is providing "abstract class" like features even for structs, but classes can also implement the same protocol.
Also notice that every class or struct that implements the Employee protocol will have to declare the annualSalary property again.
Most importantly, notice that there is no dynamic dispatch. When logSalary is called on the instance that is stored as a SoftwareEngineer it calls the overridden version of the method. When logSalary is called on the instance after it has been cast to an Employee, it calls the original implementation (it doesn't not dynamically dispatch to the overridden version even though the instance is actually a Software Engineer.
For more information, check great WWDC video about that feature: Building Better Apps with Value Types in Swift
Note that this answer is targeted at Swift 2.0 and above
You can achieve the same behaviour with protocols and protocol extensions.
First, you write a protocol that acts as an interface for all the methods that have to be implemented in all types that conform to it.
protocol Drivable {
var speed: Float { get set }
}
Then you can add default behaviour to all types that conform to it
extension Drivable {
func accelerate(by: Float) {
speed += by
}
}
You can now create new types by implementing Drivable.
struct Car: Drivable {
var speed: Float = 0.0
init() {}
}
let c = Car()
c.accelerate(10)
So basically you get:
Compile time checks that guarantee that all Drivables implement speed
You can implement default-behaviour for all types that conform to Drivable (accelerate)
Drivable is guaranteed not to be instantiated since it's just a protocol
This model actually behaves much more like traits, meaning you can conform to multiple protocols and take on default implementations of any of them, whereas with an abstract superclass you're limited to a simple class hierarchy.
I think this is the closest to Java's abstract or C#'s abstract:
class AbstractClass {
private init() {
}
}
Note that, in order for the private modifiers to work, you must define this class in a separate Swift file.
EDIT: Still, this code doesn't allow to declare an abstract method and thus force its implementation.
The simplest way is to use a call to fatalError("Not Implemented") into the abstract method (not variable) on the protocol extension.
protocol MyInterface {
func myMethod() -> String
}
extension MyInterface {
func myMethod() -> String {
fatalError("Not Implemented")
}
}
class MyConcreteClass: MyInterface {
func myMethod() -> String {
return "The output"
}
}
MyConcreteClass().myMethod()
After I struggled for several weeks, I finally realized how to translate a Java/PHP abstract class to Swift:
public class AbstractClass: NSObject {
internal override init(){}
public func getFoodToEat()->String
{
if(self._iAmHungry())
{
return self._myFavoriteFood();
}else{
return "";
}
}
private func _myFavoriteFood()->String
{
return "Sandwich";
}
internal func _iAmHungry()->Bool
{
fatalError(__FUNCTION__ + "Must be overridden");
return false;
}
}
public class ConcreteClass: AbstractClass, IConcreteClass {
private var _hungry: Bool = false;
public override init() {
super.init();
}
public func starve()->Void
{
self._hungry = true;
}
public override func _iAmHungry()->Bool
{
return self._hungry;
}
}
public protocol IConcreteClass
{
func _iAmHungry()->Bool;
}
class ConcreteClassTest: XCTestCase {
func testExample() {
var concreteClass: ConcreteClass = ConcreteClass();
XCTAssertEqual("", concreteClass.getFoodToEat());
concreteClass.starve();
XCTAssertEqual("Sandwich", concreteClass.getFoodToEat());
}
}
However I think Apple did not implement abstract classes because it generally uses the delegate+protocol pattern instead. For example the same pattern above would be better done like this:
import UIKit
public class GoldenSpoonChild
{
private var delegate: IStomach!;
internal init(){}
internal func setup(delegate: IStomach)
{
self.delegate = delegate;
}
public func getFoodToEat()->String
{
if(self.delegate.iAmHungry())
{
return self._myFavoriteFood();
}else{
return "";
}
}
private func _myFavoriteFood()->String
{
return "Sandwich";
}
}
public class Mother: GoldenSpoonChild, IStomach
{
private var _hungry: Bool = false;
public override init()
{
super.init();
super.setup(self);
}
public func makeFamilyHungry()->Void
{
self._hungry = true;
}
public func iAmHungry()->Bool
{
return self._hungry;
}
}
protocol IStomach
{
func iAmHungry()->Bool;
}
class DelegateTest: XCTestCase {
func testGetFood() {
var concreteClass: Mother = Mother();
XCTAssertEqual("", concreteClass.getFoodToEat());
concreteClass.makeFamilyHungry();
XCTAssertEqual("Sandwich", concreteClass.getFoodToEat());
}
}
I needed this kind of pattern because I wanted to commonize some methods in UITableViewController such as viewWillAppear etc. Was this helpful?
There is a way for simulating abstract classes using Protocols.
This is an example:
protocol MyProtocol {
func doIt()
}
class BaseClass {
weak var myDelegate: MyProtocol?
init() {
...
}
func myFunc() {
...
self.myDelegate?.doIt()
...
}
}
class ChildClass: BaseClass, MyProtocol {
override init(){
super.init()
self.myDelegate = self
}
func doIt() {
// Custom implementation
}
}
One more way how you can implement abstract class is to block initializer.
I've done it this way:
class Element:CALayer { // IT'S ABSTRACT CLASS
override init(){
super.init()
if self.dynamicType === Element.self {
fatalError("Element is abstract class, do not try to create instance of this class")
}
}
}
It's a really old question but still… Here's a snippet of actual code that compiles on Swift 5.2 and works as intended:
protocol Context {
init() throws
func out(_ aStr: String) throws
// Other stuff
}
class AbstractContext: Context {
required init() throws {
if Self.self === AbstractContext.self {
preconditionFailure("Call to abstract method \(Self.self).\(#function)")
}
}
func out(_ aStr: String) throws {
preconditionFailure("Call to abstract method \(Self.self).\(#function)")
}
// Other stuff
}
class CompileContext: AbstractContext {
required init() throws {}
override func out(_ aStr: String) throws {
print(aStr)
}
// Other stuff
}
And here's what I get once I remove CompileContext.out:
Fatal error: Call to abstract method CompileContext.out(_:): file swiftpg/contexts.swift, line 28
With the limitation of no dynamic dispatch, you could do something like this:
import Foundation
protocol foo {
static var instance: foo? { get }
func prt()
}
extension foo {
func prt() {
if Thread.callStackSymbols.count > 30 {
print("super")
} else {
Self.instance?.prt()
}
}
}
class foo1 : foo {
static var instance : foo? = nil
init() {
foo1.instance = self
}
func prt() {
print("foo1")
}
}
class foo2 : foo {
static var instance : foo? = nil
init() {
foo2.instance = self
}
func prt() {
print("foo2")
}
}
class foo3 : foo {
static var instance : foo? = nil
init() {
foo3.instance = self
}
}
var f1 : foo = foo1()
f1.prt()
var f2 : foo = foo2()
f2.prt()
var f3 : foo = foo3()
f3.prt()
I was trying to make a Weather abstract class, but using protocols wasn't ideal since I had to write the same init methods over and over again. Extending the protocol and writing an init method had it's issues, especially since I was using NSObject conforming to NSCoding.
So I came up with this for the NSCoding conformance:
required init?(coder aDecoder: NSCoder) {
guard type(of: self) != Weather.self else {
fatalError("<Weather> This is an abstract class. Use a subclass of `Weather`.")
}
// Initialize...
}
As for init:
fileprivate init(param: Any...) {
// Initialize
}
Move all references to abstract properties and methods of Base class to protocol extension implementation, where Self constraint to Base class. You will gain access to all methods and properties of Base class. Additionally compiler check implementation of abstract methods and properties in protocol for derived classes
protocol Commom:class{
var tableView:UITableView {get};
func update();
}
class Base{
var total:Int = 0;
}
extension Common where Self:Base{
func update(){
total += 1;
tableView.reloadData();
}
}
class Derived:Base,Common{
var tableView:UITableView{
return owner.tableView;
}
}