A Swifr Tour
Tradition suggests that the first program in a new language should print the words "Hello ,world!" on the screen. In Swift , this can be done in a single line : print("Hello world")
If you gave written code in C otr Objective - C , this syntax looks famiiar to you --- in Swift . this line of code is a complete program. Youdon't need to import a separate library for functionality like input /output or string handling . Code written at global scope is used sa 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 .
This tour gives you enough information to start writing code in Swift by showing you how to accomplish a variety of programming tasks . Don't worry if you don't understand something --everything introduced in this tour is explained in detail in the rest of this book.
Simple Values
Use ler to make a constant and var to make a variable . The value of a constant doesn't need to be known at compile time , but you must assign it a value exactly once . This means you can use constants to name a value that you determine once but use in many places .
var myVariable = 42
myVariable = 50
let myConstant = 42
A constant or variable must have the same type as the value you want to assign to it. However, you don't always have to write the type explictly.Providing a vakue when you creare a constant or variable lets the conpiler infer its type . In the exmple above , the compiler infers that myVariable is an integer because its initial value is an integer.
If the initial value doesn't provide enough information (or if there is no initial value ), specify the type by writing it after the variable , separated by a colon.
let implicitInterger = 70
let impicitDouble = 80.0
let explisitDouble : Double = 70
Values are never implicitly converted to another type . If you need to convert a value to a different type, explicitly make an instance of the desired type .
let label = " The width is "
let width = 94
let widthLable = lable + String (width)
There's an even simpler way to include balues in string : write the value in parentheses, and write a backslash (\) before th parentheses . For example: let apples = 4
let oranges = 5
let appleSummary = " I have \ (apples) apples."
let fruitSummary = " I have \ (apples + oranges ) piceces of fruit ."
Create arrays and dictionaries using brackets ([]), and access their elements by writing the index or key in brackets . A comma is allowed is allowed after the last element.
var shoppingList = ["catfish","water"]
shoppingList [1] = "bottle of water"
var occupations = ["Malcolm":"Captain"]
occupations ["Jayne"] = "Public Relations"
To create an empty array or dictionary, use the initializer syntax.
let emptyArray = [String] ()
let emptyDictionary = [String : float]()
If type information can be inferred , you can write an empty array as [] and an empty dictionary as [:] -- for example , when you set a new value for a variable or pass ab argument to a function.
shoppingList = []
occupation = [:]
Control Flow
Use if and switch to make conditionals , and use for - in , while ,and repeat- while to make loops . Paretheses around the condition or loop variable are optional . Braces around the body are required.
let indviidualScores = [75, 43 , 103, 87 12]
var teamScore = 0
for score in individualScores {
if score > 50{
teamScore += 3
}
else {
teamScore += 1
}
}
print(teamScore)
In a if statement, the conditional must be a Boolean expression --- this means that code such as if score {...} is an error, not an implicit comparison to zero.
You can use if and let together ro work with values that might be missing . These values are represented as optionals. An optional value either contains a value or contains nil to indicte that a value a is missing . Write a question mark (?) after the type of a value to mark the value as optional .
var optionalString :String? = "Hello"
print(optionalString == nil )
var optionalName :string? = "john appleseed"
var greeting = "Hello!"
if let name = optionalName {
greetiing = "Hello, \(name)"
}
If the optional value is nil , the conditional is false and the code in braces is skipped . Otherwise , the optional value is unwrapped and assigned to the constnat after let , which makes the unwrapped value available inside the block of code .
Switches support any kind of data and a wide variety of comparison operations -- they aren't limited to integers and tests for equality.
A Swifr Tour的更多相关文章
- POJ 1637 Sightseeing tour
Sightseeing tour Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 9276 Accepted: 3924 ...
- Euler Tour Tree与dynamic connectivity
Euler Tour Tree最大的优点就是可以方便的维护子树信息,这点LCT是做不到的.为什么要维护子树信息呢..?我们可以用来做fully dynamic connectivity(online) ...
- POJ2677 Tour[DP 状态规定]
Tour Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 4307 Accepted: 1894 Description ...
- soj 1015 Jill's Tour Paths 解题报告
题目描述: 1015. Jill's Tour Paths Constraints Time Limit: 1 secs, Memory Limit: 32 MB Description Every ...
- poj1637 Sightseeing tour
Sightseeing tour Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 8859 Accepted: 3728 ...
- A quick tour of JSON libraries in Scala
A quick tour of JSON libraries in Scala Update (18.11.2015): added spray-json-shapeless libraryUpdat ...
- POJ 1637 Sightseeing tour (混合图欧拉路判定)
Sightseeing tour Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 6986 Accepted: 2901 ...
- POJ 1637 Sightseeing tour (混合图欧拉回路)
Sightseeing tour Description The city executive board in Lund wants to construct a sightseeing tou ...
- POJ2135 Farm Tour
Farm Tour Time Limit: 2MS Memory Limit: 65536KB 64bit IO Format: %I64d & %I64u Description ...
随机推荐
- c语言数据类型(二)
char 类型 1.char 变量 常量 char c; 定义一个char变量 c = ‘a’ 'a'字符常量 char 的本质就是一个整数,只有一个字节大小的整数 2.printf 输出char ...
- SMP、NUMA、MPP体系结构介绍
从系统架构来看,目前的商用服务器大体可以分为三类,即对称多处理器结构 (SMP : Symmetric Multi-Processor) ,非一致存储访问结构 (NUMA : Non-Uniform ...
- 《Linux性能及调优指南》第二章:监控和基准工具2.1-2.2
翻译:飞哥 (http://hi.baidu.com/imlidapeng) 版权所有,尊重他人劳动成果,转载时请注明作者和原始出处及本声明. 原文名称:<Linux Performance a ...
- 【Jmeter自学】Jmeter作用域(五)
.Jmeter作用域 .Jmeter参数化 .Jmeter的集合点 .jmeter之关联 1.Jmeter作用域 问题: 每个元件作用域 层次结构确认 每个元件执行顺序 配置元件 前置 定时器 Sam ...
- django之模板系统 --》内容(filter过滤器、tags标签【for、if、with】、母板以及继承、crf_token、注释、组件、静态文件【load static】、get_static_prefix、自定义标签和tag)
常用: Django模板中只需要记两种特殊符号: {{ }}和 {% %} {{ }}表示变量,在模板渲染的时候替换成值,{% %}表示逻辑相关的操作. 变量 {{ 变量名 }} 变量名由字母数字和下 ...
- Django之视图Views
视图 视图接受Web请求并且返回Web响应 视图就是一个python函数,被定义在views.py中 响应可以是一张网页的HTML内容,一个重定向,一个404错误等等 响应处理过程如下图: URLco ...
- gojs 破解版
a.Hv=d[w.Kg("7eba17a4ca3b1a8346")][w.Kg("78a118b7")](d,w.pm,4,4);a.Hv= function( ...
- 《算法》第五章部分程序 part 4
▶ 书中第五章部分程序,包括在加上自己补充的代码,Trie 树类,Trie 集合,三值搜索树(Ternary Search Trie) ● Trie 树类 package package01; imp ...
- 12. ajax、datagrid请求传参实例
############实例1:############ var data = {};data.orgRoleCode = orgRoleCode;data.orgRoleName = orgRole ...
- idea 关闭自动保存,未保存星号提醒, springboot + freemarker 热部署
1,自动保存 File > setting 去掉下图勾选 2,未保存文件星号提示 File > Settings 3,spring boot 项目 热部署 3.1,pom文件添加依赖 &l ...