Not identical to "I"

I want to create a Convertible-like protocol and extend the subclasses NSObjectfor its implementation. In particular:

protocol DataConvertible {

    class func convertFromData(data:NSData) -> Self?

    func data() -> NSData

}

I thought the implementation would be as simple as:

extension UIImage : DataConvertible {

    class func convertFromData(data:NSData) -> Self? {
        let image : UIImage? = UIImage(data: data)
        return image
    }

    func data() -> NSData {
        return UIImagePNGRepresentation(self)
    }

}

But this does not compile with an error 'UIImage' is not identical to 'Self'. Did I miss something?

Is there any other way to implement such a protocol?

+4
source share
3 answers

Disclaimer: This is a workaround, not an ideal solution.


Using typealiasin protocolinstead Selfworks:

protocol DataConvertible {
    typealias Result

    class func convertFromData(data:NSData) -> Result?

    func data() -> NSData

}

Then return UIImage?instead of Self?from the implementation convertFromData:

extension UIImage : DataConvertible {

    class func convertFromData(data:NSData) -> UIImage? {
        let image : UIImage? = UIImage(data: data)
        return image
    }

    func data() -> NSData {
        return UIImagePNGRepresentation(self)
    }

}

:. , UIImage.convertFromData(data) UIImage? , ( @hpique ).

:

class Cache<T: DataConvertible where T.Result == T> { /* ... */ }

, UIImage.convertFromData, Int?:

class func convertFromData(data:NSData) -> Int? {
    return 1
}

, . , Cache<UIImage>, , Int (T.Result) UIImage (T).

+4

"" :

class func convertFromData(data:NSData) -> Self? {
    return self(data:data)
}

, , , . , /REPL, , , .

, :

let image = UIImage.convertFromData(data)       <--- works

let converter = UIImage.self as DataConvertible
let image = converter.convertFromData(data)     <--- crashes

, , :

class Fred {
    var fred:Int

    required init(value:Int) {
        fred = value
    }
}

extension Fred {
    class func makeOne(value:Int) -> Self {
        return self(value:value)
    }
}

, , UIImage - UIImage (:) , [UIImage imageWithData:]

+1

init(). , , .

, "" :

fooobar.com/questions/103101/...

In particular, if you have a subclass of UIImage, say AnimatedImage, that does not override the protocol method, the superclass instead returns UIImagewhat it is not Self.

Note. This does not work, but it seems like it is needed. Error?

protocol DataConvertible {

    init?(usingData:NSData)

    func data() -> NSData

}

extension UIImage : DataConvertible {

    convenience init?(usingData: NSData) {
        self.init(data: usingData)
    }

    func data() -> NSData {
        return UIImagePNGRepresentation(self)
    }

}
0
source

All Articles