Swift Xcode

Swift Package Manager.2

In the first post, we saw how to create a package, here we’ll see how to use our newly created package without our project.

Add code to your package

First, open your xcode project, and create some code.

  • Get rid of the automatically generated code : FluentCoding_MediaControl.swift
  • Create a new swift file: MediaControlManager.swift
import Foundation
public class MediaControlManager {
    public init() {} 
    public func sayHi() -> String {

⚠️ Please note that we need to annotate classes or struct as public (or open), so they can be visible outside of the package. If you don’t specify, they will stay only accessible within your package and not at the client code.

  • Remove the automatically generated test: FluentCoding_MediaControlTests.swift
  • Create a new Swift file: MediaControlManagerTests.swift
import Foundation
import XCTest
@testable import FluentCoding_MediaControl
class MediaControlManagerTests: XCTestCase {
    func test_SayHi() {
        let sut = MediaControlManager()
        XCTAssertEqual(sut.sayHi(), "Hi")
  • You can compile and run tests within Xcode to make sure everything works fine.
  • Commit and push to the main repo.

Import your package in your client app

  • Create a new iOS project or use an existing one as you wish.
  • Select File > Swift Packages > Add Package Dependency
  • Select in theory, your package should be in the list. If not, you can specify the git Url of it.
  • XCode may ask you to create a Personal Access token. You need to follow the step of your favourite git repo (the link will appear in the UI) For example in Github, it will be under Settings > Developer Settings > Personal Access Tokens.
  • Next, select the version of the package you want to use. For now, we have just pushed everything to the main branch, so it’s easy.
  • Press Next. Xcode will download the package within your project. Select your project target, so the package will be automatically linked there.
  • Press Finish

That’s it, the package should be successfully imported into your project and ready to be used 👍

Using our package in the client code

import Foundation
import FluentCoding_MediaControl
class ThisIsATestCodeToUseMyPackage {
    init() {
        let manager = MediaControlManager()

Of course this code here doesn’t make any sense, but we can see using the keyword import, that we can bring our package code into our client swift code. As we mark the MediaControlManager as public, this is possible to instantiate it.

Updating package code

  • Each time you are going to add new code into your package, you will need to update on the client code. (like if you would do a pod update or pos install with cocoa pod)
  • To do so, go in File > Swift Packages > Update to Latest Package version

Thank you for reading until here…  👊 Have a good week end…  🍺