Help us understand the problem. What is going on with this article?

Swiftのインタプリタモードが楽しい

More than 5 years have passed since last update.

What is Swift?

概要

  • Appleが作った不自由言語。ソースコードの公開は無い
  • 主にXcodeで動く。
  • LLVMを用いており、コンパイルが激速(らしい。それに関しては後述)
  • PHPに関数型言語の要素を追加したようなカオスな言語
  • 人によってはJavaに似てるとかPythonに似てるとかCoffeeScriptに似てるとか言ってる。
  • (Lispに似ていると言っている人はまだ見たこと無い)
  • 僕(Apple)の考えた最強のプログラミング言語

Xcodeと呼ばれる FUJITSU 不自由なIDEでしか動かない不自由なプログラミング言語です。
言語仕様はiBooksと呼ばれる、これも不自由(主に使い勝手が悪い)なストアからDLして読める。
しかし、これもサンプルコードから理解してね☆(ゝω・)vキャピ的なノリで書かれている感が否めない。

LT大会が行われるようだが、既にネタがあるのだろうか。

--
--6/10追記--
HTML版のドキュメントもあるようです
The Swift Programming Language: About Swift

SwiftにもREPLモードがあった

/Applications/Xcode6-Beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/
の中になんか色々と入ってた。
その中にswiftなるものがあり、公式ドキュメントには存在自体無いが、こいつの中に説明文が埋め込まれていた。

$ swift -h

OVERVIEW: Swift compiler

USAGE: swift [options] <inputs>

MODES:
  -dump-ast        Parse and type-check input file(s) and dump AST(s)
  -dump-parse      Parse input file(s) and dump AST(s)
  -emit-assembly   Emit assembly file(s) (-S)
  -emit-bc         Emit LLVM BC file(s)
  -emit-executable Emit a linked executable
  -emit-ir         Emit LLVM IR file(s)
  -emit-library    Emit a linked library
  -emit-object     Emit object file(s) (-c)
  -emit-silgen     Emit raw SIL file(s)
  -emit-sil        Emit canonical SIL file(s)
  -integrated-repl Integrated REPL mode
  -i               Immediate mode
  -lldb-repl       LLDB-enhanced REPL mode
  -parse           Parse input file(s)
  -print-ast       Parse and type-check input file(s) and pretty print AST(s)
  -repl            REPL mode

OPTIONS:
  -application-extension  Restrict code to those available for App Extensions
  -arch <arch>            Compile for architecture <arch>
  -assert-config <value>  Specify the assert_configuration replacement. Possible values are Debug, Release, Replacement.
  -D <value>              Specifies one or more build configuration options
  -emit-dependencies      Emit Make-compatible dependencies files
  -emit-module-path <path>
                          Emit an importable module to <path>
  -emit-module            Emit an importable module
  -emit-objc-header-path <path>
                          Emit an Objective-C header file to <path>
  -emit-objc-header       Emit an Objective-C header file
  -framework <value>      Specifies a framework which should be linked against
  -F <value>              Add directory to framework search path
  -g                      Emit debug info
  -help                   Display available options
  -import-underlying-module
                          Implicitly imports the Objective-C half of a module
  -I <value>              Add directory to the import search path
  -j <n>                  Number of commands to execute in parallel
  -L <value>              Add directory to library link search path
  -l<value>               Specifies a library which should be linked against
  -module-cache-path <value>
                          Specifies the Clang module cache path
  -module-link-name <value>
                          Library to link against when using this module
  -module-name <value>    Name of the module to build
  -nostdimport            Don't search the standard library import path for modules
  -output-file-map <path> A file which specifies the location of outputs
  -o <file>               Write output to <file>
  -parse-as-library       Parse the input file(s) as libraries, not scripts
  -parse-sil              Parse the input file as SIL code, not Swift source
  -save-temps             Save intermediate compilation results
  -sdk <sdk>              Compile against <sdk>
  -serialize-diagnostics  Serialize diagnostics in a binary format
  -target-cpu <value>     Generate code for a particular CPU variant
  -target-feature [+-]<feature-name>
                          Generate code with a particular CPU feature enabled or disabled
  -target <value>         Generate code for the given target
  -version                Print version information and exit
  -v                      Show commands to run and use verbose output
  -Xcc <arg>              Pass <arg> to the C/C++/Objective-C compiler
  -Xfrontend <arg>        Pass <arg> to the Swift frontend
  -Xlinker <value>        Specifies an option which should be passed to the linker
  -Xllvm <arg>            Pass <arg> to LLVM.

色々出来そうだぞ…!

早速swiftコマンドで遊んでみる

.swiftファイルを普通に実行する

swiftファイルを実行するにはswift -i filename.swiftで行えます

$ cat hello.swift
let text = "HelloWorld!"
println(text)

