Swift基础语法

print("Hello Swift")

.不用编写main函数,Swift将全局范围内的首句可执行作为程序入口

.一句代码尾部可以省略分号(;),多句代码写在同一行时必须用分号(;)隔开

.用var定义变量,let定义常量,编译器能自动推断出变量\常量的类型

let a = 10
let b = 20
var c = a + b + 10
c += 30

Playground可以快速预览代码效果,是学习语法的好帮手

Command+Shift+Enter:运行整个Playground

Shift+Enter:运行截止到某一行代码

import UIKit
import PlaygroundSupport


let view = UIView()
view.frame = CGRect(x:0,y:0,width:100,height:100)
view.backgroundColor = UIColor.blue
PlaygroundPage.current.liveView = view

// 注释

// 单行注释

/*

多行注释

*/

/*

swift基础语法

/* 注释文本嵌套*/

*/

常量

只能赋值一次

它的值不要求在编译时期确定,但使用之前必须赋值1次.

let a = 10
let b: Int
b = 20

func getData() -> Int{
    return 30
}

let c = getData()

常量/变量在初始化之前,都不能使用

let width: Double
var height: Double
print(width) // error: variable 'height' used before being initialized
print(height) // note: variable defined here

 语法错误: 未申明变量类型, 不在同一行赋值,需要先申明类型

let a
a = 20 
// note: join the identifiers together with camel-case
a = 20
^
aA

标识符

标识符(比如常量名 / 变量名 / 函数名)几乎可以使用任何字符

标识符不能以数字开头,不能包含空白字符 / 制表符 / 箭头等特殊字符

常见数据类型

值类型(value type)枚举(enum)Optional
值类型(value type)结构体(struct)Bool、Int、Float、Double、Character
引用类型(reference type)类(class)

整数类型:Int8、Int16、Int32、Int64、UInt16、UInt32、UInt64

在32 bit平台、Int等价于Int32; 在64 bit平台,Int等价于Int64

整数的最值:UInt8.max、Int16.min

一般情况下,都是直接使用Int即可。

浮点类型:Float,32位,精度只有6位; Double,64位,精度至少15位

let lf: Float = 40.0
let ld = 30.0

字面量

// 布尔
let bool = true // 取反false
//字符串
let string = "Swift"
// 字符
let character: Character = "🐶"
// 整数
let i = 10
// 浮点
let f = 30.0
// 数组
let array = [1,3,5,6,7]
// 字典
let dictionary = ["age":20,"name":"Jack"]

类型转换

// 整数转换
let int1: UInt16 = 2
let int2: UInt8 = 1
let int3 = int1 + UInt16(int2)

// 整数、浮点数转换
let int = 3
let double = 0.31456
let pi = Double(int) + double
let intPi = Int(pi)

// 字面量可以直接相加,因为数字字面量本身没有明确的类型
let result = 3 + 0.31456

元组

let http404error = (404,"Page not found")
print("this status code is \(http404error.0)",http404error.1) // this status code is 404 Page not found

let (statusCode,statusMessage) = http404error
print("this status code is \(statusCode)",statusMessage)

let (juststatusCode,_) = http404error
print("this status code is \(juststatusCode)")

let http200Status = (statusCode:200,description:"OK")
print("this status code is \(http200Status.statusCode)",http200Status.description)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值