Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

swift - How can I disambiguate a type and a module with the same name?

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

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 <...>

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'

How can I resolve this ambiguity between the BTree type and the BTree module?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The type can be disambiguated using the little-known import (class|struct|func|protocol|enum) Module.Symbol syntax.

import struct BTree.OrderedSet

From this point on, OrderedSet unambiguously refers to the one in BTree.

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

There was a new syntax discussed for Swift 3, but it fell through.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...