UIImage(名为:)和UIImage(imageLiteralResourceName :)有什么区别?

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


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

Swift 3 / iOS 10在UIImage上添加了一个新的初始化程序,imageLiteralResourceName:

extension UIImage {

    required public convenience init(imageLiteralResourceName name: String)
}

How does this differ from public init?(named name: String)? I named is a failable initializer while imageLiteralResourceName will crash on an invalid image name. Does imageLiteralResourceName trade safety for performance? When should you use imageLiteralResourceName over named?

这与公共init有什么不同?(命名名称:String)?我命名是一个可用的初始化程序,而imageLiteralResourceName将在无效的图像名称上崩溃。 imageLiteralResourceName是否为性能交易安全?什么时候应该使用imageLiteralResourceName而不是命名?

1 个解决方案

#1


5  

Looking at the open-source implementation of UIKit, there seems to be no difference:

看看UIKit的开源实现,似乎没有区别:

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 it does is force-unwrap the result of init(named:).

它只是强制解包init(名为:)的结果。

It seems like it's just an implementation of the _ImageLiteralConvertible protocol found in CompilerProtocols.swift :

看起来它只是CompilerProtocols.swift中的_ImageLiteralConvertible协议的一个实现:

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

AppKit also has a similar implementation:

AppKit也有类似的实现:

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 might have to do with the new image literal functionality added to Xcode 8.

这可能与添加到Xcode 8的新图像文字功能有关。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/06/14/3095895929de84db50c758952d1b4e26.html



 
  © 2014-2022 ITdaan.com 联系我们: