Using Swift Package Manager

About Swift Package Manager

The Swift Package Manager is the tool used to build Applications and Libraries. it streamlines the process of managing multiple Modules & Packages. Before we go ahead and learn to use Swift Package Manager we need to get familiar with some basic terminology.

Modules

Modules are used to specify a namespace and used to control access to that particular piece of code. Everything in Swift is organised as a module. An entire app can fit into a module or an app can be made using multiple modules. The fact that we can build modules using other modules means that reusing code becomes a lot easier. So, when we make an iOS App with Xcode and Swift. The entire app is considered a single module.

Targets

Targets are the end product that we want to make. So an app for iOS is a separate target. A library is a target. An app for macOS is a separate target. You can have many targets. Some can be for testing purposes only.

Packages

Packages group the necessary source files together. A package can contain more than one target. Normally one would create a package for a family of products. For example: you want to make a photo editing app that runs on macOS & iOS. You would create one package for it. That package would have 2 targets: an iOS App & a macOS App.

Products

This is a categorisation of your packages. There are 2 types of products. Executables or Libraries. A library contains the module which can be reused elsewhere. Executables are application that run & may make use of other modules.

Dependencies

Dependencies are the modules or the pieces of code that are required to make the different targets within the package. These are normally provided as URLs.

End Products

*NOTE: Before you get started you must be familiar with Setting up Swift on Linux. If you haven’t done that then please go through the updated article: UPDATE: Swift on Linux. This also makes use of Swift Package Manager.

Example

So let us get started with an example. We are going to learn how to create:

  • a library package called ErrorTypes
  • a library package, called MathOperations, that uses the ErrorTypes library package
  • an executable package called Calc that makes use of the MathOperations package.

We will see how to create all three elements. Also I have uploaded the ErrorTypes & MathOperations packages to the http://www.github.com repository to demonstrate the use of dependencies. You can also create your own local git repositories if you wish.

To illustrate the folder hierarchy: I have created a folder called “Developer” in my Ubuntu linux home folder. Within that I have created a folder called “SPMDEMO“. All the paths that I will be using will be with reference to these folders. You should see a structure like this:

/home/admin/Developer/SPMDEMO/ErrorTypes
/home/admin/Developer/SPMDEMO/MathOperations
/home/admin/Developer/SPMDEMO/Calc

You are free to follow this exercise using your own folder locations. Just modify the paths accordingly.

swift package init
swift package init --type executable
swift build

If you need help with the commands run:

swift package --help
swift --help

