首页 > 解决方案 > 如何将字符串类型数据转换为我自己的类类型

问题描述

我有一个 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”)
 } 
}

标签: swiftcastingswift4

解决方案


根据@rmaddy,问题是通过将 Node 实例放入类型字典中来解决的var myNodes: [Int: Node]。并通过他们的密钥访问它们myNodes.keys


推荐阅读