您的位置:首页 > 移动开发 > Swift

swift笔记1

2016-05-24 09:20 591 查看
个人随记:不喜勿喷

基础数据类型和算法

相关知识点:半开区间,for循环

例:for _ in 0..<3 ==》 for(int i=0;i<3;i++)

空合运算符( a ?? b )将对可选类型 a 进行空判断,如果 a 包含一个值就进行解封,否则就返回一个默认值 b .这 个运算符有两个条件:

• 表达式 a 必须是Optional类型

• 默认值 b 的类型必须要和 a 存储值的类型保持一致

例:var colorNameToUse = userDefinedColorName ?? defaultColorName

字符串

3.1 字符串String类型,“Hello”不需要NS String一样带@符

3.2 字符串拼接,直接用+号即可,可以用 append 方法将一个字符附加到一个字符串变量的尾部

例:var instruction = “look over”

instruction += “-ok”

let exclamationMark: Character = “!” instruction.append(exclamationMark)

输出:look over-ok!

3.3 可通过 for-in 循环来遍历字符串中的 characters 属性来获取每一个 字符的值

例:for character in “Dog!?” { print(character) }

3.4 通过标明一个 Character 类型并用字符字面量进行赋值,可以建立一 个独立的字符常量或变量:

例:let exclamationMark: Character = “!”

3.5字符串可以通过传递一个值类型为 Character 的数组作为自变量来初始化:

例:let catCharacters: [Character] = [“C”, “a”, “t”, “!”, “?”] let catString = String(catCharacters) catString就是“Cat!?”

3.6 构建字符串的新方法:

字符串插值是一种构建新字符串的方式,可以在其中包含常量、变量、字面量和表达式。 您插入的字符串字面量 的每一项都在以反斜线\为前缀的圆括号中:

let multiplier = 3

let message = “(multiplier) times 2.5 is (Double(multiplier) * 2.5)” // message 是 “3 times 2.5 is 7.5”

3.7 字符串字面量可以包含以下特殊字符:

• 转义字符 \0 (空字符)、 \ (反斜线)、 \t (水平制表符)、 \n (换行符)、 \r (回车符)、 \” (双引号)、 \’ (单引 号)。

• Unicode 标量,写成 \u{n} (u为小写),其中 n 为任意一到八位十六进制数且可用的 Unicode 位码。

3.8

数组,字符串都可以调用isEmpty来判断对象是否为空

例:if array.isEmpty{

return(0,0)

}

以前字符串和数组等都是通过MultableString等方式来区分可变和不可变的,在swift中,这个区分来自定义时属性是var还是let

获得一个字符串中字符的数量,可以调用全局函数 count(_:) ,把字符串作为参数传进去:

例:let unusualMenagerie = “Koala ?, Snail ?, Penguin ?, Dromedary ?” println(“unusualMenagerie has (count(unusualMenagerie)) characters”) // 打印输出:”unusualMenagerie has 40 characters”

集合-数组

集合-Set

集合-字典

条件语句-if..else,while(),repeat{}while(),switch(),where,

10.1 switch()

(1)条件中可以是数值,字符,区间,元组,如:

case 1..4: 表示从1到4的区间范围

case“a”,”b”:表示是字符a或b

case (0..3,0..2):表示在一个坐标区域内的point

(2)case分之模式可以使用where语句来判断额外的条件。如:

let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y") case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y") case let (x, y):
print("(\(x), \(y)) is just some arbitrary point") }
// 输出 "(1, -1) is on the line x == -y"


11.控制转移语句:continue,break,fall through,return,throw,

有点不懂:

注意在 Swift 中,使用可拓展的字符群集作为字符来连接或改变字符串时,并不一定会更改字符串的字符数量。例:

var word = “cafe”

println(“the number of characters in (word) is (count(word))”) // 打印输出 “the number of characters in cafe is 4”

word += “\u{301}” // COMBINING ACUTE ACCENT, U+0301

println(“the number of characters in (word) is (count(word))”)

// 打印输出 “the number of characters in caféis 4”

12.检查API是否可用

if #available(iOS 9, OSX 10.10, *) {
// 在 iOS 使用 iOS 9 APIs , 并且在 OS X 使用 OS X v10.10 APIs
} else {
// 回滚至早前 iOS and OS X 的API
}


在它普遍的形式中,可用性条件获取了平台名字和版本的清单。平台名字可以是 iOS , OSX 或 watchOS 。除 了特定的主板本号像iOS8,我们可以指定较小的版本号像iOS8.3以及 OS X v10.10.3。

if #available(
platform name
version
,
...
, *) {}else{}

函数