Creating a Package

  1. First let us start off by creating the ErrorTypes package.
    mkdir ErrorTypes
  2. Navigate to the folder and create the package:
  3. cd ErrorTypes
    swift package init
    

    By default init will create a library package type.

  4. Navigate to the folder containing the source files:
    cd ./Sources/ErrorTypes/
  5. Open the ErrorTypes.swift file and write the following code
    public enum ErrorCodes : Error
    {
         case FileNotFound(String)
         case DivideByZero(String)
         case UnknownError(String)
    }
    
    public struct MathConstants
    {
         static let pi : Float = 3.14159
         static let e  : Float = 2.68791
    }
    

    Feel free to add some code of your own. The above is just an example.

  6. Run the command to build to make sure that there aren’t any issues. You shouldn’t have any as there are no dependencies of any kind. Its a simple straightforward piece of code.
    swift build
  7. If everything is fine check your code into a git repository. This can be local or on the web. Remember that we will need the URL to this repository.
  8. Navigate back to the SPMDEMO folder.
    cd ~/Developer/SPMDEMO/
  9. Create a folder called MathOperations.
    mkdir MathOperations
  10. Navigate to the newly created folder and run the command to create a library package.
    cd MathOperations
    swift package init
    
  11. Navigate to the sources folder:
    cd ./Sources/MathOperations/
  12. Open the MathOperations.swift file and write the following code.
    import ErrorTypes
    
    public struct MathOperations
    {
         public static func add(Number num1 : Int, with num2 : Int) -> Int
         {
              return num1 + num2
         }
    
         public static func mult(Number num1 : Int, with num2 : Int) -> Int
         {
              return num1 * num2
         }
    
         public static func div(Number num1 : Int, by num2 : Int) throws -> Int
         {
              guard num2 > 0
              else
              {
              throw ErrorCodes.DivideByZero("You are dividing by zero. The second argument is incorrect.")
              }
    
              return num1 / num2
         }
    
         public static func sub(_ num1 : Int, from num2 : Int) -> Int
         {
              return num2 - num1
         }
    }
    
  13. Before we build we need to modify the Packages.swift file to indicate there is a dependency.
    Notice that in the MathOperations.swift file we are importing a module called ErrorTypes. We just created it. But just because we created it doesn’t mean it will be added automatically. We need to pull that module into our own

    Also notice that I have provided access specifiers “public” everywhere. This ensures that the code written in one module is accessible in the other.

    Navigate to the MathOperations parent folder.

    cd ~/Developer/SPMDEMO/MathOperations/
  14. Open the Packages.swift file and make the changes as shown below:
    // swift-tools-version:4.0
    // The swift-tools-version declares the minimum version of Swift required to build this package.
    
    import PackageDescription
    
    let package = Package(name: "MathOperations",
         products: [
              // Products define the executables and libraries produced by a package, and make them visible to other packages.
              .library(name: "MathOperations", targets: ["MathOperations"]),
         ],
    
         dependencies: [
              // Dependencies declare other packages that this package depends on.
              .package(url:"https://github.com/AmaranthineTech/ErrorTypes.git", from:"1.0.0"),
         ],
    
         targets: [
              // Targets are the basic building blocks of a package. A target can define a module or a test suite.
              // Targets can depend on other targets in this package, and on products in packages which this package depends on.
              .target(name: "MathOperations", dependencies: ["ErrorTypes"]),
              .testTarget(name: "MathOperationsTests", dependencies:   ["MathOperations"]),]
    )
    
  15. Once these changes are made save the file and run the command
    swift build

    If you typed everything correctly then you should see the source code for the ErrorTypes module being pulled in and the build being successful.Here are some common mistakes:
    – Forgetting to write the import ErrorTypes statement
    – Error in the URL
    – The from tag not matching the tag in the repository
    – Access specifiers are incorrect or missing
    – Not mentioning the dependencies in the target

  16. Just like with the ErrorTypes module create a git repository for the MathOperations module.
  17. Now let us make the Calc executable that will use the MathOperations library. First navigate back to the SPMDEMO folder and create a folder called Calc.
    cd ~/Developer/SPMDEMO/
    mkdir Calc
    
  18. This time we are going to create an executable package. Run the command:
    swift package init --type executable

    This also creates a similar folder structure as in the case of the library.

  19. Navigate to the folder containing the main.swift file.
    cd ./Sources/Calc/
  20. Modify the main.swift file as shown below:
    import MathOperations
    
    //testing addition
    var result : Int = MathOperations.add(Number: 33, with: 29)
    print("Result of adding 33 with 29 is: \(result)")
    
    //testing multiplication
    result = MathOperations.mult(Number: 33, with: 29)
    print("Result of multiplying 33 with 29 is: \(result)")
    
    //testing division
    do
    {
         result = try MathOperations.div(Number: 33, by: 0)
         print("Result of dividing 33 by 29 is: \(result)")
    }
    catch let error
    {
         print("ERROR: \(error)")
    }
    
    //testing subtraction
    result = MathOperations.sub(3, from: 29)print("Result of subtracting 3 from 29 is: \(result)")
    
  21. Navigate back to the main Calc folder.
    cd ~/Developer/SPMDEMO/Calc/
  22. Modify the Packages.swift file as shown below:
    // swift-tools-version:4.0
    // The swift-tools-version declares the minimum version of Swift required to build this package.
    
    import PackageDescription
    
    let package = Package(name: "Calc",
    dependencies: [
         // Dependencies declare other packages that this package depends on.
         .package(url: "https://github.com/AmaranthineTech/MathOperations.git", from: "1.0.1"),
    ],
    targets: [
         // Targets are the basic building blocks of a package. A target can define a module or a test suite.
         // Targets can depend on other targets in this package, and on products in packages which this package depends on.
         .target(name: "Calc", dependencies: ["MathOperations"]),
    ]
    )
    
  23. Save the file and run the build command:
    swift build
  24. Like before you should see both the MathOperationsErrorType module being pulled in. We are ready to run the executable. Navigate to the debug folder which contains the executable. Make sure you are in the main Calc folder when you run this command.
    cd ./build/debug/
  25. You should see an executable file called Calc. Run it.
    ./Calc
  26. If everything went okay then you should see the output on the console.

