アップルが開発しているプログラミング言語である
アップルさん家のSwift
「アップルさん家の」
このオープンソース版Swiftの最大の特徴は
詳しいことは
また、
今のところLinux版のSwiftは、
Swiftのインストール方法
UbuntuにSwiftをインストールする方法はいくつか存在します。
- バイナリアーカイブをダウンロードする
- ソースコードからビルドする
- Dockerを使う
- Ubuntu Makeを使う
(12月7日時点では未実装)
サポートプラットフォームは、
バイナリファイルをインストールする
Swiftを試す上で、
バイナリファイルは
まずはバイナリアーカイブとその署名ファイルのダウンロードです。ファイル名の日付部分は将来的に変わるかもしれませんので、
$ wget https://swift.org/builds/ubuntu1404/swift-2.2-SNAPSHOT-2015-12-01-b/swift-2.2-SNAPSHOT-2015-12-01-b-ubuntu14.04.tar.gz $ wget https://swift.org/builds/ubuntu1404/swift-2.2-SNAPSHOT-2015-12-01-b/swift-2.2-SNAPSHOT-2015-12-01-b-ubuntu14.04.tar.gz.sig
手順ではこのあと署名ファイルを使って、
$ gpg --verify swift-2.2-SNAPSHOT-2015-12-01-b-ubuntu14.04.tar.gz.sig (中略) gpg: Signature made 2015年12月03日 06時23分10秒 JST using RSA key ID 412B37AD gpg: Can't check signature: public key not found
この鍵ID
$ gpg --keyserver hkp://pool.sks-keyservers.net --search-keys 412B37AD gpg: searching for "412B37AD" from hkp server pool.sks-keyservers.net (1) Swift Automatic Signing Key #1 <[email protected]> 4096 bit RSA key 412B37AD, created: 2015-11-19, expires: 2017-11-18 Keys 1-1 of 1 for "412B37AD". Enter number(s), N)ext, or Q)uit > q
上記のようにこの鍵IDは
今回はこのままインポートするわけではないので、
$ gpg --keyserver hkp://pool.sks-keyservers.net \ --recv-keys \ '7463 A81A 4B2E EA1B 551F FBCF D441 C977 412B 37AD' \ '1BE1 E29A 084C B305 F397 D62A 9F59 7F4D 21A5 6D5F' gpg: requesting key 412B37AD from hkp server pool.sks-keyservers.net gpg: requesting key 21A56D5F from hkp server pool.sks-keyservers.net gpg: /home/ubuntu/.gnupg/trustdb.gpg: trustdb created gpg: key 412B37AD: public key "Swift Automatic Signing Key #1 <[email protected]>" imported gpg: key 21A56D5F: public key "Swift 2.2 Release Signing Key <[email protected]>" imported gpg: Total number processed: 2 gpg: imported: 2 (RSA: 2)
先ほどの
取り込まれた鍵のリストを表示してみましょう。
$ gpg --list-keys /home/ubuntu/.gnupg/pubring.gpg ------------------------------- pub 4096R/412B37AD 2015-11-19 [expires: 2017-11-18] uid Swift Automatic Signing Key #1 <[email protected]> pub 4096R/21A56D5F 2015-11-28 [expires: 2017-11-27] uid Swift 2.2 Release Signing Key <[email protected]>
取り込んだ鍵を使って、
$ gpg --verify swift-2.2-SNAPSHOT-2015-12-01-b-ubuntu14.04.tar.gz.sig gpg: Signature made 2015年12月03日 06時23分10秒 JST using RSA key ID 412B37AD gpg: Good signature from "Swift Automatic Signing Key #1 <[email protected]>" gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: 7463 A81A 4B2E EA1B 551F FBCF D441 C977 412B 37AD
「Good signature」
ちなみに
$ gpg --delete-keys 412B37AD (中略) pub 4096R/412B37AD 2015-11-19 Swift Automatic Signing Key #1 <[email protected]> Delete this key from the keyring? (y/N) y $ gpg --list-keys /home/ubuntu/.gnupg/pubring.gpg ------------------------------- pub 4096R/21A56D5F 2015-11-28 [expires: 2017-11-27] uid Swift 2.2 Release Signing Key <[email protected]>
さて、
$ tar xvf swift-2.2-SNAPSHOT-2015-12-01-b-ubuntu14.04.tar.gz $ mv swift-2.2-SNAPSHOT-2015-12-01-b-ubuntu14.04 swift
展開したディレクトリの
$ export PATH=`pwd`/swift/usr/bin:${PATH} $ which swift /home/ubuntu/swift/usr/bin/swift $ swift --version Swift version 2.2-dev (LLVM 46be9ff861, Clang 4deb154edc, Swift 778f82939c) Target: x86_64-unknown-linux-gnu
上記のようにバージョンが表示されればインストール完了です。
ちなみにswiftcコマンドを使う場合、
$ sudo apt-get install clang build-essential
特に後者をインストールしていない場合、
$ swiftc foo.swift clang: error: unable to execute command: Executable "ld" doesn't exist! clang: error: linker command failed with exit code 1 (use -v to see invocation) <unknown>:0: error: link command failed with exit code 1 (use -v to see invocation)
ソースコードからビルドする
ソースコードが公開されているので、
ビルド手順はGitHub上のプロジェクトのREADMEに記載されています。けっこう大きなプロジェクトですので、
またこの方法では、
最初にビルドに必要なパッケージをインストールします。ビルドシステムとしてcmakeとninjaを使っています。
$ sudo apt-get install git cmake ninja-build clang uuid-dev \ libicu-dev icu-devtools libbsd-dev libedit-dev libxml2-dev \ libsqlite3-dev swig libpython-dev libncurses5-dev pkg-config
Ubuntu 14.
$ sudo apt-get install clang-3.6 $ sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.6 100 $ sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.6 100
次に必要なソースコードをGitHubからcloneしていきます。今回は使わないリポジトリもcloneしています。
$ mkdir swift && cd $_ $ git clone https://github.com/apple/swift.git swift $ git clone https://github.com/apple/swift-llvm.git llvm $ git clone https://github.com/apple/swift-clang.git clang $ git clone https://github.com/apple/swift-lldb.git lldb $ git clone https://github.com/apple/swift-cmark.git cmark $ git clone https://github.com/apple/swift-llbuild.git llbuild $ git clone https://github.com/apple/swift-package-manager.git swiftpm $ git clone https://github.com/apple/swift-corelibs-xctest.git $ git clone https://github.com/apple/swift-corelibs-foundation.git
ちなみにバイナリ版のリビジョンには
ビルドスクリプトは
$ ./swift/utils/build-script -h
今回はリリースビルド
$ time ./swift/utils/build-script -R -t --lldb (中略) Testing Time: 922.64s Expected Passes : 1667 Expected Failures : 92 Unsupported Tests : 573 -- check-swift-linux-x86_64 finished -- --- Finished tests for swift --- real 299m19.298s user 232m14.336s sys 19m27.081s
ビルドしたバイナリは
$ export PATH=`pwd`/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin:${PATH} $ which swift /home/ubuntu/swift/build/Ninja-ReleaseAssert/swift-linux-x86_64/bin $ swift --version Swift version 2.2-dev (LLVM 46be9ff861, Clang 4deb154edc, Swift 7245c0729b) Target: x86_64-unknown-linux-gnu
ちなみに
LLVM ERROR: Compiler-internal integrated REPL unimplemented for this platform; use the LLDB-enhanced REPL instead.
これはswiftコマンド組み込みの対話インターフェースであるREPLが、
$ export PATH=`pwd`/build/Ninja-ReleaseAssert/lldb-linux-x86_64/bin:${PATH} $ lldb --repl lldb: /home/ubuntu/swift/swift/lib/AST/Module.cpp:1477: void performAutoImport(swift::SourceFile &, SourceFile::ImplicitModuleImportKind): Assertion `M && "unable to auto-import module"' failed. Aborted (core dumped)
swiftのコンパイラそのものは動きます。REPLを使いたい場合のみ、
Dockerを使う
Swiftインストール済みのDockerイメージも早速公開されています。これはPhusion Baseimageをベースに、
まずはDockerのインストールからです。Ubuntu 14.
$ sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 \ --recv-keys 58118E89F3A912897C070ADBF76221572C52609D $ echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" | \ sudo tee -a /etc/apt/sources.list.d/docker.list $ sudo apt-get update $ sudo apt-get install docker-engine $ sudo service docker status docker start/running, process 648
インストール後、
ちなみにdocker-engineパッケージは、
それではDockerイメージを取得してコンテナを起動しましょう。
$ sudo docker pull swiftdocker/swift $ sudo docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE swiftdocker/swift latest 8d736fc221b8 20 hours ago 873.8 MB $ sudo docker run -i -t --privileged=true --name swiftfun swiftdocker/swift:latest /bin/bash root@3ad0c66c55e1:/# swift --version Swift version 2.2-dev (LLVM 46be9ff861, Clang 4deb154edc, Swift 778f82939c) Target: x86_64-unknown-linux-gnu root@3ad0c66c55e1:/# exit
「--privileged=true」
$ sudo docker start swiftfun swiftfun $ sudo docker attach swiftfun root@54b06cfceebe:/#
Ubuntu Makeを使う
Ubuntuには各種ソフトウェアの開発環境を導入するための
当然のことながら、
Swiftの基本的な使い方
Swiftは一般的なコンパイラ言語ですが、
$ swift Welcome to Swift version 2.2-dev (LLVM 46be9ff861, Clang 4deb154edc, Swift 778f82939c). Type :help for assistance. 1> let prog = "swift" prog: String = "swift" 2> print("I think the perfection of \(prog) is that it's not perfect.") I think the perfection of swift is that it's not perfect. 3> :quit
REPLは対話的なデバッガなので、
その他のSwift言語の書式を一通り把握したい場合は、
実際のところSwiftのプリミティブな機能だけでは、
$ swift Welcome to Swift version 2.2-dev (LLVM 46be9ff861, Clang 4deb154edc, Swift 778f82939c). Type :help for assistance. 1> import Glibc 2> let prog = "swift" prog: String = "swift" 3> puts("I think the perfection of \(prog) is that it's not perfect.") I think the perfection of swift is that it's not perfect. $R0: Int32 = 58 4> :quit
上記ではSwiftにないlibcのputs()を用いて文字列を出力しています
もちろんREPLではなく、
import Glibc
let prog = "swift"
puts("I think the perfection of \(prog) is that it's not perfect.")
swiftコマンドにファイル名を渡すと、
$ swift puts.swift I think the perfection of swift is that it's not perfect.
実行バイナリファイルを生成したい場合は、
$ swiftc puts.swift $ ls puts puts.swift $ ./puts I think the perfection of swift is that it's not perfect.
このはさん家のSwift
「このはさん家の」
詳しいことはgihyo.
さて、
実際のところSwiftでHTTP通信する場合、
Welcome to Swift version 2.2-dev (LLVM 46be9ff861, Clang 4deb154edc, Swift 778f82939c). Type :help for assistance. 1> import Foundation 2> var url = NSURL(string: "http://gihyo.jp") 3> var myRequest:NSURLRequest = NSURLRequest(URL: url!) fatal error: init(URL:) is not yet implemented: file Foundation/NSObjCRuntime.swift, line 64 myRequest: Foundation.NSURLRequest = <extracting data from value failed> Execution interrupted. Enter code to recover and continue. Enter LLDB commands to investigate (type :help for assistance.)
どうやら一筋縄ではいかないようです。そこで今回は
というわけで実際に作ってみたコードを、
- https://
gist. github. com/ m-shibata/ a67eef729aba045bb6eb (※gihyo. jp からもダウンロードできます)
最初の#!/usr/
」
Glibcのインポートのあとに、
let config = [
"tenantName": "XXXXDDDDDDDD", // テナント名
"tenantId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // テナントID
"username": "XXXXDDDDDDDD", // APIユーザー名
"password": "PPPPPPPPPPPPPPPPP", // APIパスワード
"configfile": ".conoha", // 設定ファイル名
]
設定ファイルは実行したユーザーのホームディレクトリに保存されます。保存する内容はgetContainer()で取得したトークンとその有効期限です。
d0b24cf7c74346b6b47113a19bd57c29
2015-12-08T12:24:29Z
有効期限以内であればconfigfileのトークンを再利用し、
では、
$ sudo apt-get jq curl $ wget https://gist.githubusercontent.com/m-shibata/a67eef729aba045bb6eb/raw/e73f457022bdff8c793c01b839e60c5fb9492852/conoha.swift (conoha.swiftのconfigを更新) $ swiftc conoha.swift
ファイルをオブジェクトストレージにアップロードするには次のコマンドを実行します。
$ ./conoha put images taylor.png
オブジェクトストレージからファイルをダウンロードするには次のコマンドを実行します。ダウンロードする際、
$ mv taylor.png taylor_backup.png $ ./conoha get images taylor.png
今回のスクリプトでできるのは、
内部ではcurlとjqを使ったコマンド文字列を生成し、
func execToString(command: String) -> String {
let fp = popen(command, "r")
if fp == nil {
return ""
}
var data = String()
let buffer = [CChar](count: 1024, repeatedValue: 0)
while fgets(UnsafeMutablePointer(buffer), Int32(buffer.count), fp) != nil {
if let read = String.fromCString(buffer) {
data += read
}
}
if pclose(fp) != 0 {
return ""
}
return data
}
popen()で実行し、
popen()の第一引数はconst char *
」FILE *
」char *
」
トークンの有効期限が、
func isExpired(expire: String) -> Bool {
var expireTm = tm()
var buffer: [Character] = []
// parse YYYY-mm-ddTHH:MM:SSZ
for i in 0...3 { buffer.append(expire[expire.startIndex.advancedBy(i)]) }
expireTm.tm_year = Int32(String(buffer))! - 1900
buffer = []
(以下略)
FoundationモジュールにはNSDateがあり、
「var expireTm = tm()」
getToken()では、
func getToken() -> String {
// set config file name
let pwent = getpwuid(getuid())
let homeDir = String.fromCString(pwent.memory.pw_dir)
getpwuid()の戻り値はstruct passwd *
」
このようにSwiftでC APIを使うためには、