In Swift, how to create convenience initialization for a class, where the init implementation creates a class value instead of calling an existing init

It seems to me that the answer is obvious, but I could not understand it, and for me this is a recurring problem. Basically I want to do something like this:

extension NSData {
    convenience init(JSONObject: AnyObject) {
        do {
            self = try NSJSONSerialization.dataWithJSONObject(JSONObject, options: [])
        }
        catch {
            self = nil
        }
    }
}

However, he will not allow me to simply assign meaning to myself. I do this all the time with enumerations, but that will not allow me to do this with classes. Is there a way to implement in a convenient initializer using an instance of the class created in the implementation of the initializer?

+4
source share
2 answers

, factory " " Swift . , ; Apple Swift

factory Swift, .

...

Swifts , , factory.

, , , . , -

extension NSData {
    convenience init?(JSONObject: AnyObject) {
        do {
            let foo = try NSJSONSerialization.dataWithJSONObject(JSONObject, options: [])
            self.init(data: foo)
        }
        catch {
            return nil
        }
    }
}

/* Example usage */
let foo : AnyObject = ["Foo":"bar"]
let bar = NSData.init(JSONObject: foo)

"... init". convenience ( ) - ( ). Swift Language Guide - - :

...

2

.

3

.

() , NSJSONSerialization.dataWithJSONObject(...) , , ( init(data:), ).


. Swift Language Guide - Initialization - Failable Initializers. (convenience -> ... -> designated initializer) . rickster: s .

+1

, factory. Swift . , , factory.

+1

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


All Articles