What is the difference between UIImage (named :) and UIImage (imageLiteralResourceName :)?

Swift 3 / iOS 10 added a new initializer on UIImage , imageLiteralResourceName :

 extension UIImage { required public convenience init(imageLiteralResourceName name: String) } 

How is this different from public init?(named name: String) ? I named is a fault tolerant initializer, and imageLiteralResourceName will crash with an invalid image name. Does imageLiteralResourceName security? When should you use imageLiteralResourceName over named ?

+5
source share
1 answer

Looking at the open source UIKit implementation , it seems there is no difference:

 extension UIImage : _ImageLiteralConvertible { private convenience init!(failableImageLiteral name: String) { self.init(named: name) } public required convenience init(imageLiteralResourceName name: String) { self.init(failableImageLiteral: name) } } public typealias _ImageLiteralType = UIImage 

All he does is force the deployment of the init(named:) result.

This seems to be just an implementation of the _ImageLiteralConvertible protocol found in CompilerProtocols.swift :

 public protocol _ImageLiteralConvertible { init(imageLiteralResourceName path: String) } 

AppKit also has a similar implementation:

 extension NSImage : _ImageLiteralConvertible { private convenience init!(failableImageLiteral name: String) { self.init(named: name) } public required convenience init(imageLiteralResourceName name: String) { self.init(failableImageLiteral: name) } } public typealias _ImageLiteralType = NSImage 

This may be related to the new literal image functionality added in Xcode 8.

+5
source

All Articles