Swift:写这个数组映射的更优雅的方法吗?

时间:2019-05-17 07:06:11

标签: ios arrays swift xcode

我想知道是否有一种更优雅的方式来编写此代码:

struct S {
    var state: [String: Any] 

    public var amounts: [Amount] {
        var result: [Amount] = []
        (self.state["amounts"] as? [Any]?)??.forEach({ a in
            result.append(Amount(a))
        })
        return result
    }      
}

struct Amount {
    init(_ any: Any?) {}
}

我尝试将map用于数组,但找不到找到方法。

5 个答案:

答案 0 :(得分:4)

您还可以使用guard let和提前返回,这会使它看起来更好一些。

这是我的做法,

struct S {

    var state: [String: Any]

    public var amounts: [Amount] {
        guard let amounts = state["amounts"] as? [Any] else {
            return []
        }

        return amounts.map(Amount.init)
    }

}

答案 1 :(得分:3)

struct S {
    var state: [String: Any]
    public var amounts: [Amount] {
        return (self.state["amounts"] as? [Any] ?? []).map({ Amount($0) })
    }
}

struct Amount {
    init(_ any: Any?) {}
}

答案 2 :(得分:2)

您在这里使用了太多不必要的可选内容。您应始终将as?与非可选类型一起使用。而不是forEach,请使用map

public var amounts: [Amount] {
    if let anyArray = self.state["amounts"] as? [Any] {
        return anyArray.map(Amount.init)
    } else {
        return []
    }
}

答案 3 :(得分:1)

您可以将其放在一行中,

public var amounts: [Amount] {
    return (self.state["amounts"] as? [Any])?.map({ Amount($0) }) ?? []
}

答案 4 :(得分:1)

init(_ state: [Amount]) {
    self.init()
    guard let amounts = state["amounts"] as? [Any] else {
        return []
    }

    return amounts.map(Amount.init)
}