Swift Package Manager Tutorial

Source: Internet
Author: User
Tags locale pack


Original: An Introduction to the Swift package Manager
Mikael Konutgan
Translator: Kmyhy


The official release of the SWIFT Package Manager, released with SWIFT3.0, is a new way to build swift libraries and apps that run on MacOS and Linux. It can help you manage dependencies, allowing you to easily build, test, and run your Swift code.



Swift Package Manager helps to greatly improve the swift ecosystem, making swift easier to use and deploy to platforms without Xcode, such as Linux. The Swift Package Manager also solves the problem of "relying on hell" when using multiple interdependent libraries.



It is important that, because of Swift 3, the SWIFT Package Manager can only be compiled on the host platform. In other words, you can't compile, use packages on IOS, WatchOS, and TvOS.



Let's get started!


Begin


Before you begin, confirm that you have installed Swift 3.0 or higher. Swift 3 is built in xcode8+, so if you have installed Xcode8 or above, you can start this tutorial. Of course you don't need to use Xcode to complete this tutorial, you can download and install Swift 3 directly from swift.org.



Open the Terminal window and enter the SWIFT package. You will see an introduction to this command. You will use these several commands:


    1. Swift Package init, creating new packages
    2. Swift Package update, updating the dependency of a packet
    3. Swift package Generate-xcodeproj, creating Xcode projects for packages


To learn Swift Package Manager, we will write a command-line app that prints out flag characters for all countries in a single library. First we will create an executable package. This package is also the command-line app. The Swift web app also falls into this category.



Create an executable package named Flag with the following command:


mkdir Flagcd Flagswift package init --type executable


When running the SWIFT Package init command line, it is critical to switch to the flag directory, because flag will be used as the packet name. You will see that some files and folders are displayed in the output and they are automatically generated. Now to familiarize yourself with the project structure:



Https://koenig-media.raywenderlich.com/uploads/2016/12/Flag-%E2%94%9C%E2%94%80%E2%94%80-Package.swi_.png ' width = '/> '


    1. The Package.swift contains the description information for the package and also contains the package dependencies.
    2. Sources/, as the name suggests, is used to store your Swift source files. A main.swift file is generated inside. This is the entry for the application. Now, it will only print Hello world.
    3. tests/, which contains unit tests, you can write these tests with Xctext. You'll write the test code later.


Back to the terminal window, run:


swift build


This compiles the package and creates an executable Flag in the. build/debug/file. To run this app, just:


.build/debug/Flag


You'll see hello,world! on the screen.



Congratulations to you! You created and compiled your first Swift package!


Create a library


To really be able to generate state-owned State enterprise characters, we need to write a library called Atlas. Then call the library in your Flag app.



Cut to a directory other than the Flag package and create a library from the terminal command:


cd ..mkdir Atlascd Atlasswift package init --type library


Package Manager creates several files and folders.



Https://koenig-media.raywenderlich.com/uploads/2017/01/atlas-library-structure.png ' width= '/>



This time, Main.swift will be replaced by Atlas.swift. This file and the files in the sources/directory will be imported into this library. In fact, the difference between a library and an executable package is that there is no main.swift.



This time we need to use a test. Run the test with Swift test. The Swift Package Manager compiles the library and runs the tests.


Note: You will see the Linuxmain.swift file in the tests/directory, and there is a alltests attribute in the Atlastests test case class. Both are necessary for running the Xctest test on Linux. Linux does not have a o-c runtime, and the O-C runtime automatically finds the method that starts with test and runs it. Whenever you add a test method, you need to modify the Alltests property, and whenever you add a new test case class, you need to modify the Linuxmain.swift.


Open Atlas.swift Modify content to:


 
 
public struct Country {
  public let code: String

  public init(code: String) {
    self.code = code.uppercased()
  }

  public var emojiFlag: String {
    return "\u{1f1f5}\u{1f1f7}"
  }
}


Here we implement a country structure, which is initialized with an ISO country code. The Emojiflag property returns the corresponding flag character according to the country code. Now you need to write the test.



Note that each method and property is marked as public, so that every member of it is courseware for the code that uses the library:]



Open the Atlastests.swift and edit the contents as follows:


 
import XCTest
@testable import Atlas

class AtlasTests: XCTestCase {
  func testAustria() {
    XCTAssertEqual(Country(code: "AT").emojiFlag, "\u{1f1e6}\u{1f1f9}")
  }

  func testTurkey() {
    XCTAssertEqual(Country(code: "TR").emojiFlag, "\u{1f1f9}\u{1f1f7}")
  }

  func testUnitedStates() {
    XCTAssertEqual(Country(code: "US").emojiFlag, "\u{1f1fa}\u{1f1f8}")
  }
}

extension AtlasTests {
  static var allTests : [(String, (AtlasTests) -> () throws -> Void)] {
    return [
      ("testAustria", testAustria),
      ("testTurkey", testTurkey),
      ("testUnitedStates", testUnitedStates)
    ]
  }
}


3 tests are implemented here. We created 3 different nationalities and then asserted whether they had the correct emoji flag characters.



To run the test:


swift test


You will see that 3 tests were run, but all failed. It means we have a lot of things to do:]



Now that we have failed the test, we have to let them pass the test.



The emoji flag works very simply: pass in a country code, such as at, and then convert each character to a locale indicator. For example?? And??. Then combine the two together and you'll get the emoji flag!



Https://koenig-media.raywenderlich.com/uploads/2017/01/ragecomic_flags.png ' width= '/>



Go back to Atlas.swift to add a method to the country structure:


func regionalIndicatorSymbol(unicodeScalar: UnicodeScalar) -> UnicodeScalar? {
  let uppercaseA = UnicodeScalar("A")!
  let regionalIndicatorSymbolA = UnicodeScalar("\u{1f1e6}")!
  let distance = unicodeScalar.value - uppercaseA.value
  return UnicodeScalar(regionalIndicatorSymbolA.value + distance)
}


