swift - 如何将字符串类型数据转换为我自己的类类型
问题描述
我有一个 Node 类,它负责定义节点的名称和坐标。类的实例已经定义为 nodeOne 和 nodeTwo。我正在尝试进行字符串连接,如图所示var node: String = “node”+ userInput
并将其传递给test(source: Node)
显然接受数据类型为 Node.So,如何从字符串类型转换为我的类 Node?我试着做test(source: nodeOne as Node)
,但它抛出了一个错误,不能在运行时强制转换。
class Node {
let name: String
let coordinates: CGPoint
init(name: String, coordinates: CGPoint) {
self.name = name
self.coordinates = coordinates
}
}
类对象:
//defining nodes
let nodeOne = Node(name: "East Entrance", coordinates: CGPoint(x: 623.5, y: 166.0))
let nodeTwo = Node(name: "Main Entrance", coordinates: CGPoint(x: 621.0, y: 935.5))
var userInput: String = One
var node: String = “node”+ userInput
test(source: nodeOne as Node)
func test(source: Node) {
If nodeOne.name == "nodeOne" {
print(“node 1”)
} else {
print(“node 2”)
}
}
解决方案
根据@rmaddy,问题是通过将 Node 实例放入类型字典中来解决的var myNodes: [Int: Node]
。并通过他们的密钥访问它们myNodes.keys
推荐阅读
- java - 为自定义视图提供阴影效果
- java - 如何在 tfs Java sdk 中查询链接的工作项
- excel - VLOOKUP 的宏
- php - 代码点火器邮件功能在我的本地运行良好但在现场运行并引发错误
- python - 将 pyspark 数据框行值转换为同一行中其他元素的关系
- mysql - MySql - 按日期选择和计算正在运行的 AVG 日期
- c# - 如何在 MVC 中显示 Asp.net Identity cookie 过期弹出窗口
- html-table - Selenium webdriver代码如何遍历表/网格中的隐藏行
- php - PHP SOAP-ERROR:对象没有“test2”属性
- php - 登录时捕获用户id并根据操作保存用户id