搭建linux上的swift环境
1.安装苹果公司提供的C编译器,也是swift必需的组件
sudo apt-get --assume-yes install clang
2.在swift.org上下载最新的swift版本
点击Download,里面有swift从1-4 的版本,下载相应的版本,一般都最新的,在用户的Download目录里可以找到下载的文件
解压并放到用户根目录下tar xzf swift-版本.tar.gz
mv swift-版本 ~
3.把swift的bin目录写入环境变量
vi ~/.bashrc
把下面代码加入到文件末尾
export PATH=/home/username/swift-版本/usr/bin:"${PATH}"
4.检查是否安装成功
swift -version
出现类似下面内容即成功
Swift version 3.1.1 (swift-3.1.1-RELEASE)
Target: x86_64-unknown-linux-gnu
交互式编程
REPL — 交互式解释器环境。
R(read)、E(evaluate)、P(print)、L(loop)
输入值,交互式解释器会读取输入内容并对它求值,再返回结果,并重复此过程。
可以用来练习或检测语法
1> 1 $R0: Int = 1 2> print($R0); 1 3> let arr=[1,2,"mhj"]as Any arr: [Any] = 3 values { [0] = 1 [1] = 2 [2] = "mhj" }
4> "100".toInt() $R0: Int? = 100 5> let name = "Katherine" name: String = "Katherine" 6> println("Hello, \(name)") Hello, Katherine
7> $R0! + 200 $R1: Int = 300
//这里当出现函数参数未定义函数无返回值的问题时,可用上下键多行恢复8> func timesTwo(value: Int) -> Int { 9. return value * 2 10.}
//使用上面连续定义函数时,会出现错误“func foo() { bar() } func bar() { foo() }
error: use of unresolved identifier 'bar'
”
//解决方法是把两个函数在在同一行进行定义,更好的方法是在两个定义之间空一行,将两个函数分开,这样两个函数就能同时编译,形成互递归
19> func a(){
20. b()
21. }
22.
23. func b(){
24. a()
25. }
//这里我还发现另一种方法,直接对两个函数分别定义也可以,至于为什么不会产生对e未定义的error,还找不到原因
26> func c(){
27. e()
28. }
29> func e(){
30. c()
31. }
快捷键
Arrow Keys Move cursor left/right/up/down Control+F Move cursor right one character, same as right arrow Control+B Move cursor left one character, same as left arrow Control+N Move cursor to end of next line, same as down arrow Control+P Move cursor to end of prior line, same as up arrow Control+D Delete the character under the cursor Option+Left Move cursor to start of prior word Option+Right Move cursor to start of next word Control+A Move cursor to start of current line Control+E Move cursor to end of current line Delete Delete the character to the left of the cursor Esc < Move cursor to start of first line Esc > Move cursor to end of last line
crtl+z退出repl
简单编程
输入Print("Hello world!")保存退出vim Helloworld.swift
swiftc Helloworld.swift
显示Hello world!./Helloworld
简单可执行项目编程
编译完成后在.build/debug/中会有可执行文件Hellomkdir Hello cd Hello swift package init --type executable //使用包初始化命令,参数表示创建一个可执行的包 swift build //编译 swift test //测试
输入.build/debug/Hello回车即可运行
创建好包之后,Hello里面会有对应的文件Package.swift记录项目依赖的包和文件夹Source保存源文件,初始化默认自动创建一个main.swift,
LLDB调试器使用
主要使用到的命令有expression和breakpoint,可以简化为expr或者br
主要用法可参考以下博客:
http://blog.csdn.net/hello_hwc/article/details/50491813