我正在使用 R.swift 获取 Assets 名称。我正在创建一个用于检查 Assets 重复项的库,并希望遍历所有 Assets 名称以获取数据以检查 Assets 的重复性。我如何快速遍历静态。
struct image {
static let winnerPunyaOrang = Rswift.ImageResource(bundle: R.hostingBundle, name: "Winner Punya Orang")
static let fire_ico = Rswift.ImageResource(bundle: R.hostingBundle, name: "fire_ico")
static let fire = Rswift.ImageResource(bundle: R.hostingBundle, name: "fire")
}
最佳答案
您的解决方案存在一些问题:
- 如果不创建和 维护所有值的数组(您不想这样做)。
- 将图像分配给静态变量这一事实会给您的程序带来大量内存开销,如果这些是大图像或图像很多,这将尤其糟糕。
更好的方法是使用 CaseIterable
枚举。这将允许将来使用不会导致内存开销且维护最少的模式进行代码扩展。
enum ImageAsset: String, CaseIterable {
//your cases go here...
case winnerPunyaOrang = "Winner Punya Orang"
case fireIco = "fire_ico"
//... and you can continuously extend them by adding more asset names
//This function will return images as and when you need them
func image() -> UIImage {
return Rswift.ImageResource(bundle: R.hostingBundle, name: self.rawValue)
}
}
现在,只要您需要程序中的图像资源,您只需调用:
let image = ImageAsset.fireIco.image()
关于ios - 如何遍历结构的静态常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54385470/