我正在Swift中创建一个邻接表,存储一个节点数组。但是,当从现有节点添加边时,我需要检查from密钥是否存在于任何子节点中,并且是否确实要检查to值是否存在于同一子节点中。
func addEdge(from: String, to: String) {
//the full code for addEdge is incomplete here
if (children.contains{ $0.nodes[from] != nil}) {
for child in children {
if (child.nodes[from] != nil) {
if (!(child.nodes[from]?.contains{$0 == to})!){
child.nodes[from]?.append(to)
}
}
}
}
}
孩子是
var children = [Node]()
并且节点是
class Node: Hashable {
var nodes = [String:[String]]()
var hashValue: Int{ return nodes.hashValue }
static func == (lhs: Node, rhs: Node) -> Bool {
return lhs.nodes.keys == rhs.nodes.keys
}
}
现在可以了,但是看起来真的很丑。 Swift中肯定有更好的方法,但这是什么?
答案 0 :(得分:1)
假设您不希望更改实现上述代码的方式,但希望提高可读性,则可以利用if let
和可选链接来使代码更整洁,更具可读性。
func addEdge(from: String, to: String) {
//the full code for addEdge is incomplete here
if children.contains{ $0.nodes[from] != nil } {
for child in children {
if let fromNode = child.nodes[from], fromNode.contains{$0 == to} {
fromNode.append(to)
}
}
}
}
答案 1 :(得分:0)
尝试类似的东西:
if (children.contains{ $0.nodes[from] != nil}) {
children.filter { $0.nodes[from] != nil }.
compactMap { $0.nodes[from] }.
filter { !($0.nodes[from]!.contains{$0 == to}) }.
forEach { $0.nodes[from]?.append(to) }
}