Deep dive into Swift frameworks

0/5 No votes

Report this app

Description

[ad_1]

Study every part about Swift modules, libraries, packages, closed supply frameworks, command line instruments and extra.

Swift

Primary definitions

To start with you need to have a transparent understanding concerning the primary phrases. In the event you already know what is the distinction between a module, package deal, library or framework you’ll be able to skip this part. Nonetheless in case you nonetheless have some combined emotions about this stuff, please learn forward, you will not remorse it. πŸ˜‰


Bundle

A package deal consists of Swift supply information and a manifest file.

A package deal is a group of Swift supply information. In case you are utilizing Swift Bundle Supervisor you even have to offer a manifest file with the intention to make an actual package deal. If you wish to be taught extra about this software, you need to verify my Swift Bundle Supervisor tutorial.

Instance: that is your package deal:


Sources
    my-source-file.swift
Bundle.swift


You too can try the open sourced switf-corelibs-foundation package deal by Apple, which is used to construct the Basis framework for Swift.



Library

Library is a packaged assortment of object information that program can hyperlink towards.

So a library is a bunch of compiled code. You may create two sorts of libraries:


From a very easy perspective the one distinction between them is the tactic of “integrating” aka. linking them into your challenge. Earlier than I let you know extra about this course of, first we should always discuss object information.


Mach-O file format

To create packages, builders convert supply code to object information. The article information are then packaged into executable code or static libraries.

While you’re compiling the supply information you might be mainly making object information, utilizing the Mach-O (MachObject) file format. These information are the core constructing blocks of your purposes, frameworks, and libraries (each dynamic and static).


Linking libraries

Linking refers back to the creation of a single executable file from a number of object information.

In different phrases:

After the compiler has created all the item information, one other program known as to bundle them into an executable program file. That program known as a linker and the method of bundling them into the executable known as linking.

Linking is simply combining all of your object information into an executable and resolving all of the externals, so the system will have the ability to name all of the features contained in the binary.


Static linking

The supply code of the library is actually going to be copied into the applying’s supply. It will lead to a giant executable, it will take extra time to load, so the binary can have a slower startup time. Oh, did I point out that if you’re making an attempt to hyperlink the identical library greater than as soon as, the method will fail due to duplicated symbols?


This technique has benefits as nicely, for instance the executable will at all times comprise the proper model of the library, and solely these components will likely be copied into the principle software which are actually used, so you do not have to load the entire stuff, however it looks as if dynamic linking goes to be higher in some instances.


Dynamic linking

Dynamic libraries aren’t embedded into the supply of the binary, they’re loaded at runtime. Because of this apps will be smaller and startup time can considerably be sooner due to the light-weight binary information. As a free of charge dynamic libraries will be shared with a number of executables to allow them to have decrease reminiscence footprints. That is why typically they’re being referred as shared libraries.


In fact if the dynamic library isn’t out there – or it is out there however ther model is incompatible – your software will not run or it will crash.Β Then again this may be a bonus, as a result of the writer of the dynamic library can ship fixes and your app can profit from these, with out recompilation.

Luckily system libraries like UIKit are at all times out there, so you do not have to fret an excessive amount of about this subject…


Framework

A framework is a hierarchical listing that encapsulates shared sources, comparable to a dynamic shared library, nib information, picture information, localized strings, header information, and reference documentation in a single package deal.

So let’s make this straightforward: frameworks are static or dynamic libraries packed right into a bundle with some additional belongings, meta description for versioning and extra. UIKit is a framework which wants picture belongings to show among the UI parts, additionally it has a model description, by the best way the model of UIKit is identical because the model of iOS.


Module

Swift organizes code into modules. Every module specifies a namespace and enforces entry controls on which components of that code can be utilized outdoors of the module.

With the import key phrase you might be actually importing exterior modules into your sorce. In Swift you might be at all times utilizing frameworks as modules, however let’s return in time for some time to grasp why we wanted modules in any respect.


import UIKit
import my-awesome-module


Earlier than modules you needed to import framework headers instantly into your code and also you additionally needed to hyperlink manually the framework’s binary inside Xcode. The #import macro actually copy-pasted the entire resolved dependency construction into your code, and the compiler did the work on that massive supply file.

