Override static var in Swift child class

To decompose my code, I want to set the stringKey from the Child class, which I will get in the func class in the parent class:

Chair.request();
Table.request();

class Furniture: NSObject {

    static let requestKey : String!

    class func request(){

        print("class key => \(self.requestKey)")
        ...
    }
}

class Chair: Furniture {
    static let requestKey : String = "jsonchairs"
} 

class Table: Furniture {
    static let requestKey : String = "tables"
} 

Of course I have a precompiled error message

A property does not override any property from its superclass.

Is there a solution for this, or do I need to pass the key as a parameter? eg:

Chair.request(key : "jsonchairs" );
Table.request(key : "tables" );
+4
source share
3 answers

Just the same problem. Use calculated properties - they can be overridden.

Base class:

class BaseLanguage {
    class var language: String {
        return "Base"
    }

    static func getLocalized(key: String) -> String {
        print("language: \(language)");
    }
}

Child class:

class German: BaseLanguage {
    override class var language: String {
        return "de"
    }
}

- , private singleton. , . ( , ) init.

+4

, vale , . requestKey, request :

// define Furniture protocol

protocol Furniture {
    static var requestKey: String { get }
    static func request()
}

// implement default implementation in extension

extension Furniture {
    static func request() {
        print("class key => \(self.requestKey)")
    }
}

// both Chair and Table conform to this protocol

class Chair: Furniture {
    static let requestKey = "jsonchairs"
}

class Table: Furniture {
    static let requestKey = "tables"
} 

, , Furniture , . , Furniture . , - , , Furniture, / , , (.. Chair Table).

Furniture , , , static, . , Furniture Chair Table, , static /.

Furniture , , , , . - - , . Crusty. . WWDC 2015 - Swift WWDC 2016 , , UIKit.

, , , static / , . - static, , , .

+1

You can use protocols for this. Just make them both match the RequestKeyProtocol fir example and implement it in each case.

protocol RequestKeyProtocol {
 var requestKey: String
}




 class myClass: RequestKeyProtocol {
   var requestKey = "myKey"
   }

If you need a default value, look at protocol extensions. Watch this year's WWDC protocol video.

0
source

Source: https://habr.com/ru/post/1617964/


All Articles