Skip to content

Instantly share code, notes, and snippets.

@DianQK

DianQK/Swifty.md

Last active Apr 7, 2016
Embed
What would you like to do?
struct Phone {
    var number: String?
    var originalLabel: String?
    
    init(number: String? = nil, originalLabel: String? = nil) {
        self.number = number
        self.originalLabel = originalLabel
    }
}

struct User {
    var name: String?
    var phones: [Phone]?
    
    init(name: String? = nil, phones: [Phone]? = nil) {
        self.name = name
        self.phones = phones
    }
}

我们需要从 [User] 中拿出符合以下条件的结果:

  • name 不是 nil ,也就是有名字的 User
  • phonenumber 不是 nil ,也就是要有手机号

拿出以上结果后,最终返回一个 ["name": "", "number": ""] 。也就是说最终的 array 是根据 number 数量决定的。

struct Phone {
var number: String?
var originalLabel: String?
init(number: String? = nil, originalLabel: String? = nil) {
self.number = number
self.originalLabel = originalLabel
}
}
struct User {
var name: String?
var phones: [Phone]?
init(name: String? = nil, phones: [Phone]? = nil) {
self.name = name
self.phones = phones
}
}
let user1 = User(name: "user1", phones: nil)
let user2 = User(name: nil, phones: [Phone(number: "110")])
let user3 = User(name: "user3", phones: [Phone(number: "120"), Phone(number: "1201")])
let user4 = User(name: "user4", phones: [Phone(number: "140")])
typealias UploadContact = [String: String]
[user1, user2, user3, user4]
// 最终结果 [["number": "120", "name": "user3"], ["number": "1201", "name": "user3"], ["number": "140", "name": "user4"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment