我不太清楚该如何把它写成文字,但是代码应该会有所帮助。
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 { $0.name }
}
func loadFriendsArray() -> [String] {
let arrayOfFriends = self.People.map { $0.friends }
let friends = arrayOfFriends.flatMap { $0 }
return friends
}然后我交叉比较了这两个数组,以提醒使用此函数的普通用户.
func loadCommonInteractingArray() -> [String] {
let output = loadNamesArray().filter{ loadFriendsArray().contains($0) }
return output
}但这只会返回"Sam“、"Tom”、"Adam“、"William",我不知道从哪里可以得到我想要的结果,即识别匹配对,而不是仅仅列出那些匹配的。
谢谢
发布于 2020-04-11 19:28:02
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{ $0.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和汤姆在同一个社交圈里
汤姆和萨姆在同一个社交圈里。
亚当和威廉在同一个社交圈里。
威廉和亚当在同一个社交圈里。
发布于 2020-04-11 19:22:04
据我所知,您正在尝试查找任何其他人的friends数组中包含的每个人。
for person in people {
let others = people.filter {$0 != person}
for other in others {
if other.friends.contains(person.name) {
print("\(person.name) is in the same social circle as \(other.name)")
}
}
}People模型类必须符合Equatable才能完成上述操作。
https://stackoverflow.com/questions/61162103
复制相似问题