Swift Basic - 一些 Swift 基础中的基础

本文介绍了Swift编程的基础知识,包括类型推断、变量与常量的区别、数值类型转换规则、元组的使用以及字符串插值。Swift是一种静态类型语言,编译时进行类型检查,允许通过var和let控制内置类型是否可变。数值转换必须显式进行,超过Int类型最大容量会导致运行时错误。此外,还提到了Swift中的控制流结构。
摘要由CSDN通过智能技术生成

 Kye Points 要点

Playground

1 - Variables, constants, stings

(1)Type inference 类型推断: Swift compiler can infer the type of variable or constant based on the literal value you've assigned them.

Swift is a statically typed language with compile-time checking of types < Swift是静态类型语言,在编译时做类型检查 >

比如新建playground,并输入下列代码:

var str = "Hello, playground"
str = 100
println(str)

此时,编译器会在代码第二行处报错: type 'String' does not conform to protocol 'IntegerLiteralConvertible'

(2)It allows you to control the mutability of the built-in Swift type (e.g. String, Int, Dictionary, etc.) by using either the var or the let keywords at the point of declaration.

所以,通过灵活的使用var和let,可以方便的决定是某个实例是mutable还是imutable。

2 - Semicolons

If you wanna write multiple statements on a single line, you will use your familiar ';'. Otherwise, dispense with semicolons. \(^_^)/

3 - Numeric types, conversion

(1)除非程序有特殊需求,否则在一般情况下,Int和Double应该是首选。

(2)在Swift中,可以使用下划线_作为千位分隔符(thousands separator),在playground里输入以下代码

let million = 1_000_000

这样就定义了一个等于1,000,000的整型值。

(3)There is a especially important feature of Swift: all numeric type conversions must be explicit regardless of whether you want to convert to a type with more or less precision.

var radius = 4
let pi = 3.14159
//Error: Cannot invoke '*' with an argument list of type '($T4, Double).
//var area = radius * radius * pi
var area = Double(radius) * Double(radius) * pi

显式类型转换是Swift众多安全机制中得一个

(4)Swift不允许你存储一个比maximum capacity of the Int type还要大的数字。在多数除Swift 以外的语言中,这样的溢出会造成数字的“wrap around”,从而使数字变成负数。

而Swift会把它视为runtime error。

//Runtime Error: '9223372036854775807 + 1' (on type 'Int') results in an overflow.
var overflow = Int.max + 1


4 - Booleans

Swift中得布尔类型是Bool,这种类型的值是 true 或 false。和包括Objective-C在内的其他语言不同,Swift是不会讲none-zero的整型值当做“true”的。

let myBoolean = true

5 - Tuples

Tuples are a grouping of multiple values into a single type. 它与类以及结构体不通之处在于,创造一个tuple时,可以不用显式的定义类型。

//Tuples
//var loiInfo = (1000,"SuperLoi")
var loiInfo:(Int, String) = (1000,"SuperLoi")
println(loiInfo.0)
println(loiInfo.1)
loiInfo.0 = 1111

// using a type annotation
var loiInfo1:(Double, String) = (1000,"Super")
// by explicit creation of a Double
var loiInfo2 = (Double(1000), "Super")
// by using a double literal value
var loiInfo3 = (1000.0, "Super")

// deconstruct tuples into their individual elements
let (firstP, secondP) = loiInfo
println(firstP)
println(secondP)


即便是给tuple的各个元素命了名字,任然可以通过index notation 和 deconstruct them with let or var


6 - Sting interpolation

var superloiInfo = ("super", "Loi")
let (first, second) = superloiInfo
println("I am \(first.uppercaseString),\(second)")

If you wanna output a backslash character, rather than use it to indicate the start of a placeholder, you need to escape it: \\


7 - Control flow

// For loops and ranges
let loiGreeting = "Swift Rocks!"

var range = 1...10
for i in range {
    println("\(i) - \(loiGreeting)")
}

// While loops
var i = 0
while i < 5 {
    println("\(i) - \(loiGreeting)")
    i++
}

// If statements
for i in 1...5 {
    if i == 5 {
    println(loiGreeting.uppercaseString)
} else {
    println(loiGreeting)
    }
}

// Switch statements
var manner = "like"

switch manner {
case "like":
    println("loi likes it!")
case "hate":
        println("loi hates it!")
default:
            println("What about u?")
}

var percentage = 650

var prefix: String
switch percentage {
case 1..<10:
    println("novice")
case 10..<100:
        println("proficient")
case 100..<1000:
            println("rock-star")
default:
                println("awesome")
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值