如何不使用 Xcode 學習 Swift

Swift 自從於 2015 年底自 Apple inc 開源之後,有許多人想學習卻因為無法找到 Xcode 之外的開發環境,而有不少的挫責,最近因為 Swift for tensorflow 的發展,有不少人想知道 Swift 究竟有何魔力,今天介紹如何在不用 Xcode (甚至不在macOS環境) 下,編譯並學習 Swift 的語言特性!
確認 Swift Compiler
在開始之前,你必須自己研究出如何在自己的編譯系統安裝 Swift,我建議你學習最新版本的 Swift,就如同上面解釋的,Swift 是個開源的語言,有許多更新是集成廣大開發者的智慧,像是 2019 年 Swift 5.1 的 Property Wrapper,就改變了許多程式設計的面向。若是想要確認自己的 Swift 版本,可以使用一下指令:
$ swift --version
Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15)
Target: x86_64-apple-darwin19.3.0
編譯 .swift 程式檔就像 clang (gcc) 一樣簡單
在 C 語言中,我們可以使用 gcc 來編譯 .c
的檔案,如果今天只有一個檔案,我們仍需要 int main ()
的函式來充當程式的進入點(與 Python 同理),而在 swiftc
這個 Swift compiler 中,若是以畫單一檔案的方式的話,並不需要 main function, 因此我們可以使用下面的方式:
$ swiftc AnyFileName.swift -o SingleFile.app
$ ./SingleFile.app
swiftc a single file just like Xcode playground
然而大部分時間我們並不會把所有的程式碼寫於同一個檔案,因此需要 main.swift
來告訴 compiler 程式的進入點在何處。
$ swiftc main.swift Calculator.swift hello.swift -o MultipleFile.app
$ ./MultipleFile.app
1 + 1 = 2
hello, again
以上,你就可以透過 docs.Swift.org 上的教學,不用任何 Xcode 來認識 Swift。 demo on GitHub: https://github.com/ytyubox/SwiftWithoutXcode
[進階] 透過 Swift Package 來使用 Open-Source Library
在學習完語法之後,我們會想開始建立自己的程式,但是不同於 C,Swift 有自主的套件管理方案,Swift Package Maneger(SPM),當使用 Swift Package 之後,Swift 將 swiftc 的指令做了大幅度封裝。在介紹之前,如果你還不會 Swift 語法,我建議你將這個段落保留起來;如果你沒使用過 Swift Package, 可以參考我的另一篇文章: 使用 Swift Package Manager 建立 Command line tool
接下來要做什麼?
如果你在學習完 Swift 的語言之後,想試著製作一個應用程式,我建議你可以考慮一下幾個方面:
- 使用 SPM 建立 Command line tool,簡化 Linux/Unix 流程 我有使用 SPM 建立一個 Git 的 Pre-Commit 流程,主要功能是檢查 GitSubmodule 的自動化工具,請參考 ytyubox/check-submodule-all-commit
- 使用 Swift for Tensorflow 處理機器學習
- 製作一個 Apple OS 的 APP (iOS、macOS)
- 利用 Server Side Swift 建立網頁或是 API,如 Vapor
如果你有製作任何讓你得到成就感的程式,歡迎你留言分享!