arrays - 如何在 Swift 中合并不同对象的数组

标签 arrays swift higher-order-functions

<分区>

这听起来很简单,但我如何在 Swift 中合并两个不同类型的数组(Simpson 和 Movie),然后继续按对象唯一的共同属性(在本例中为“名称”)按字母顺序排列该对象数组?

struct Simpson {
    var age: Int
    var name: String
    init(age: Int, name: String) {
        self.age = age
        self.name = name
    }
}
let homer = Simpson(age: 39, name: "Homer")
let marge = Simpson(age: 36, name: "Marge")
var simpson = [homer, marge] // [{age 39, name "Homer"}, {age 36, name "Marge"}]

struct Movie {
    var location: String
    var name: String
    init(location: String, name: String) {
        self.location = location
        self.name = name
    }
}
let jaws = Movie(location: "Amity", name: "Jaws")
let et = Movie(location: "LA", name: "E.T")
var movies: [Movie] = [jaws, et] // [{location "Amity", name "Jaws"}, {location "LA", name "E.T"}]

最佳答案

你需要

protocol SharedName {
    var name : String {get set}
}

struct Simpson: SharedName {
    var name : String = ""
    // add other vars 
}

struct Movie: SharedName {
    var name : String = ""
    // add other vars 
}

然后创建一个数组

var arr:[SharedName] = [] // fill in with different objects from Simpson and Movie
arr.sort { $0.name < $1.name }

提示:

使用 struct 摆脱 init

init(age: Int, name: String) {
    self.age = age
    self.name = name
}

&

init(location: String, name: String) {
    self.location = location
    self.name = name
}

你应该让它们自动生成

关于arrays - 如何在 Swift 中合并不同对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56917381/

相关文章:

JavaScript——试图使用循环删除数组中的某些项目,但它删除了所有项目

python - 在 numpy 中混合数组的最快方法?

swift - 以编程方式或通过 xcode 将 NSTextView 设置为按字符换行?

swift - 用于 UI 测试的 Typhoon 交换组件

arrays - 哪种方法更好,每次保存一个值或评估?

arrays - 无法返回过滤后的数组

jQuery 数组不断返回 [object Object]

java - 在凯撒密码中引用数组中的字符

ios - SpriteKit : find all descendants of SKNode of certain class?

android - 高阶函数作为绑定(bind)适配器的问题