您的位置:首页 > 移动开发 > Swift

Swift 第一个程序HelloWorld

2016-01-18 11:37 465 查看
大学那会学的第一门编程语言是C语言。后来接触了其他语言,也看过一些书。发现第一个程序基本都是从HelloWorld开始的。那么Swift的第一个程序也不例外。

首先新建一个工程:按照下图操作。



选择新建命令行程序。



语言选择Swift。

之后就可以看见项目结构了。



main.swift就是主程序,后缀.swift是扩展名。

其实HelloWorld这个程序Xcode已经帮我们写好了。我们要做的就是编译这个工程就可以输出了。



import Foundation 导入Foundation架构,这样就可以在程序中使用Foundation架构提供的函数和类了。
print("Hello, World!")这句话是执行控制台输出。
奇怪的是,在上面的程序中,我们没有看见main函数和分号(;)。
官方的解释:
If you have written code in C or Objective-C, this syntax looks familiar to you—in Swift, this line of code is a complete program. You don’t need to import a separate library for functionality
like input/output or string handling. Code written at global scope is used as the entry point for the program, so you don’t need a main() function.
You also don’t need to write semicolons at the end of every statement.

其实在源文件.swift中得第一行可执行代码就是程序的入口。
在上面的程序中我们在print("Hello, World!")后面没有分号(;)。
在Swift程序中官方的说法:You also don’t need to write semicolons at the end of every statement.(你也不需要在每个语句的末尾写分号.)
但是一行写两个语句就是错的:print("Hello, World!") var name:String
这样写回报红色的圆圈。加上;就好了。

print("Hello, World!"); var name:String
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: