【问题标题】:How to filter an Dictionary with a key and a value that is a structure in Swift 5?如何使用 Swift 5 中结构的键和值过滤字典?
【发布时间】:2020-05-10 14:51:48
【问题描述】:

如何过滤具有Swift 5 结构值的字典? 我打算从池(字典)中过滤出结构字段'stock'等于'STOCK01'(A1, A2 and A3)的股票。

var pool = [String: StockOption]()

pool[ "A1" ] = StockOption( code: "A1", strikePrice: "10.1", stock: "STOCK01" )
pool[ "A2" ] = StockOption( code: "A2", strikePrice: "11.5", stock: "STOCK01" )
pool[ "A3" ] = StockOption( code: "A3", strikePrice: "12.7", stock: "STOCK01" )

pool[ "B5" ] = StockOption( code: "B5", strikePrice: "23.3", stock: "STOCK02" )
pool[ "B6" ] = StockOption( code: "B6", strikePrice: "24.3", stock: "STOCK02" )


struct StockOption {

    var code                  : String?       // "A1", "B2", ..., "ZE43", ... (unique key) ,
    var strikePrice           : String?       // just a price stored in string

    var stock                 : String?       // "STOCK01", "STOCK02", ... "STOCK99" (Can repeat)
}

【问题讨论】:

标签: swift xcode dictionary filter structure


【解决方案1】:

你需要

let res = pool.filter { $0.value.stock == "STOCK01" }

【讨论】:

  • 在操场上,您的建议按预期工作。但是,当我输入以下内容时,我才是真正的代码:“let res = pool.values.filter { $0.stock == "STOCK01" }" 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2017-03-27
  • 2020-05-21
  • 1970-01-01
  • 2023-01-14
  • 1970-01-01
  • 2019-10-09
相关资源
最近更新 更多