Swift 第一个程序HelloWorld

大学那会学的第一门编程语言是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!"); varname:String

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...