Yoichi Tagaya
Yoichi Tagaya

Reputation: 4577

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

Is there any way to get a Swift type name as a string with its namespace (or framework name)?

For example, if Foo.framework has a class named Bar, I would like to get a string something like "Foo.Bar".

The followings just return the class name "Bar".

let barName1 = String(Bar.self)       // returns "Bar"
let barName2 = "\(Bar.self)"          // returns "Bar"
let barName3 = "\(Bar().dynamicType)" // returns "Bar"

I would like to also get the framework name "Foo" as a namespace.

Upvotes: 17

Views: 7288

Answers (2)

Clay Ellis
Clay Ellis

Reputation: 5330

String(reflecting:) works right now, but could change in the future. So if you only need the fully-qualified name temporarily, you should be fine. However, if the name is something you're going to rely on over a longer period of time (spanning multiple releases of Swift) you shouldn't use it.

The Swift community is trying to come to a consensus on a longer-term method for getting the information from a type.

From Joe Groff:

In 4.2, String(reflecting:) still shows a fully qualified name for local types, but the local type context is anonymized and printed in a way that's intended to be clear is non-stable, since no matter what reflection support we add in the future, it'd be a bad idea to incidentally rely on the presence or identity of local types in dynamic code.

https://forums.swift.org/t/getting-the-more-fully-qualified-name-of-a-type/14375/9

Upvotes: 2

Martin R
Martin R

Reputation: 539705

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.

Upvotes: 33

Related Questions