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.

var variableNumber: Int = 1_000_000


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

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

let coordinates: (Int, Int) = (2, 3)  
let x: Int = coordinates.0  
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:

let coordinatesNamed: (x: Int, y: Int) = (2, 3)  
let x: Int = coordinatesNamed.x
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:

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

The code is equivalent to the following:

let coordinates3D: (x: Int, y: Int, z: Int) = (2, 3, 1)
let x = coordinates3D.x
let y = coordinates3D.y
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.

let (x, y, _) = coordinates3D  

This line of code only declares x and y. 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 the Option key and clicking on the variable or constant's name.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值