扩展一个Dictionary <string,any =“”> Swift 3的数组

时间:2017-07-22 10:29:51

标签: arrays swift swift-dictionary

var dicts = [["key1": "value1", "key2": "value2"]]

dicts.values(of: "key1") // prints - value1

我正在开发一个项目,我想存储字典数组,然后在条件数组包含特定值的条件下从那里获取数据。

3 个答案:

答案 0 :(得分:1)

Swift 3.0

你可以这样试试。

var dicts:[[String:Any]] = []
var check:Bool = false

dicts = [["search_date": "17/03/17", "search_title": ""],["search_date": "17/02/19", "search_title": "parth"],["search_date": "20/02/19", "search_title": "roy"]]

for item in dicts {
    if let title = item["search_title"] as? String {
        if title == "parth"  {
            check = true
            break
        }else {
            check = false
        }
    }
    else {
       check = false
    }

}
print(check)

答案 1 :(得分:1)

我们可以使用模型来解决问题

class Person: NSObject, NSCoding {
let name: String
let age: Int
init(name: String, age: Int) {
    self.name = name
    self.age = age
}
required init(coder decoder: NSCoder) {
    self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
    self.age = decoder.decodeInteger(forKey: "age")
}

func encode(with coder: NSCoder) {
    coder.encode(name, forKey: "name")
    coder.encode(age, forKey: "age")
}

}

class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    // setting a value for a key
    let newPerson = Person(name: "Joe", age: 10)
    var people = [Person]()
    people.append(newPerson)
    let encodedData = NSKeyedArchiver.archivedData(withRootObject: people)
    UserDefaults.standard.set(encodedData, forKey: "people")

    // retrieving a value for a key
    if let data = UserDefaults.standard.data(forKey: "people"),
        let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Person] {
        myPeopleList.forEach({print( $0.name, $0.age)})  // Joe 10
    } else {
        print("There is an issue")
    }
}

}

感谢Leo Dabus

[Link](https://stackoverflow.com/a/37983027/3706845

答案 2 :(得分:0)

你的问题很模糊。但我所理解的是你想要过滤字典数组,因此它只包含具有特定值的字典,这可以这样做:

let filteredDicts = dicts.filter({ $0.values.contains("value2") })