Getting the currently running target name

How can I reliably get the currently running target name in Swift 4 ?


My solution so far is the following:


        let bundle = Bundle.main
        let executablePath = bundle.executablePath
        let splitArray = executablePath?.split(separator: "/")
        let targetName = splitArray?.last?.description


Is there a better way ?

Accepted Reply

I’m mystified as to why you’d want this info — if you can explain the context I may be able to offer better advice — but your current code is working way too hard. Try this:

print(Bundle.main.bundleURL.lastPathComponent)
// prints MyAppName.app

print(Bundle.main.executableURL!.lastPathComponent)
// prints MyAppName

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

I’m mystified as to why you’d want this info — if you can explain the context I may be able to offer better advice — but your current code is working way too hard. Try this:

print(Bundle.main.bundleURL.lastPathComponent)
// prints MyAppName.app

print(Bundle.main.executableURL!.lastPathComponent)
// prints MyAppName

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Hi eskimo,


Thanks for the answer.


The idea is to be able to configure an application with multiple targets.


Objects such as view controllers will be configured in different ways based on the target in the application context.


Cheers.

The idea is to be able to configure an application with multiple targets.

I don’t think you should do this based on the executable name; such an approach is likely to cause maintenance issues down the pike. For example, imagine Future You™ decides to reuse this view controller in some completely unrelated app; they are going to be very surprised when they see it behave differently just because the executable name changed.

Some alternatives:

  • You can use conditional compilation. See The Swift Programming Language for details.

  • Your code could look up a resource (perhaps a property list) in your target and then behave differently depending on the values it finds.

  • You could have a separate ‘parameters’ Swift file containing configuration parameters, and then include different ones in each target.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"