Here, we take advantage of the letter and area indicator flags in the Unicode table where the values are sequential in the principle. For example A is 65,b is 66, and?? Is 127462,?? Is 127463. If the character P is converted to a zone indicator, it is necessary to calculate the difference in the value of A to P, then the?? Plus this difference will get??。



This is the hardest part. After writing this method, the rest of the matter is simple. Modify the Emojiflag property definition to:


 
public var emojiFlag: String {
  return code.unicodeScalars.map { 
  String(regionalIndicatorSymbol(unicodeScalar: $0)!) } .joined()
}


We put each letter of the country code into an array, then we convert each letter to the corresponding area indicator, and then we connect them together. That's got the flag!



Running the test, 3 tests were passed.



Next, commit the code to GIT and tag a number. Since this is our first version, we can mark the version as 1.0.0.



Create a Git repository and mark the version by executing the following command:


 
 
git init
git add .
git commit -m "Initial commit"
git tag 1.0.0
Create an executable package


Now that you have the flag library ready, we can add it as a dependency on the flag executable package.



Go back to the Flag directory and open the Package.swift file. It is now like this:


 
import PackageDescription

let package = Package(
  name: "Flag"
)


Each Swift package has a similar packagedescription. The most important parameter is the dependencies parameter.



Modify the package description to this:


 
let package = Package(
  name: "Flag",
  dependencies: [
    .Package(url: "../Atlas", "1.0.0")
  ]
)


Here, we declare that the Flag package has a dependency, and this dependent URL is: /atlas, version is 1.0.0.



The version number should be the version number on which the term is defined. Simply put, it is similar to MAJOR. MINOR. A version number such as PATCH. The MAJOR version represents a non-backward-compatible modification, and the MINOR version represents a backward-compatible modification, and a PATCH version is a bug fix. For a semantic version, details can be found here.



In most cases, you just want the new version to be modified on bug fixes and minor version improvements. Fortunately, the Swift Package Manager allows us to do so. Modify the package description to:


 
let package = Package(
  name: "Flag",
  dependencies: [
    .Package(url: "../Atlas", majorVersion: 1)
  ]
)


The Package Manager provides the version you want to control precisely when you update the library. Please refer to here.



To compile the package:


swift build


The Swift Package Manager will crawl, compile, and connect the library to your executable package. Now the folder structure will look like this:



Https://koenig-media.raywenderlich.com/uploads/2017/01/flag-structure.png ' width= '/>



You will see that the Swift Package Manager has carefully installed the 1.0.0 version into the project according to your requirements. Open a Main.swift file and edit the following:


 
import Atlas

let arguments = CommandLine.arguments

if arguments.count != 2 {
  print("USAGE: flag [iso country code]")
} else {
  let code = arguments[1]
  let country = Atlas.Country(code: code)
  print(country.emojiFlag)
}


Here, we import the Atlas library and print out the corresponding flag emoji according to the first parameter of the command line parameter. If a parameter is missing, we print the command help.



Compile and run the app:


swift build./.build/debug/Flag US


You see the American flag in the terminal window!



When you and your app are having a good time, we should pack it. Finally compile the app, this time need to add the release optimization parameters:


swift build --configuration release


Now you can run your release app like this:


./.build/release/Flag PR


You can pack your./.build/release/flag files and then share them with your friends, family, or other people:]


Build a Xcode project with Package Manager


The old command line and text editor are cool, but you're probably an IOS or MacOS programmer, and you're using Xcode. Don't worry-most work with Xcode can do very well.



Go back to the Atlas package and build a Xcode project:


cd ../Atlasswift package generate-xcodeproj


This will generate a atlas.xcodeproj file. You can use Xcode to open the project and compile the package and run tests like any other Xcode project.



Https://koenig-media.raywenderlich.com/uploads/2017/01/xcode-650x357.png ' width= '/>



The same method can be used on the Flag packet. Execute the SWIFT Package generate-xcodeproj command below the Flag folder to generate the Flag.xcodeproj.


cd ../Flagswift package generate-xcodeproj


Open the project with Xcode and confirm that the Flag executable target is selected, which displays the icon for a small terminal window. Now you can also compile and run the package.



In order to specify the parameters of the executable command, go to Product\scheme\edit Scheme ... window, select Run\arguments, add a parameter such as US in Arguments Passed on Launch:



Https://koenig-media.raywenderlich.com/uploads/2017/01/Flag_xcodeproj-650x361.png ' width= '/>



Note that Xcode cannot add and compile dependencies, so you cannot completely leave the command line.


End


You can download the completed Swift Package Manager project from here.



You can also refer to the SWIFT website section on package Manager.



For the latest documentation on package description options, please refer to GitHub.



You can refer to the mailing list of the Swift Evolution roadmap for the Package Manager change direction for Swift 4.



You can also refer to the IBM Swift package Catalog, which can help you find new packages that can be used in your project.



Before Swift Package Manager can support non-host platforms, you still have to use Cocoapods or Carthage to build IOS, WatchOS, and TvOS apps.



To stay in today's job, you can push your library to GitHub and then use its remote dependencies in Atlas. Tip: Simply modify the URL parameter of the dependency to the GitHub URL.



Try adding new features, such as listing the names and flags of all countries when no parameters are provided. Tip: You will need to use the locale.isoregioncodes.



Implement your new feature in the Atlas library, and then create a new version, such as 1.1.0, and then use this new version in Flag. Verify that you have used the new version in the package description and then upgrade the dependency to the new version through the Swift Package Manager.



Publish your answer to the following message, Wish you happy!



Swift Package Manager Tutorial


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.