As you can see it is pretty straightforward to develop Applications written in Swift on Linux.

Adding System Modules

In the previous example we saw how to import our own custom made modules. However, there are some modules provided by the system which offers functionality we may wish to use. For example if we wanted to use the random number generator in our application we would need to use the random() method. This is in the glib module.

  1. Quickly create a package called SystemLibs. This is an executable.
  2. Write the following code in the main.swift.
    #if os(Linux)
    import Glibc
    #else
    import Darwin.C
    #endif
    extension Int
    {
         func toString() -> String
         {
              return "\(self)"
         }
    }
    
    var luckyNumber : Int = Int(random())
    
    var luckyNumberStr : String = luckyNumber.toString()
    
    print("The lucky number is \(luckyNumberStr)")
    
  3. Build the code and run the executable.

Adding system modules is direct and simple. The glibc module contains aspects of the standard library. The condition check is to make sure that we are importing the correct module based on the system that we are developing the application on.

Handling Sub-dependencies

As we saw in the earlier example, sub dependencies are handled automatically. So when our Calc application marked the MathOperations module as a dependency it was pulled during the build. However, the MathOperations module itself marked ErrorTypes module as a dependency. We did not have to modify the Packages.swift file belonging to Calc to indicate that ErrorTypes module also needs to be pulled. This was handled automatically by Swift Package Manager.

Conclusion

In this article we have seen:

  • How to create a library package
  • How to create a library package that depends on another library package
  • How to create an executable that depends on a library package
  • How to import the system Glibc module into our executables.

The Swift Package Manager simplifies many aspects of the development process for us. Many of the things we have discussed also work on macOS. Going forward reusing code and planning for the same should be done keeping Swift Package Manager in mind.

Creating Frameworks for iOS/OS X App Development

Creating Swift Frameworks