It was a fragile system, issues might go mistaken with macro definitions, you might simply break different frameworks. That was the explanation for outlining prefixed uppercased very lengthy macro names like: NS_MYSUPERLONGMACRONAME… πŸ˜’

There was an different subject: the copy-pasing resulted in non-scalable compile occasions. So as to remedy this, precompiled header (PCH) information have been born, however that was solely a partial resolution, as a result of they polluted the namespace ( in case you import UIKit in a PCH file it will get out there in in all places), and noone actually maintained them.


Modules and module maps

The holy grail was already there, with the assistance of module maps (defining what sort of headers are a part of a module and what is the binary that has the implementation) we have encapsulated modular frameworks. πŸŽ‰ They’re individually compiled as soon as, the header information are defining the interface (API), and the (robotically) linked dylib file comprises the implementation. Hurray, no must parse framework headers throughout compilation time (scalability), so native macro definitions will not break something. Modules can comprise submodules (inheritance), and you do not have to hyperlink them explicitly inside your (Xcode) challenge, as a result of the .modulemap file has all the data that the construct system wants.

Finish of the story, now what occurs beneath the hood, while you import Basis or import UIKit.



Command line instruments

Now that the logic behind the entire dynamic modular framework system, we should always begin inspecting the instruments that make this infrastructure potential.

All the time learn the person pages, aka. RTFM! In the event you do not prefer to learn that a lot, you’ll be able to obtain the instance challenge from gitlab and open the makefiles for the essence. There will likely be 3 important classes: C, Swift and Xcode challenge examples.


clang

the Clang C, C++, and Goal-C compiler

Clang is a compiler frontend for C languages (C, C++, Goal-C). You probably have ever tried to compiled C code with gcc throughout your college years, you’ll be able to think about that clang is kind of the identical as gcc, however these days it could actually do much more.

clang -c important.c -o important.o #compiles a C supply file

LLVM: compiler backend system, which might compile and optimize the intermediate illustration (IR) code generated by clang or the Swift compiler for instance. It is language unbiased, and it could actually achieve this many issues that would match right into a guide, however for now to illustrate that LLVM is making the ultimate machine code in your executable.


swiftc

The Swift compiler, there is no such thing as a guide entry for this factor, however don’t be concerned, simply fireplace up swiftc -h and see what can provide to you.

swiftc important.swift #compiles a Swift supply file

As you’ll be able to see this software is what truly can compile the Swift supply information into Mach-O’s or ultimate executables. There’s a quick instance within the connected repository, you need to verify on that if you would like to be taught extra concerning the Swift compiler.


ar

The ar utility creates and maintains teams of information mixed into an archive. As soon as an archive has been created, new information will be added and present information will be extracted, deleted, or changed.

So, in a nutshell you’ll be able to zip Mach-O information into one file.

ar -rcs myLibrary.a *.o

With the assistance of ar you have been capable of create static library information, however these days libtool have the identical performance and much more.


ranlib

ranlib generates an index to the contents of an archive and shops it within the archive. The index lists every image outlined by a member of an archive that may be a relocatable object file.

Ranlib can create an index file contained in the static lib, so issues are going to be sooner while you’re about to make use of your library.

ranlib myLibrary.a

So ranlib & ar are instruments for sustaining static libraries, normally ar takes care of the indexing, and you do not have to run ranlib anymore. Nonetheless there’s a higher possibility for managing static (and dynamic) libraries that you need to be taught…


libtool

create libraries

With libtool you’ll be able to create dynamically linked libraries, or statically linked (archive) libraries. This software with the -static possibility is meant to switch ar & ranlib.

libtool -static *.o -o myLibrary.a

These days libtool is the principle possibility for build up library information, you need to positively be taught this software in case you’re into the subject. You may verify the instance challenge’s makefile for more information, or as normally you’ll be able to learn the manuals (man libtool). πŸ˜‰


ld

The ld command combines a number of object information and libraries, resolves references, and produces an ouput file. ld can produce a ultimate linked picture (executable, dylib, or bundle).

Let’s make it easy: that is the linker software.

