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的更多相关文章

  1. POJ 1637 Sightseeing tour

    Sightseeing tour Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 9276   Accepted: 3924 ...

  2. Euler Tour Tree与dynamic connectivity

    Euler Tour Tree最大的优点就是可以方便的维护子树信息,这点LCT是做不到的.为什么要维护子树信息呢..?我们可以用来做fully dynamic connectivity(online) ...

  3. POJ2677 Tour[DP 状态规定]

    Tour Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 4307   Accepted: 1894 Description ...

  4. soj 1015 Jill's Tour Paths 解题报告

    题目描述: 1015. Jill's Tour Paths Constraints Time Limit: 1 secs, Memory Limit: 32 MB Description Every ...

  5. poj1637 Sightseeing tour

    Sightseeing tour Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 8859   Accepted: 3728 ...

  6. 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 ...

  7. POJ 1637 Sightseeing tour (混合图欧拉路判定)

    Sightseeing tour Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 6986   Accepted: 2901 ...

  8. POJ 1637 Sightseeing tour (混合图欧拉回路)

    Sightseeing tour   Description The city executive board in Lund wants to construct a sightseeing tou ...

  9. POJ2135 Farm Tour

      Farm Tour Time Limit: 2MS   Memory Limit: 65536KB   64bit IO Format: %I64d & %I64u Description ...

随机推荐

  1. RabbitMQ manage

    1. RabbitMQ service sudo systemctl enable rabbitmq-server sudo systemctl start rabbitmq-server sudo ...

  2. 「HNOI2015」开店(树链剖分, 主席树)

    /* 考虑将所求的值拆分 记每个点到根的路径长度为dis_i, 那么我们要求的就是\sum_{i = l} ^ r dis_i + dis[u] * (r - l + 1) - 2\sum_{i = ...

  3. 提示:pip install --upgrade pip

    安装模块时报错了,提示我需要更新pip,如下所示: 但是使用pip install --upgrade pip时依然报这个错,原来是命令应该这样写: python -m pip install -U ...

  4. 微信小程序开发warning: Now you can provide attr "wx:key" for a "wx:for" to improve performance

    用微信官方的模板发现突然报了这个warning,检查原因: 官方解释: wx:key 如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <i ...

  5. CentOS7开机时的菜单选项及时间的修改

    一.在CentOS更新后,并不会自动删除旧内核.所以在启动选项中会有多个内核选项,可以手动使用以下命令删除多余的内核:(正常下,第一个选项正常启动,第二个选项急救模式启动(系统出项问题不能正常启动时使 ...

  6. (转)开放window是服务器端口——以8080为例

    本文记录两个内容: 1.win7下打开端口 2.服务器(2003或者其他老版的系统以2003为例) 测试端口时 可用telnet 命令 侦听端口:C:\Documents and Settings\a ...

  7. RPM软件管理工具

    1 概述 RPM(RedHat Package Manager),Rethat软件包管理工具,类似windows里面的setup.exe 是Linux这系列操作系统里面的打包安装工具,它虽然是RedH ...

  8. 记一次恐怖的 Integer 溢出

    一不注意, 看起来ok 的地方都出问题了! 后来才突然想起,原来是 Integer 溢出啊 这样的代码, 没想到也会出问题. public static final long Cap_Size = 9 ...

  9. centos 共享文件目录

    # yum install nfs-utils # mkdir /storage # cat /etc/exports /storage *(fsid=0,rw,sync,no_root_squash ...

  10. koltin语言学习(一)——什么是koltin

    转自:Koltin China (一) 介绍 #Kotlin-for-Android-Dev 1. 什么是Kotlin? Kotlin是JetBrains开发的基于JVM的语言.Kotlin是使用Ja ...