Creating Swift Frameworks is easy. The steps below walk you through creating a Swift Framework. The steps below have been performed on Xcode 7.3

  1. Launch Xcode.
  2. Select Create New Project. Or from the menu bar select File > New > Project
  3. From the Template chooser select the Framework & Library  Option under iOS
  4. Select Cocoa Touch Framework1
  5. Give your project a name.
  6. Make sure the language selected is Swift.
  7. Feel free to enter values of your choice for organisation name and organisation identifier.
  8. Save your project. Optionally, if you have a version control repository like Git you may save it there.
  9. In left hand side bar make sure you have selected the Project Navigator.
  10. Within the Project Navigator make sure you have selected the folder named after your project.
  11. Click on File > New > File.
  12. Make sure iOS Source is selected on the left hand side.
  13. Select the file type as Swift.IMG_3525
  14. Write down the code that you want to make available through a framework.
  15. Now this is the key point. Place the keyword public before all the elements that you want to make publicly accessible.Why do we need to do this? To understand this we need to understand the scope of different elements within a typical Swift project. IMG_3521

    Different variables/classes/functions that are declared within a module are accessible freely within the module. Swift files contain code & are themselves found within Swift modules. So a module can mean project or a framework.So, to access the variables/functions/classes from module A in module B, we have to make those elements of module A public in order to access them in module B.

    For more information, do read Apple’s Swift Documentation.

  16. The next steps depend on what your ultimate objective is. If you wish to build a framework for distribution then you need to follow a process that is similar to distributing an app. You need to get the code signing done & prepare the project for distribution.
  17. If however, you plan to release it internally, or even just test it. Then you can follow the steps below.
  18. Firstly, our objective is to make this framework run on both OS X(macOS) as well as iOS.
  19. To do that we will be adding a new target. Click on File > New > Target.
  20. Select OS X & the Frameworks & Libraries from the sidebar.
  21. Select Cocoa Touch Framework
  22. Give your framework a unique name. Something that indicates this framework is for OS X(macOS).
  23. Now, we don’t need to rewrite the code for the Mac. We can simply make the file we have written a member for the OS X Framework Target.
  24. To do that make sure that the right hand side sidebar is visible.
  25. In the left hand side sidebar make sure that you have selected the new Swift file with the code you have written in there.
  26. In the right hand side sidebar select the Document Inspector.
  27. Under Target Membership make sure that both the Targets are checked. The target for iOS should already be checked.IMG_3520
  28. Thats it. If you do not wish to make your code available for both iOS & OS X then skip steps 19 – 27.
  29. The next part is building the framework. We will be building this framework for use internally. We will first build the iOS framework.
  30. From the tool bar, make sure the target selected is for iOS. For the device you can select any device that you wish.
  31. Then click on Product > Build to build the framework. If all goes well then you should get the message Build Succeeded on your screen.
    IMG_3519
  32. To get hold of the framework, expand the product folder from the left hand side sidebar.
  33. Select the Framework you have just built. Note that it should be black in colour. If you have opted to make a framework for OS X, then you should see that framework listed too, it should be in red colour. The red colour indicates that it has not yet been built.IMG_3524
  34. Control-click on the iOS version of the framework and select Show in Finder.
  35. This will take you directly to the folder containing the framework. Copy paste it to the desktop or to any other location to easily access it when required.
  36. Repeat steps 30 – 34 to build the OS X version of the Framework. Make sure that the target selected is OS X.
  37. Once we have done that, we need to test the framework we just created.
  38. Create a dummy iOS Project for testing.
  39. From the left hand side project navigator make sure that the blue project settings file is selected.
  40. Make sure that the Target is selected within the settings screen.
  41. Under the General tab scroll down to the Embedded Binaries section.
  42. Click on the ‘+’ sign to add a framework.IMG_3523
  43. Click on Add other
  44. Navigate to the folder where you saved the Framework and select it.
  45. Click Open
  46. Select Copy Items if needed
  47. The framework should be added to your project.
  48. In the ViewController.swift file import your Framework: import CustomStack
  49. Replace CustomStack with your frameworks name.
  50. Try to write the code which uses the elements you have packaged within the framework.

Creating Mixed Frameworks (Swift & Objective-C)

The process of creating a mixed library is straightforward. Its almost the same as above with some minor differences.

  1. Follow the steps mentioned above to add your Swift Code.
  2. Add your objective-C files to the project.
  3. While adding the files make sure that the checkbox for the targets is selected appropriately. Screen Shot 2016-08-05 at 1.20.37 PM
  4. Write the code that you wish to write in Objective-C. Of course, if you are including prewritten files then you do not need to do this.
  5. To make the Objective-C code accessible in Swift you need to make the following changes:
    1. In the umbrella header of your framework add the line to import the header
      #import "<FrameworkName>/<HeaderName>.h
    2. Modify the access property located within the target membership of the Objective-C header file. IMG_3527
  6. This should make your Objective-C code accessible to the Swift files.
  7. Test the changes by accessing your Objective-C code in your Swift files within the framework.
  8. Test the changes further by embedding your mixed language framework into a project & then try to access both the Swift as well as Objective-C versions of the code in your new project.
  9. To make your Swift code accessible to Objective-C File make the following changes:
    1. Make sure that your Swift code is compatible with Objective-C. There are 2 ways of doing this. One you can make your Swift class inherit from NSObject. The second way is to use the @objc keyword before your class declaration.
    2. In the Objective-C header file add the line to add the bridging header which is auto generated. You do not need to create your own bridging header.
      #import "<FrameworkName>/<FrameworkName>-Swift.h"

      Replace the word FrameworkName with the name of your Framework.

    3. This should allow you to access your Swift code in your Objective-C header file within the same Framework Project.
  10. This way you can make a single framework which contains code written in both Swift & Objective-C.