Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

205
202

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftをコマンドラインから実行

Last updated at Posted at 2014-06-03

swift、ステキな言語ですね。
Objective-Cはキモ可愛い言語でしたが、キモさの部分がとれて、ただただ可愛い言語になったと思います。

まるで、大学デビューをして大人びてしまった幼なじみを見ているみたいで、
嬉しいような、なんだか少しもの寂しいような気持ちでいっぱいです。

さて、せっかくのswift、インストールしたのにxcode上でしか実行できないの、もったいないと思いませんか?
そんなあなたに朗報です。swift、コマンドラインからも実行できるようです。

Xcode6-Betaをインストールした状態で、以下のコマンドを実行しましょう。

$ find /Applications/Xcode6-Beta.app -name swift | grep /bin/swift

もしも標準出力にほにゃらら/bin/swiftというファイルが書き出されたら、それがswiftです。
このファイルを実行してみると、インタプリタが立ち上がって、コマンドラインからswiftを実行できるようになります。

~/.bash_profile等に以下を追記して、いつでも呼び出せるようにしておきましょう。

~/.bash_profile
export PATH=(swiftがある"bin/"ディレクトリへのフルパス):$PATH

これで、swiftとタイプするだけでswiftのインタプリタを呼び出せるようにできます。
ちなみに、-iオプションで、外部スクリプトも実行できます。

$ swift -i main.swift

スクリーンショット 2014-06-03 19.01.35.png

これは便利!!
これでみなさんも幸せなswiftライフを。

追記

外部スクリプトを実行する際に、import Foundationしているとこのままでは実行できず、以下のようなエラーが出てしまいます。

main.swift:1:8: error: cannot load underlying module for 'Foundation'
import Foundation
       ^
<unknown>:0: note: did you forget to set an SDK using -sdk or SDKROOT?
<unknown>:0: note: use "-sdk $(xcrun --show-sdk-path --sdk macosx)" to select the default OS X SDK installed with Xcode

エラーに従って、いかのように実行するれば無事に通ります。

$ swift -sdk $(xcrun --show-sdk-path --sdk macosx) -i main.swift 
205
202
1

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

Qiita Conference 2025 Autumn will be held!: 11/5(Wed) - 11/7(Fri)

Qiita Conference is Qiita's largest tech conference, dedicated to engineers in the age of AI!

Keynote Speaker

piacere, Tsuyoshi Ushio, Esteban Suarez, Takuto Wada, seya, MinoDriven, Toshihiro Ichitani, Karaage, Yoshimasa Iwase, Matz, Minorun, Null-Sensei

View event details

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

205
202

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?