Swift笔记(一)

前端之家收集整理的这篇文章主要介绍了Swift笔记(一)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我的主力博客半亩方塘


1、In Swift,you can optionally use underscores to make larger numbers more human-readable. The quantity and placement of the underscores is up to you.

  1. var variableNumber: Int = 1_000_000


2、
  1. var integer: Int = 100
  2. var decimal: Double = 12.5
  3. integer = decimal // wrong
  4. integer = Int(decimal) // right

3、Here is how to access the data inside the tuple:

  1. let coordinates: (Int,Int) = (2,3)
  2. let x: Int = coordinates.0
  3. let y: Int = coordinates.1

You can reference each item in the tuple by its position in the tuple,starting with zero. Swift allows you to name the individual parts of a tuple,so you to be explicit about what each part represents. For example:

  1. let coordinatesNamed: (x: Int,y: Int) = (2,3)
  2. let x: Int = coordinatesNamed.x
  3. let y: Int = coordinatesNamed.y

If you want to access multiple parts of the tuple at the same time,you can also use a shorthand Syntax to make it easier:

  1. let coordinates3D: (x: Int,y: Int,z: Int) = (2,3,1)
  2. let (x,y,z) = coordinates3D

The code is equivalent to the following:

  1. let coordinates3D: (x: Int,1)
  2. let x = coordinates3D.x
  3. let y = coordinates3D.y
  4. let z = coordinates3D.z

If you want to ignore a certain element of the tuple,you can replace the corresponding part of the declaration with an underscore.

  1. let (x,_) = coordinates3D

This line of code only declaresxandy. The_is special and simply means you are ignoring this part for now. You'll find that you can use the underscore throughout Swift to ignore a value.

4、Sometimes it's useful to check the inferred type of a variable or constant. You can do this in a playground by holding down theOptionkey and clicking on the variable or constant's name.

猜你在找的Swift相关文章