如何将数组与嵌套数组进行比较并打印匹配对,而不是匹配的值列表? (代码帮助解释)

How to compare array with nested array and print the matching pairs, not list of values that match? (Code helps explain)

我不太确定如何用文字表达,但代码应该有所帮助。

var People = [

      .init(name: "Sam", friends: ["James", "Tom", "Rick"]),
      .init(name: "Tom", friends: ["Callum", "Steve", "Sam"]),
      .init(name: "Adam", friends: ["Harry", "Diane", "William"]),
      .init(name: "William", friends: ["Rodger", "Adam", "Bill"]),
      .init(name: "Guy", friends: ["Zack", "Frank", "Cody"])
]

我想生成打印的警报

" Sam is in the same social circle as Tom " / " Tom is in the same social circle as Sam "

" Adam is in the same social circle as William " / " William is in the same social circle as Adam "

" Guy has no common social circles "

我尝试的方法是首先创建一个名称数组:[String],然后为朋友做同样的事情,使用以下函数将 [[String]] 转换为 [String]...

func loadNamesArray() -> [String] {
    return self.People.map { [=14=].name }
}

func loadFriendsArray() -> [String] {
    let arrayOfFriends = self.People.map { [=14=].friends }
    let friends = arrayOfFriends.flatMap { [=14=] }
    return friends
}

然后我交叉比较了两个数组以提醒任何使用此功能的普通人...

func loadCommonInteractingArray() -> [String] {
    let output = loadNamesArray().filter{ loadFriendsArray().contains([=15=]) }

    return output
}

但这只是 returns ["Sam"、"Tom"、"Adam"、"William"],我不确定从这里到哪里去获得我想要的结果,即识别匹配对,而不仅仅是匹配的列表。

谢谢

据我了解,您正在尝试查找任何其他人的 friends 数组中包含的每个人。

for person in people {
    let others = people.filter {[=10=] != person}

    for other in others {
        if other.friends.contains(person.name) {
            print("\(person.name) is in the same social circle as \(other.name)")
        }
    }
}

People 模型 class 必须符合 Equatable 才能执行上述操作。

struct Person {
    let name: String
    let friends: [String]
}

var people: [Person] = [
      .init(name: "Sam", friends: ["James", "Tom", "Rick"]),
      .init(name: "Tom", friends: ["Callum", "Steve", "Sam"]),
      .init(name: "Adam", friends: ["Harry", "Diane", "William"]),
      .init(name: "William", friends: ["Rodger", "Adam", "Bill"])]

func loadCommonInteracting(in people: [Person]) -> [String] {
    var connections: [String] = []
    people.forEach { person in
        let friends = people.filter{ [=11=].friends.contains(person.name) }
        for friend in friends {
            connections.append("\(person.name) is in the same social circle as \(friend.name)")
        }
        
    }
    return connections
}

let connections = loadCommonInteracting(in: people)
for connection in connections {
    print(connection)
}

这将打印

Sam is in the same social circle as Tom

Tom is in the same social circle as Sam

Adam is in the same social circle as William

William is in the same social circle as Adam