函数定义与调用
func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!" return greeting}
函数的定义,并以 Fun 作为前缀。指定函数返回类型时,用返回箭头  (一个 连字符后跟一个右尖括号)后跟返回类型的名称的方式来表示。
函数参数与返回值
1.多重输入参数:函数多个输入参数,写在->后的圆括号中,用逗号分割
2.带参函数:函数名圆后括号内是参数,没有参数时,括号也不可省略
3.无返回值函数:函数可以没有返回值,没有返回值的函数定义中没有返回箭头->
例:func printWithoutCounting(stringToPrint: String) {
4.多返回值函数:
例:func minMax(array: [Int]) -> (min: Int, max: Int) 定义一个可以返回数组中最值的函数
注:如果函数返回的元组类型中有可能在整个元组中含有“没有值”,你可以使用可选的(Optional) 元组返回类型反映整个元组可以是 nil 的事实.你可以通过在元组类型的右括号后放置一个问号来定义一个可选元组
例:func minMax(array: [Int]) -> (min: Int, max: Int)? {}这样如果遇到空数组问题,可以返回nil,但是你在调用函数时需要注意nil的处理

函数参数名称
1.指定外部参数名
例:func sayHello(to person: String, and anotherPerson: String) -> String {},这个sayHello(to:and:)使用外部函数名可使得所有参数用一句话表达清楚,使得函数体内部可读,能表达出函数的明确意图.
注:这种写法不常用,有点多余
2.默认参数值:可以在函数体中为每个参数定义 默认值(Deafult Values) 。当默认值被定义后,调用这个函数时可以忽略这个 参数。
例:func someFunction(parameterWithDefault: Int = 12)
3.可变参数:可接受零个或多个值。通过在变量类型名后面加入 (...) 的方式来定义可变参数。函数调用时,你可以用可变参数来传入不确定数 量的输入参数。
例:


//计算一组任意长度数字的 算术平均数(arithmetic mean)
func arithmeticMean(numbers: Double...) -> Double { var total: Double = 0
for number in numbers {
total += number }
return total / Double(numbers.count) }
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers


注意: 最多可以有一个可变参数函数,和它必须出现在参数列表中,为了避免歧义在调用函数有多个参数。 如果 你的函数有一个或多个参数有默认值,还有一个可变的参数,将可变参写在参数列表的最后。
4.常量参数和变量参数:**
函数参数默认是常量。试图在函数体中更改参数值将会导致编译错误。这意味着你不能错误地更改参数值。
但是,有时候,如果函数中有传入参数的变量值副本将是很有用的。你可以通过指定一个或多个参数为变量参数,从而避免自己在函数中定义新的变量。变量参数不是常量,你可以在函数中把它当做新的可修改副本来使用。
定义变量参数要在参数前加关键字var,例:


func alignRight(var string: String, totalLength: Int, pad: Character) -> String { let amountToPad = totalLength - string.characters.count
if amountToPad < 1 {
return string }
let padString = String(pad) for _ in 1...amountToPad {
string = padString + string }
return string }
let originalString = "hello"
let paddedString = alignRight(originalString, totalLength: 10, pad: "-") // paddedString is equal to "-----hello"
// originalString is still equal to "hello"


5.输入输出函数
定义一个输入输出参数时,在参数定义前加 inout 关键字。一个输入输出参数有传入函数的值,这个值被函数修 改,然后被传出函数,替换原来的值。
你只能将变量作为输入输出参数。你不能传入常量或者字面量(literal value),因为这些量是不能被修改的。当 传入的参数作为输入输出参数时,需要在参数前加 & 符,表示这个值可以被函数修改。例:


func swapTwoInts(inout a: Int, inout _ b: Int) { let temporaryA = a
a =b
b = temporaryA
}


函数类型

1.在 Swift 中,使用函数类型就像使用其他类型一样。例如,你可以定义一个类型为函数的常量或变量,并将函数 赋值给它:

var mathFunction: (Int, Int) -> Int = addTwoInts

这个可以读作:“定义一个叫做 mathFunction 的变量,类型是‘一个有两个 Int 型的参数并返回一个 Int 型的值的函数’,并让这个新变量指向 addTwoInts 函数”。addTwoInts 和 mathFunction 有同样的类型,所以这个赋值过程在 Swift 类型检查中是允许的。有相同匹配类型的不同函数也可以被赋值给同一个变量,就像非函数类型的变量一样

例:

var mathFunction:(Int,Int)->Int = addTwoInts
print("add Result:\(mathFunction(2,3))")
mathFunction = multiplyTowInts
print("multiply Result:\(mathFunction(2,3))")


就像其他类型一样,当赋值一个函数给常量或变量时,你可以让 Swift 来推断其函数类型,例:


let anotherMathFunction = addTwoInts
// anotherMathFunction is inferred to be of type (Int, Int) -> Int


2.函数类型作为参数类型(Function Types as Parameter Types) 例:

func printMathResult(mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \(mathFunction(a, b))")}
printMathResult(addTwoInts, 3, 5) // prints "Result: 8"


3.函数类型作为返回类型

你可以用函数类型作为另一个函数的返回类型。你需要做的是在返回箭头( -> )后写一个完整的函数类型。例:

func stepForward(input: Int) -> Int { return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1 }
func chooseStepFunction(backwards: Bool) -> (Int) -> Int { return backwards ? stepBackward : stepForward
}

//函数调用
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0) // moveNearerToZero now refers to the stepBackward() function
print("Counting to zero:") // Counting to zero: while currentValue != 0 {
print("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue) }
print("zero!") // 3...
// 2...
// 1...
// zero!


函数嵌套:
这章中你所见到的所有函数都叫全局函数(global functions),它们定义在全局域中。你也可以把函数定义在别 的函数体中,称作嵌套函数(nested functions)。
默认情况下,嵌套函数是对外界不可见的,但是可以被他们封闭函数(enclosing function)来调用。一个封闭 函数也可以返回它的某一个嵌套函数,使得这个函数可以在其他域中被使用。


你可以用返回嵌套函数的方式重写 chooseStepFunction(_:) 函数:
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
}
return backwards ? stepBackward : stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
print("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue) }
print("zero!") // -4...
// -3...
// -2...
// -1... // zero!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: