gpt4 book ai didi

通过动态类快速映射/过滤?

转载 作者:搜寻专家 更新时间:2023-11-01 07:05:12 29 4
gpt4 key购买 nike

我正在尝试按变量类型过滤对象数组。节点是一个具有位置的对象,但以不同的方式定义——作为点、矢量或附件。这是一个代码:

class Joint {
var position:Position
init(_ position:Position) {
self.position = position
}
}

class Position {
var point:Point {
return Point (0,0)
}
}

class Point: Position {
//Something different
}

class Vector:Position {
//Something different
}

class Attachment : Position {
//Something different
}

let content : [Joint] = [Joint(Vector()), Joint(Vector()), Joint(Attachment()), Joint(Point()), Joint(Point()) ]
let positionTypes:[Position.Type] = [Point.self, Attachment.self, Vector.self]


let points :[Position] = content.filter{$0.position is Point}.map{$0.position as! Point}
Swift.print(points)
// OK, prints: [__lldb_expr_148.Point, __lldb_expr_148.Point]
let attachments :[Position] = content.filter{$0.position is Attachment}.map{$0.position as! Attachment}
Swift.print(attachments)
// OK, prints: [__lldb_expr_148.Attachment]
let vectors :[Position] = content.filter{$0.position is Vector}.map{$0.position as! Vector}
Swift.print(vectors)
// OK, prints: [__lldb_expr_148.Vector, __lldb_expr_148.Vector]

for positionType in positionTypes {
Swift.print (positionType, type(of:positionType))

// if the next line does not exist loop returns:
// Point Position.Type
// Attachment Position.Type
// Vector Position.Type

// This line doesn't work:
let positions:[Position] = content.filter{$0.position is positionType}.map{$0.position as! positionType}
}

在最后一行我有一条消息Use of undeclared type positionType

如何让最后一行工作?

最佳答案

这不是正确的做法:

let points :[Position] = content.filter{$0.position is Point}.map{$0.position as! Point}

这里正确的工具是flatMap:

let points: [Position] = content.flatMap { $0.position as? Point }

但是 as? 转换并不是真正必要的。 .position 始终是一个 Position;没有必要将它转换到任何东西上。所以你也可以这样做:

let points: [Position] = content.map { $0.position }.filter { $0 is Point }

该模式允许您执行您在最后一步中尝试执行的操作。映射到 .position,然后根据类型进行过滤。

let positions:[Position] = content
.map { $0.position }
.filter { type(of: $0) == positionType }
}

关于通过动态类快速映射/过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48502295/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com