如何消除具有相同名称的类型和模块的歧义? [英] How can I disambiguate a type and a module with the same name?
问题描述
我正在尝试在项目中使用KárolyLőrentey的基于B树的OrderedSet
.但是,我遇到了一个问题,即我无法声明不合格的OrderedSet<T>
,因为该名称在Foundation的NSOrderedSet
(在Swift 3中作为OrderedSet
导入)和BTree
的OrderedSet
之间冲突./p>
I'm trying to use Károly Lőrentey's B-tree based OrderedSet
in a project. However, I'm running into an issue where I can't declare an unqualified OrderedSet<T>
because the name conflicts between Foundation's NSOrderedSet
(imported as OrderedSet
in Swift 3) and BTree
's OrderedSet
.
let set = OrderedSet<Int>()
// error: 'OrderedSet' is ambiguous for type lookup in this context
// Found this candidate: Foundation.OrderedSet:3:14
// Found this candidate: BTree.OrderedSet:12:15
要解决此冲突,通常需要限定名称,然后再赋予BTree.OrderedSet<T>
.但是,BTree
模块还包含一个名为BTree
的类.如果我写BTree.OrderedSet
,Swift认为我指的是嵌套在BTree.BTree
类型中的名为OrderedSet
的类型.
To resolve this conflict, you would normally qualify the name, and that would give you BTree.OrderedSet<T>
. However, the BTree
module also contains a class named BTree
. If I write BTree.OrderedSet
, Swift thinks that I'm referring to a type named OrderedSet
that is nested in the BTree.BTree
type.
let set = BTree.OrderedSet<Int>()
// error: reference to generic type 'BTree' requires arguments in <...>
如果我不使用import BTree
,则根本无法使用BTree
名称.
If I don't import BTree
, I can't use the BTree
name at all.
// no import BTree
let set = BTree.OrderedSet<Int>()
// error: use of undeclared type 'BTree'
如何解决BTree
类型和BTree
模块之间的这种歧义?
How can I resolve this ambiguity between the BTree
type and the BTree
module?
推荐答案
可以使用鲜为人知的import (class|struct|func|protocol|enum) Module.Symbol
语法消除类型的歧义.
The type can be disambiguated using the little-known import (class|struct|func|protocol|enum) Module.Symbol
syntax.
import struct BTree.OrderedSet
从这一点开始,OrderedSet明确引用了BTree中的那个.
From this point on, OrderedSet unambiguously refers to the one in BTree.
如果在某些文件中这仍然是模棱两可或次优的,则可以创建一个Swift文件来使用类型别名重命名导入:
If this would still be ambiguous or sub-optimal in some files, you can create a Swift file to rename imports using typealiases:
// a.swift
import struct BTree.OrderedSet
typealias BTreeOrderedSet<T> = BTree.OrderedSet<T>
// b.swift
let foo = OrderedSet<Int>() // from Foundation
let bar = BTreeOrderedSet<Int>() // from BTree
Swift 3讨论了一种新语法,但失败了.
There was a new syntax discussed for Swift 3, but it fell through.
这篇关于如何消除具有相同名称的类型和模块的歧义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!