$ swift -i hello.swift
HelloWorld!

.swiftファイルを実行可能な形式にコンパイルする

引数なしでswift filename.swiftで実行可能なバイナリが吐かれます。
ってかコンパイルが早すぎて何が起きたのか分からなかった...

$ swift hello.swift

$ ./hello
HelloWorld!

インタプリタモード(REPL)で動かしてみる

nodeirbのような一行ずつ実行できる機能が搭載されています。

$ swift

Welcome to Swift!  Type :help for assistance.
  1> 

ヽ('ω')ノ三ヽ('ω')ノ楽しい!!!!
ちなみに、Control + Dでコンソールを抜け出す事が出来ます。

  1> :help

The Swift REPL (Read-Eval-Print-Loop) acts like an interpreter.  Valid statements, expressions, and declarations are
immediately compiled and executed.

The complete set of LLDB debugging commands are also available as described
below.  Commands must be prefixed with a colon at the REPL prompt (:quit for example.)  Typing just a colon followed
by return will switch to the LLDB prompt.


Debugger commands:

_regexp-attach    -- Attach to a process id if in decimal, otherwise treat the argument as a process name to attach
                     to.
_regexp-break     -- Set a breakpoint using a regular expression to specify the location, where <linenum> is in
                     decimal and <address> is in hex.
_regexp-bt        -- Show a backtrace.  An optional argument is accepted; if that argument is a number, it specifies
                     the number of frames to display.  If that argument is 'all', full backtraces of all threads are
                     displayed.
_regexp-display   -- Add an expression evaluation stop-hook.
_regexp-down      -- Go down "n" frames in the stack (1 frame by default).
_regexp-env       -- Implements a shortcut to viewing and setting environment variables.
_regexp-jump      -- Sets the program counter to a new address.
_regexp-list      -- Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the
                     appropriate 'source list' commands.
_regexp-tbreak    -- Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is
                     in decimal and <address> is in hex.
_regexp-undisplay -- Remove an expression evaluation stop-hook.
_regexp-up        -- Go up "n" frames in the stack (1 frame by default).
apropos           -- Find a list of debugger commands related to a particular word/subject.
breakpoint        -- A set of commands for operating on breakpoints. Also see _regexp-break.
command           -- A set of commands for managing or customizing the debugger commands.
disassemble       -- Disassemble bytes in the current function, or elsewhere in the executable program as specified
                     by the user.
expression        -- Evaluate a C/ObjC/C++ expression in the current program context, using user defined variables
                     and variables currently in scope.
frame             -- A set of commands for operating on the current thread's frames.
gdb-remote        -- Connect to a remote GDB server.  If no hostname is provided, localhost is assumed.
gui               -- Switch into the curses based GUI mode.
help              -- Show a list of all debugger commands, or give details about specific commands.
kdp-remote        -- Connect to a remote KDP server.  udp port 41139 is the default port number.
log               -- A set of commands for operating on logs.
memory            -- A set of commands for operating on memory.
platform          -- A set of commands to manage and create platforms.
plugin            -- A set of commands for managing or customizing plugin commands.
process           -- A set of commands for operating on a process.
quit              -- Quit out of the LLDB debugger.
register          -- A set of commands to access thread registers.
script            -- Pass an expression to the script interpreter for evaluation and return the results. Drop into
                     the interactive interpreter if no expression is given.
settings          -- A set of commands for manipulating internal settable debugger variables.
source            -- A set of commands for accessing source file information
target            -- A set of commands for operating on debugger targets.
thread            -- A set of commands for operating on one or more threads within a running process.
type              -- A set of commands for operating on the type system
version           -- Show version of LLDB debugger.
watchpoint        -- A set of commands for operating on watchpoints.

For more information on any command, type ':help <command-name>'.
  1>

REPLを触って気づいたこと

  • letで宣言した変数を再代入可能である
  • 再宣言時なら型を変えることが可能
  1> let t = 10
t: Int = 10
  2> let t = 1.0
t: Double = 1
  3> let t = "a"
t: String = "a"
  4> t = "hello"
  5> println(t)
hello
  • しかし、動的に型を変更することはできない。
  • 以下の挙動から見るに、REPLでのletはvarとして宣言されているっぽい?
  4> let a = 10
a: Int = 10
  5> a = "10"
<REPL>:5:3: error: cannot convert the expression's type '()' to type 'Int'
a = "10"
~~^~~~~~

  5> var b = 10
b: Int = 10
  6> b = "10"
<REPL>:6:3: error: cannot convert the expression's type '()' to type 'Int'
b = "10"
~~^~~~~~

しかしまだバグが多い

まぁ、まだ初期バージョンですからね。

1> let crash:Any = {(s:String)in s}
[1] 79475 segmentation fault swift

dll7
Node.jsと眼鏡っ娘が大好き
http://blog.temp.ws
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした