LoginSignup
4

More than 3 years have passed since last update.

Swiftをコマンドラインから実行(メモ)

Last updated at Posted at 2020-03-01

環境設定

Mac OS Catalina(10.15.3)、xcodeは5.1.3が入っています。

$ sudo xcode-select -s /Applications/Xcode.app
$ sudo xcode-select --install
xcode-select: note: install requested for command line developer tools

ここでデベロッパーツールを追加でインストール。完了後はswiftを打つと通るようになりました。

$ swift
Welcome to Apple Swift version 5.1.3 (swiftlang-1100.0.282.1 clang-1100.0.33.15).
Type :help for assistance.
  1>  

コンパイル

collatz.swift
var n = 100
repeat {
    print("\(n)")
    if n % 2 == 0{
    n /= 2
    }else{
    n = n * 3 + 1
    }
}while n > 1
print(n)

これを保存しておきます。

$ swiftc collatz.swift

このコマンドでコンパイルできます。

screenshot.png

すると実行ファイルが作成されます。

これを実行します。

$ ./collatz

実行結果
100
50
25
76
38
19
58
29
88
44
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1


コンパイルせずに解釈実行

上のファイルを解釈実行させます。

swift collatz.swift

参考文献

『詳解Swift 第5版』

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4