将字符串数组转换为图像数组

时间:2018-02-22 11:16:44

标签: arrays swift

我有一个字符串数组,可以转换为图像数组。

var inviteStatus = [Any]()    
inviteStatus = ["accepted", "accepted", "pending", "pending"]

当邀请状态为"已接受"时,我希望将其替换为该索引处的图像。期望的结果是:

inviteStatus = [UIImage(named: "accepted.png"), UIImage(named: "accepted.png"), UIImage(named: "pending.png"),, UIImage(named: "pending.png")]

我尝试使用以下代码,但它无效:

for (index, str) in self.arrayInviteStatus.enumerated() {
    self.arrayInviteStatus[index] = str.replacingOccurrences(of: "accepted", with: UIImage(name: "accepted.png"))
    self.arrayInviteStatus[index] = str.replacingOccurrences(of: "pending", with: UIImage(name: "pending"))
}

感谢您的帮助。

4 个答案:

答案 0 :(得分:3)

使用map

let inviteStatusImages = inviteStatus.map{ UIImage(named: $0+".png") }

不鼓励您使用[Any]。最好使用两个不同类型的独立数组。

答案 1 :(得分:1)

我认为map绝对是可行的方法,但也许可以考虑使用enum,因此您可以通过类型安全的方式来区分这两种情况:

enum InviteStatus {
  case accepted
  case pending
}

现在你可以拥有一个InviteStatus数组,并将map与模式匹配结合起来:

let inviteStatus: [InviteStatus] = [.accepted, .accepted, .pending, .pending]

func statusToImage(status: InviteStatus) -> UIImage {
  switch status {
    case let .accepted: return UIImage(named: "accepted.png")
    case let .pending: return UIImage(named: "pending.png")
  }
}

let imageArray = inviteStatus.map(statusToImage)

这给你的是能够在不失去类型安全的情况下轻松重构。例如。如果你想在将来添加另一个状态案例,例如"已拒绝"或类似的东西,你可以将它添加到你的枚举中,switch-case模式匹配将在编译时告诉你你&# 39;我必须添加另一个案例。

答案 2 :(得分:0)

你可以这样做

var inviteStatus: [String] = [] 
inviteStatus = ["accepted", "accepted", "pending", "pending"]
var imgArray: [UIImage] = []
imageArray = inviteStatus.map { UIImage(named: "\($0).png") }

答案 3 :(得分:0)

您可以尝试创建一个集成数组,然后将变量传递给原始数组

var inviteStatus = [Any]()
        inviteStatus = ["accepted", "accepted", "pending", "pending"]
        //inviteStatus = [UIImage(named: "accepted.png"), UIImage(named: "accepted.png"), UIImage(named: "pending.png"),, UIImage(named: "pending.png")]
        var newArray = [Any]()
        for invStat in inviteStatus {
            newArray.append(UIImage(named: "\(invStat).png"))
        }
        inviteStatus.removeAll()
        for na in newArray{
            inviteStatus.append(na)
        }