ld important.o -lSystem -LmyLibLocation -lmyLibrary -o MyApp

It will probably hyperlink a number of information right into a single entity, so from the Mach-O’s you’ll make an executable binary. Linking is critical, as a result of the system must resolve the addresses of every technique from the linked libraries. In different phrases, the executable will have the ability to run and your whole features will likely be out there for calling. πŸ“±


nm

show identify record (image desk)

With nm you’ll be able to see what symbols are inside a file.

nm myLibrary.a




As you’ll be able to see from the output, some sort of reminiscence addresses are related for a few of symbols. Those who have addresses are literally resolved, all of the others are coming from different libraries (they are not resolved but). So which means that they’re going to be resolved at runtime. The opposite possibility is that it’s important to hyperlink them. πŸ˜…


otool

object file displaying software

With otool you’ll be able to look at the contents of Mach-O information or libraries.

otool -L myLibrary.a
otool -tV myLibrary.a

For instance you’ll be able to record the linked libraries, or see the disassembled textual content contents of the file. It is a actually useful software in case you’re acquainted with the Mach-O file format, additionally good one to make use of for reverse-engineer an present software.


lipo

create or function on common information

With the assistance of the lipo software you’ll be able to create common (multi-architecture) information. Normally this software is used for creating common frameworks.

lipo -create -output myFramework.framework units.framework simulator.framework

Think about the next situation: you construct your sources each for arm7 and i386. On an actual gadget you’d must ship the arm7 model, however for the iOS simulator you will want the i386 one. With the assistance of lipo you’ll be able to mix these architectures into one, and ship that framework, so the top consumer haven’t got to fret about this subject anymore.

Learn on the article to see the way it’s achieved. πŸ‘‡



Xcode associated instruments

These instruments will be invoked from the command line as nicely, however they are much extra associated to Xcode than those earlier than. Let’s have a fast walk-through.


xcode-select

Manages the energetic developer listing for Xcode and BSD instruments. You probably have a number of variations of Xcode in your machine this software can simply swap between the developer instruments supplied by the induvidual variations.

xcode-select --switch path/to/Xcode.app


xcrun

Run or find growth instruments and properties. With xcrun you’ll be able to mainly run something which you can handle from Xcode.

xcrun simctl record #record of simulators


codesign

Create and manipulate code signatures

It will probably signal your software with the correct signature. Normally this factor failed while you have been making an attempt to signal your app earlier than computerized signing was launched.

codesign -s "Your Firm, Inc." /path/to/MyApp.app
    codesign -v /path/to/MyApp.app


xcodebuild

construct Xcode tasks and workspaces

That is it. It’s going to parse the Xcode challenge or workspace file and executes the suitable buid instructions primarily based on it.

xcodebuild -project Instance.xcodeproj -target Instance
    xcodebuild -list
    xcodebuild -showsdks



Tips on how to make a closed supply common FATtened (multi-architecture) Swift framework for iOS?

So we’re right here, the entire article was made for studying the logic behind this tutorial.

To start with, I do not need to reinvent the wheel, as a result of there’s a superbly written article that you need to learn. Nonetheless, I might like to provide you some extra detailed clarification and slightly modification for the scripts.


Skinny vs. fats frameworks

Skinny frameworks comprises compiled code for just one structure. Fats frameworks however are containing “slices” for a number of architectures. Architectures are mainly referred as slices, so for instance the i386 or arm7 slice.

This implies, in case you compile a framework just for i386 and x86_64 architectures, it’s going to work solely on the simulator and horribly fail on actual units. So if you wish to construct a very common framework, it’s important to compile for ALL the present architectures.


Constructing a fats framework

I’ve a excellent news for you. You simply want one little construct part script and an mixture goal with the intention to construct a multi-architecture framework. Right here it’s, shamelessly ripped off from the supply article, with some additional adjustments… 😁

set -e
BUILD_PATH="${SRCROOT}/construct"
DEPLOYMENT_PATH="${SRCROOT}"
TARGET_NAME="Console-iOS"
FRAMEWORK_NAME="Console"
FRAMEWORK="${FRAMEWORK_NAME}.framework"
FRAMEWORK_PATH="${DEPLOYMENT_PATH}/${FRAMEWORK}"


