gpt4 book ai didi

swift - 类型别名的目的

转载 作者:行者123 更新时间:2023-12-05 08:49:41 31 4
gpt4 key购买 nike

我以为今天我终于明白什么是类型别名了。

我没有。

让我们来看一个例子:

typealias Graph = [String: [String]]

let futurama: Graph = [
"you": ["bender", "hermes", "scruffy"],
"bender": ["hubert", "zoidberh"],
"hermes": ["hubert", "amy", "scruffy"],
"hubert": ["mom", "fry"],
"fry": ["leela"],
"leela": ["brannigan", "nibbler", "scruffy"],
"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", "hermes", "scruffy"],
"bender": ["hubert", "zoidberh"],
...

我原以为 futurama.bfs() 不会编译,因为 futurama 没有方法 bfs。多么聪明,我在想,多么伟大的语言设计!
但我很失望。没有改变。完全没有。代码仍然可以编译和工作。
所以……

  1. 什么是类型别名?
  2. 如何实现我期望的行为?

最佳答案

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

A type alias declaration introduces a named alias of an existing typeinto your program.

[...]

After a type alias is declared, the aliased name can be used insteadof the existing type everywhere in your program. The existing type canbe a named type or a compound type. Type aliases do not create newtypes; they simply allow a name to refer to an existing type.

所以实际上你并没有定义一个新的类型。您只是用另一个名称为您的类型起别名,以使该类型更易于使用。

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

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

这是否回答了您的问题?

关于swift - 类型别名的目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63464958/

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