Swift学习笔记

学习无止境,学完一门语言又一门,只有不停的学习,才不会被淘汰,在学了scala之后,在学习与scala非常接近的swift,只有记录学习中的过程

才能将一门语言学好,因为有了scala 的基础,在学习swift的时候尽可能的比较它们之间的差别。

1.类型定义

scala里类型定义分为可变与不可变,swift也使用了这种函数式类型定义。

 

let hLet = "Hello world"
var vLet = "Hello world"

let为不可变类型,而var为可变类型,与scala一样swift也使用这种类型推断系统,来推断你当前的类型是什么,然而也可以给他们做类型定义

let hLet = "Hello world"
var vLet = "Hello world"

与scala一样swift也不强制写;结尾符,对于新一代的语言都将分好去掉,这样的语法更加简洁。

在基础类型上,swift与大多数语言一样,常用的基础类型都支持

let dLet :Double = 12.12
let iLet :Int = 12
let fLet :Float = 12.12
let cLet :Character = "1"
let sLet :String = "123"
let oLet :Any = "123"
let bLet :Bool = true

类型别名,在swift中类型也可以做定义,这与scala一样,但是我还没有接触swift的类型系统,不知道他们之间有什么区别:

typealias IntSample = UInt16

let uLet:IntSample = 1000

元组,元组类型,在C#,scala里都有:

let tLet = (404, "Not Found")
tLet.0
tLet.1
let (statusCode, statusMessage) = tLet
statusCode
statusMessage

let possibleNumber = "123"
let convertedNumber = possibleNumber.toInt()

var serverResponseCode:Int? = 404
serverResponseCode = nil

在swift 里与scala一样使用nil表示空类型

隐式解析:

let possibleString:String? = "An optional string."
println(possibleString)
println(possibleString!)

输出:Optional("An optional string.") 

       An optional string.

使用?默认给你添加了一个Optional的类型,来处理等于nil的情况。

 

2.基本运算

运算符分为一目运算符,双目运算符,和三目运算符:

因为其他的与大多数语言类似,所以我只举例了三目运算符:

let rowHeight = contentHeight + (hasHeader ? 50 : 20)

这种写法和C#还是一样的,但在scala里if是有返回值的,所以使用if取代了这种写法。

区间运算符:

for index in 1...5
{
    println(index)
}

1...5就是区间运算符,表示1至5 ,这与scala是一致的

逻辑运算,逻辑运算也与大部分语言一致 &&,!,||

字符串,字符串也与大部分语言一致,但是swift使用Character替代了char

3.集合类型

数组:

var shoppringList:[String] = ["eggs","Milk"] //定义字符串数组
var tShoppringList=["Eggs","Milk"] //使用推荐
if shoppringList.isEmpty{
    println("empty")
}
else{
    println("not empty")
}
shoppringList.append("123")
shoppringList += tShoppringList
shoppringList[0]
shoppringList.insert("f", atIndex: 0)
let mapleSyrup = shoppringList.removeAtIndex(0)
let apples = shoppringList.removeLast()
for item in shoppringList{
    println(item)
}

for(index,value) in enumerate(shoppringList){
    println("Item \(index + 1): \(value)")
}

var someInts = [Int]()
println("someInts is of type Int[] with \(someInts.count) items。")

数组的一些基本操作,只要学过其他的语言,数组的基本操作还是比较简单的。

字典类型:

var airports: Dictionary<Int,String> = [1:"TYO",2:"DUB"]
var air:Dictionary<Int,String> = [1:"TYO",2:"DUB"]
for(airportCode,airportName) in airports{
    println("\(airportCode):\(airportName)")
}
for airportCode in airports.keys{
    println("Airport code:\(airportCode)")
}

for airportName in airports.values{
    println("Airport name: \(airportName)")
}

 

你可能感兴趣的:(swift)