Swift Extension in a Framework
swift
Solution
(as outlined in http://colemancda.github.io/programming/2015/02/12/embedded-swift-frameworks-osx-command-line-tools/)
1. Create an Objective-C command line tool and change the Search Paths
Not Swift. You can create a Swift framework for the code you'd put in your command line tool, but the tool itself must not compile any Swift code. Doing so will confuse the linker and make it see duplicate declarations of the Swift library (one in the shipped .dylib, another embedded in the command line tool).
- Runpath Search Paths:
Debug: `$(inherited) @executable_path/../Frameworks @executable_path/$(PRODUCT_NAME).bundle/Contents/Frameworks`
Release: `$(inherited) @executable_path/../Frameworks`
2. Create a bundle and change the Build Settings
Give it the same name as your command line tool, but suffixed with `Bundle` (e.g. CommandLineToolProductNameBundle). Also make sure its a target in the same project as your command line tool.
Target Name: Command Line Tool Product Name + `Bundle`
Product Name: Same as Command Line Tool Product Name
- Embedded Content Contains Swift Code: `YES`
3. Add dependencies in Build Phases
Target Dependencies: Your command line tool
Create a new `Copy files` phase, set the `Destination` to `Executables` and add your command line tool to the list of files to copy.
Create a new `Copy files` phase, set the `Destination` to `Frameworks` and add your embedded frameworks to the list of files to copy.
4. Change the `Run` configuration in the bundle's scheme
You can also optionally hide the scheme of your command line tool since it cannot run standalone.
Executable: Your command line tool
Debug Executable: `YES`
Problem
I'm learning about Swift's extensions and ran into a somewhat strange problem. When I write an extension on String and compile it into a framework, I am able to import the framework into a different project and use the string extension without any issues. However, when I write an extension on NSDate and try attempt to use it in a different project, the compiler reports "NSDate does not have a member named..." To be exactly, I created a very simply swift file including these lines of code – ``` import Foundation extension NSDate { func blah() -> Int { return 0 } } ``` I then created a target (Cocoa Framework) and added this file to the compile list. The framework was compiled successfully. I then created a command line tool and imported this project, while linking against the framework. When I call the function blah() on an NSDate, the compiler complained. I'm using Xcode beta 3.