if [ -d "${BUILD_PATH}" ]; then
    rm -rf "${BUILD_PATH}"
fi


xcodebuild -target "${TARGET_NAME}" -configuration Launch 
    -arch arm64 -arch armv7 -arch armv7s 
    only_active_arch=no defines_module=sure -sdk "iphoneos"

xcodebuild -target "${TARGET_NAME}" -configuration Launch 
    -arch x86_64 -arch i386 
    only_active_arch=no defines_module=sure -sdk "iphonesimulator"


if [ -d "${FRAMEWORK_PATH}" ]; then
    rm -rf "${FRAMEWORK_PATH}"
fi


cp -r "${BUILD_PATH}/Launch-iphoneos/${FRAMEWORK}" "${FRAMEWORK_PATH}"


lipo -create -output "${FRAMEWORK_PATH}/${FRAMEWORK_NAME}" 
    "${BUILD_PATH}/Launch-iphoneos/${FRAMEWORK}/${FRAMEWORK_NAME}" 
    "${BUILD_PATH}/Launch-iphonesimulator/${FRAMEWORK}/${FRAMEWORK_NAME}"


cp -r "${BUILD_PATH}/Launch-iphonesimulator/${FRAMEWORK}/Modules/${FRAMEWORK_NAME}.swiftmodule/" 
    "${FRAMEWORK_PATH}/Modules/${FRAMEWORK_NAME}.swiftmodule"


if [ -d "${BUILD_PATH}" ]; then
    rm -rf "${BUILD_PATH}"
fi


You may at all times look at the created framework with the lipo software.

lipo -info Console.framework/Console


Utilization

You simply must embedd your model new framework into the challenge that you just’d like to make use of and set some paths. That is it. Nearly…



Transport to the App Retailer

There is just one subject with fats architectures. They comprise slices for the simulator as nicely. If you wish to submit your app to the app retailer, it’s important to minimize off the simulator associated codebase from the framework. The rationale behind that is that no precise actual gadget requires this chunk of code, so why submit it, proper?


APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}"


discover "$APP_PATH" -name '*.framework' -type d | whereas learn -r FRAMEWORK
do
    FRAMEWORK_EXECUTABLE_NAME=$(defaults learn "$FRAMEWORK/Data.plist" CFBundleExecutable)
    FRAMEWORK_EXECUTABLE_PATH="$FRAMEWORK/$FRAMEWORK_EXECUTABLE_NAME"
    echo "Executable is $FRAMEWORK_EXECUTABLE_PATH"

    EXTRACTED_ARCHS=()

    for ARCH in $ARCHS
    do
        echo "Extracting $ARCH from $FRAMEWORK_EXECUTABLE_NAME"
        lipo -extract "$ARCH" "$FRAMEWORK_EXECUTABLE_PATH" -o "$FRAMEWORK_EXECUTABLE_PATH-$ARCH"
        EXTRACTED_ARCHS+=("$FRAMEWORK_EXECUTABLE_PATH-$ARCH")
    achieved

    echo "Merging extracted architectures: ${ARCHS}"
    lipo -o "$FRAMEWORK_EXECUTABLE_PATH-merged" -create "${EXTRACTED_ARCHS[@]}"
    rm "${EXTRACTED_ARCHS[@]}"

    echo "Changing unique executable with thinned model"
    rm "$FRAMEWORK_EXECUTABLE_PATH"
    mv "$FRAMEWORK_EXECUTABLE_PATH-merged" "$FRAMEWORK_EXECUTABLE_PATH"

achieved

This little script will take away all of the pointless slices from the framework, so you’ll submit your app by way of iTunesConnect, with none points. (ha-ha-ha. πŸ˜…)

You need to add this final script to your software’s construct phases.



Closing ideas

If you wish to get faimiliar with the instruments behind the scenes, this text will assist you to with the fundamentals. I could not discover one thing like this however I wished to dig deeper into the subject, so I made one. I hope you loved it, be happy to submit a gitlab subject or contact me in case you discover something mistaken or you might have an recommendation to enhance the article. πŸ˜‰



[ad_2]

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.