Scott

swift基础语法 8 months ago

swift
2996个字符
共有110人围观

声明

以下教程都是我仔细阅读官网慢慢整理的

swfit当前版本信息如下:

basic concept

swift内置了很多基础类型:

  • String
  • Bool
  • Int
  • Double

还有基础类型的集合:

  • Array
  • Set
  • Dictionary

集合的展示形式如下:

swift还引进了python里的Tuples,这样函数在接收和返回值的时候,一个变量可替代多个相关的数据

swift和dart一样,内置类型推导,变量用var定义,常量用let定义。在swift里一旦变量 or 常量被赋值,类型就被确定下来了

swift是类型安全的语言,如果类型不匹配,编译是会报错的

基础

常量和变量

//常量let定义,可以晚点再赋值,一旦赋值,就不可改变
let maximumNumberOfLoginAttempts = 10
//变量var定义
var currentLoginAttempt = 0

流程控制

if语句后面没有() 和golang挺搭的

var environment = "development"
let maximumNumberOfLoginAttempts: Int
// maximumNumberOfLoginAttempts has no value yet.


if environment == "development" {
    maximumNumberOfLoginAttempts = 100
} else {
    maximumNumberOfLoginAttempts = 10
}
// Now maximumNumberOfLoginAttempts has a value, and can be read.

可以在单行定义多个变量,变量之间用,隔开

var x = 0.0, y = 0.0, z = 0.0, a="scott", b=2

类型声明

var welcomeMessage: String
welcomeMessage = "Hello"

如果多个变量数据类型一样 可以声明在同一行上,变量之间用,隔开,变量声明跟在最后一个变量后面

var red, green, blue: Double

关于常量和变量的名字

名字可以是任意unicode,如下都是合法的:

let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"

但是还是要遵循最基本的命名规则:

  • 不能包含空白字符、数学符号、箭头、私有使用的 Unicode 标量值或线条和方框绘制字符
  • 不能以数字开头

打印输出

打印输出是校验真理最直接也是最有效的方法

和python一样,我们可以直接print()

print(friendlyWelcome)
// Prints "Bonjour!"

swift字符串连接和lua一样使用时有点别扭, 如下将friendlyWelcome变量嵌入到字符串中:

语法:\(变量名):

print("The current value of friendlyWelcome is \(friendlyWelcome)")
// Prints "The current value of friendlyWelcome is Bonjour!"

注释

//单行
// This is a comment.
//多行
/* This is also a comment
but is written over multiple lines. */
//多行嵌套
/* This is the start of the first multiline comment.
    /* This is the second, nested multiline comment. */
This is the end of the first multiline comment. */

分号

不同于c, c++,dart, swift并没有强制让你每行声明后面都必须加分号;,但是如果你想通过单行声明多行语句时;还是必须的, 如下demo:

let cat = "🐱"; print(cat)
// Prints "🐱"

类型推导

let meaningOfLife = 42
// meaningOfLife is inferred to be of type Int
let pi = 3.14159
// pi is inferred to be of type Double
let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double

Type Aliases

typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min
// maxAmplitudeFound is now 0

bool

let orangesAreOrange = true
let turnipsAreDelicious = false
if turnipsAreDelicious {
    print("Mmm, tasty turnips!")
} else {
    print("Eww, turnips are horrible.")
}
// Prints "Eww, turnips are horrible."

不同与js, Swift 的类型安全阻止非布尔值替换 Bool。以下示例报告编译时错误:

let i = 1
if i {
    // this example will not compile, and will report an error
}
let i = 1
if i == 1 {
    // this example will compile successfully
}