How to Get a Swift Type Name as a String with Its Namespace (Or Framework Name)

How to get a Swift type name as a string with its namespace (or framework name)

Use String(reflecting:):

struct Bar { }

let barName = String(reflecting: Bar.self)
print(barName) // <Module>.Bar

From the Xcode 7 Release Notes:

Type names and enum cases now print and convert to String without
qualification by default. debugPrint or String(reflecting:) can still
be used to get fully qualified names.

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

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.

Is there a way to get a _stable_ generic class name in Swift?

New starting from Xcode 6.3 beta 1

Good news! Starting from 6.3 you can do:

toString(Gen<Int>())

And that'd print: Gen<Swift.Int>

OLD Answer:

If the scope can be reduced to T: AnyObject then you can implement it as follows:

class Gen<T: AnyObject> {
var className: String {
return "Gen<\(NSStringFromClass(T.self))>"
}
}

How to use Namespaces in Swift?

Even though it is possible to implement namespaces using Framework and Libraries but the best solution is to use local packages using Swift Package Manager. Besides having access modifiers, this approach has some other benefits. As in Swift Package Manager, the files are managed based on the directory system, not their target member ship, you won't have to struggle with merge conflicts that arise frequently in teamworks. Furthermore, there is no need to set file memberships.

To check how to use local Swift packages refer to the following link:
Organizing Your Code with Local Packages

Namespace in Swift: Differentiate between an enum and a class

It turns out you can make a file that has a typealias

import class Fruits.Banana

typealias BananaClass = Fruits.Banana

Then just use BananaClass instead in ClassA



Related Topics



Leave a reply



Submit