打字别名的目的

问题描述

我以为今天我终于明白了什么是typealias。

我没有。

让我们看一个例子:

let paths = document.querySelectorAll("svg path")
paths.forEach(p=>{
  let bb = p.getBBox()
p.setAttribute("transform",`translate(${-bb.x -bb.width/2 + 10},${-bb.y - bb.height/2 +10})`)
})

一切都很好。
然后我做了一个小改动:

typealias Graph = [String: [String]]

let futurama: Graph = [
    "you": ["bender","hermes","scruffy"],"bender": ["hubert","zoidberh"],"hermes": ["hubert","amy","hubert": ["mom","fry"],"fry": ["leela"],"leela": ["brannigan","nibbler","amy": ["kif"],"brannigan": ["kif"],"zoidberh": [],"kif": [],"mom": [],"nibbler": [],"scruffy": []
]

extension Graph {
    // Breadth First Search
    func bfs(from start: String,to finish: String) -> [String]? { 
        // Implementation of this graph algorithm here
    }
}

print(
    futurama.bfs(from: "you",to: "scruffy")?.joined(separator: " --> ") ?? "There is no pass,sorry"
)

我期望现在let futurama: [String: [String]] = [ "you": ["bender",... 将不会编译,因为futurama.bfs()没有方法futurama。我在想,这是多么出色的语言设计!
但是我很失望。没有改变。完全没有该代码仍然可以编译和运行。
所以...

  1. 什么是typealias?
  2. 如何实现我期望的行为?

解决方法

根据文档(在此处找到:https://docs.swift.org/swift-book/ReferenceManual/Declarations.html):

类型别名声明引入了现有类型的命名别名 进入您的程序。

[...]

在声明类型别名后,可以使用别名来代替 程序中各处的现有类型。现有类型可以 是命名类型或复合类型。 类型别名不会创建新的 类型; 它们只是允许名称引用现有类型。

因此,实际上您不是在定义新类型。您只是使用其他名称为您的类型加上别名,以使该类型更易于使用。

因此,在您的情况下,Graph只是类型[String: [String]]的另一个别名,不会为您引入新的类型。

因此,要达到您的期望,我想有很多可能性。一种方法是将Graph包装起来,例如[String: [String]]转换为结构或类,并为该结构/类编写扩展名。实施此方法的方式在很大程度上取决于要实现的目标。

这能回答您的问题吗?

,
  1. typealias实际上是为类型创建“别名”(即另一个名称)。您不是要创建新类型,而只是创建现有类型的另一个 name 。来自Language Reference

    类型别名不会创建新的类型。他们只是允许名称引用现有类型。

    因此,一旦声明了类型别名,Graph[String: [String]]现在引用相同的类型。 Graph上的扩展名等效于[String: [String]]上的扩展名。

  2. 对于所需的行为,您需要创建一个新类型。对于Graph,我认为一种结构比较合适:

    struct Graph {
        ...
    }
    

    然后,Graph结构可以包含(或封装 )类型为[String: [String]]的私有属性,

    private var adjacencyDictionary: [String: [String]]
    

    ,您应该编写访问方法,并(可选)对图形进行变异。例如getNode(withName:)getNeighboursOfNode(withName:)addNodeaddEdge等。

    您不应在此处使用类型别名,因为图形 不是 [String: [String]]。例如,以下[String: [String]]不是有效的图形:

    ["a": ["b"]]
    
,

typealias只是语法糖。在编译开始时,所有类型别名都会被它们别名的实际类型替换,因此类型别名在类型系统级别上不存在。

这就是您所看到的行为的原因-在类型系统级别,Graph就是[String:[String]],因此定义与Graph一起使用的任何功能实际上都可以在别名类型,即[String:[String]]

如果您希望Graph是实类型,则需要这样声明-将其设置为structclass,并带有Dictionary的后备存储

struct Graph {
    var storage: [String: [String]]
}

extension Graph {
    // Breadth First Search
    func bfs(from start: String,to finish: String) -> [String]? {
        // Implementation of this graph algorithm here
    }
}

let futurama: [String: [String]] ...
futurama.bfs() // This doesn't compile anymore
,

根据下面的答案,我提出了一种非常简洁的方法。
这是下标,ExpressibleByDictionaryLiteral和泛型的组合。

struct Graph<T> where T: Hashable {
    private var storage: [T: [T]]
    
    subscript(key: T) -> [T]! {
        storage[key]
    }
    
    func bfs(from start: T,to finish: T) -> [T]? {
        // Implementation of the algorithm here. 
    }
}

extension Graph: ExpressibleByDictionaryLiteral {

    init(dictionaryLiteral elements: (T,[T])...) {
        storage = .init(uniqueKeysWithValues: elements)
    }
}

我的第一篇文章中的代码将无需更改就可以编译和运行!
(除通用内容外,String应该在任何地方都更改为T

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...