swift進修文檔(筆記)。本站提示廣大學習愛好者:(swift進修文檔(筆記))文章只能為提供參考,不一定能成為您想要的結果。以下是swift進修文檔(筆記)正文
Swift是供iOS和OS X運用編程的新編程說話,基於C和Objective-C,而卻沒有C的一些兼容束縛。Swift采取了平安的編程形式和添加古代的功效來是的編程加倍簡略、靈巧和風趣。界面則基於廣受國民大眾敬愛的Cocoa和Cocoa Touch框架,展現了軟件開辟的新偏向。
變量與常量
變量界說應用var,常量應用let,類型平安,有主動類型推導,留意賦值的=號雙方必需有空格。變量和常量名是可以簡直一切字符,這些都異常像javascript。中文編程一下牛逼了。
var a = 123 //a為Int let b = "helo" //b為String var 貓叫 = "喵"
數字
比擬長的數字間可以加上_用來進步法式的可讀性,好比0_0其實就是0,_線不克不及加在開首
布爾類型
true和false,流程掌握if的時刻,斷定語句前往必需是一個Bool值,好比:
let i = 1 if i { //編譯報錯 }
如許便可以經由過程
if i == 1 { }
它不像js裡會有主動類型轉換
類型別號
給如今的類型添加別號,異樣可以進步法式的可讀性,如
typealias 音頻采樣 = UInt16
可以在其余處所應用 var 已發明的最年夜振幅 = 音頻采樣.min
元組
它可所以一組值,這些值不用是雷同的類型,例如,界說我本身:
var jserme = ("183cm", 26, "76kg")
可以像數組一樣拜訪
println(jserme.0) //前往183cm
元組復原為自力的變量或許常量
let jserme = ("183cm",26,"76kg") let (身高, 年紀, 體重) = jserme println("身高是 \(身高)")
也能夠給每一個值定名(這就像在JS裡把數組弄成了對象了。。。)
let jserme = (身高:"183cm",年紀:26,體重:"76kg") println("身高是 \(jserme.身高)")
字符串
字符串字面量只能用""來界說,String實質上是Character的有序聚集。
for char in "一言既出"{ println(char) } /* 一 言 既 出 */
字面量與斷定能否為空
var 字符串 = "我是字符串" var 空字符串 = "" if 空字符串.isEmpty { println("這是一個空的字符串") } if 空字符串 == "" { println("這是一個空的字符串") }
字符串實例有兩個辦法hasPrefix與hasSuffix,如:
var 成語數組 = [ "一言既出", "劍拔弩張", "一呼百諾", "一錘定音", "一無一切", "平生一世", "一見鐘情" ] var count = 0 for 成語 in 成語數組 { if(成語.hasPrefix("一")){ count++ } } println(count) //輸入7
與js一樣,string也是傳值援用,上面的兩個變量的修正不會影響到彼此
var 一串 = "我是字符串一" var 二串 = 一串 二串 = "我是字符串二" println("字符串一:\(一串), 字符串二:\(二串)")
區間運算符
閉區間應用a...b,從a到b,包括a與b,半區間a..b,從a到b,不包括b,例如:
var 成語數組 = [ "一言既出", "劍拔弩張", "一呼百諾" ] for i in 0..成語數組.count { println("第\(i)個成語是:\(成語數組[i])") } //這裡若何應用...會報錯,由於成語數組[3]是沒有值的
兩種聚集,array 和 dictionaries
絕對於js對數組和對象成員松懈的請求,swift請求數組和dictionaries裡成員類型必需分歧
var 購物清單: String[] = ["雞蛋", "牛奶"] //也能夠是上面的如許 //var 購物清單 = ["雞蛋", "牛奶"]
數組的修正可使用append辦法或許+=
var 購物清單 = ["雞蛋", "牛奶"] 購物清單.append("蘋果") 購物清單 += "草莓" println("\(購物清單)") //[雞蛋, 牛奶, 蘋果, 草莓]
數組的獲得,可以經由過程索引,也能夠經由過程區間運算符
var 購物清單 = ["雞蛋", "牛奶"] println("\(購物清單[0])") //雞蛋 println("\(購物清單[0..1])") //[雞蛋] println("\(購物清單[0...1])") //[雞蛋, 牛奶] println("\(購物清單[0...2])") //[雞蛋, 牛奶, ]
dictionaries的界說
var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"] //也能夠簡化為 //var airports = ["TYO": "Tokyo", "DUB": "Dublin"]
它的修正與讀取應用[],而不克不及應用.
airports["BJ"] = "Beijin"
掌握語句
如後面的幾個例子所示,掌握語句的前提不像js有小括號
for var index = 0; index < 3; index++ { println("index is \(index)") } //index is 0 //index is 1 //index is 2
函數
函數的聲明與挪用:
func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!" return greeting } println(sayHello("jserme"))
無前往的函數,其本質是前往一個Void,它同等於一個空的元組()
多前往值的函數與默許參數:
func info(word:String = "aha") -> (length:Int, containA:Bool){ var containA = false for char in word { if( char == "a") { containA = true break } } return (word.utf16count, containA) } println(info(word: "波波")) //(2, false) println(info()) //(3, true)
便於浏覽的內部參數名,在參數界說之前,與參數界說以空格離隔,以下面的多個參數
func join(string s1: String, toString s2: String, withJoiner joiner: String) -> String { return s1 + joiner + s2 } //挪用的時刻 join(string: "hello", toString: "world", withJoiner: ", ") // returns "hello, world"
參數名與內部參數名分歧,可以給參數名加#標識:
func containsCharacter(#string: String, #characterToFind: Character) -> Bool { for character in string { if character == characterToFind { return true } } return false } let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v") // containsAVee equals true, because "aardvark" contains a "v"
函數的參數是常量,弗成以修正,假如在函數內修正,變量界說前加var
func alignRight(var string: String, count: Int, pad: Character) -> String { let amountToPad = count - countElements(string) for _ in 1...amountToPad { string = pad + string } return string } let originalString = "hello" let paddedString = alignRight(originalString, 10, "-") // paddedString is equal to "-----hello" // originalString is still equal to "hello"
假如想在函數內修正傳入的參數,可使用inout症結字來標識,傳入的參數須要前綴&,這外部完成應當是指針。
func swapTwoInts(inout a: Int, inout b: Int) { let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherInt) println("someInt is now \(someInt), and anotherInt is now \(anotherInt)") // prints "someInt is now 107, and anotherInt is now 3"
函數類型,可以像js一樣應用函數作為參數及前往值
func addTwoInts(a: Int, b: Int) -> Int { return a + b } //函數類型為 (Int, Int) -> Int func multiplyTwoInts(a: Int, b: Int) -> Int { return a * b }//函數類型為 (Int, Int) -> Int //吸收名為mathFunction的函數類型 func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) { println("Result: \(mathFunction(a, b))") } printMathResult(addTwoInts, 3, 5) // prints "Result: 8" //前往函數類型 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
閉包
函數與它包括的高低文的變量在一路稱為閉包。如sort函數:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] func backwards(s1: String, s2: String) -> Bool { return s1 > s2 } var reversed = sort(names, backwards) println(reversed) // reversed is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]s
應用閉包可以表現為:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] var reversed = sort(names, {(s1:String, s2:String) -> Bool in return s1 > s2 }) println(reversed) // reversed is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
也能夠簡化為
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] var reversed = sort(names, { s1, s2 in s1 > s2 } ) println(reversed)
列舉
經由過程上面的語法聲明
enum Barcode { case UPCA(Int, Int, Int) = (1,2,3) case QRCode(String) = "hello" }
類與構造體
推舉應用首字母年夜寫來定名
struct Resolution { var width = 0 var heigth = 0 } class VideoMode { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? }
生成實例:
let someResolution = Resolution() let someVideoMode = VideoMode()
屬性拜訪與修正,應用.語法:
println("The width of someVideoMode is \(someVideoMode.resolution.width)") someVideoMode.resolution.width = 12880 println("The width of someVideoMode is now \(someVideoMode.resolution.width)")
構造體有主動成員初始化器,類實例沒有:
let vga = resolution(width:640, heigth: 480)
構造體與列舉都是值類型,類是援用類型
關於援用了統一個實例的值,可使用===和!==來停止斷定
延遲屬性,@lazy,設置在挪用的時刻才初始化特定的屬性
class DataImporter { /* DataImporter 是一個將內部文件中的數據導入的類。 這個類的初始化會消費很多時光。 */ var fileName = "data.txt" // 這是供給數據導入功效 } class DataManager { @lazy var importer = DataImporter() var data = String[]() // 這是供給數據治理功效 } let manager = DataManager() manager.data += "Some data" manager.data += "Some more data" // DataImporter 實例的 importer 屬性還沒有被創立
類、構造體、列舉都可以經由過程設置setter與getter來
struct AlternativeRect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set { //這裡setter 沒有界說表現新值的參數名,則可使用默許稱號newValue origin.x = newValue.x - (size.width / 2) origin.y = newValue.y - (size.height / 2) } } }
只讀屬性去失落get與set
屬性監督可使用willset和didset來處置
類型屬性有點像靜態變量,以static症結字聲明
struct SomeStructure { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { // 這裡前往一個 Int 值 } }
下標
類、構造體、列舉都可以有下標,它有像給它們增長了一個快捷方法,以下:
struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) println("3的6倍是\(threeTimesTable[6])") // 輸入 "3的6倍是18"
繼續
界說一個類
class Vehicle { var numberOfWheels: Int var maxPassengers: Int func description() -> String { return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers" } init() { numberOfWheels = 0 maxPassengers = 1 } }
繼續類
class Bicycle: Vehicle { init() { super.init() numberOfWheels = 2 } }
重寫屬性與辦法
class Car: Vehicle { var speed: Double = 0.0 override var speed: Double { get { return super.speed } set { super.speed = min(newValue, 40.0) } } init() { super.init() maxPassengers = 5 numberOfWheels = 4 } override func description() -> String { return super.description() + "; " + "traveling at \(speed) mph" } }
避免重寫,在辦法與屬性前加症結字@final,編譯時會失足
結構函數
聲明裡可以寫多個init,這有點像重載
struct Celsius { var temperatureInCelsius: Double = 0.0 init(fromFahrenheit fahrenheit: Double) { temperatureInCelsius = (fahrenheit - 32.0) / 1.8 } init(fromKelvin kelvin: Double) { temperatureInCelsius = kelvin - 273.15 } } let boilingPointOfWater = Celsius(fromFahrenheit: 212.0) // boilingPointOfWater.temperatureInCelsius 是 100.0 let freezingPointOfWater = Celsius(fromKelvin: 273.15) // freezingPointOfWater.temperatureInCelsius 是 0.0”
類的析構
有些處所叫反初始化,很別扭的名字哦
class Player { var coinsInPurse: Int init(coins: Int) { coinsInPurse = Bank.vendCoins(coins) } func winCoins(coins: Int) { coinsInPurse += Bank.vendCoins(coins) } deinit { Bank.receiveCoins(coinsInPurse) } } var player = Player(coins:200) player = nil //挪用deinit辦法
擴大
關於類、構造體、列舉,可以擴大它們的一切
class Player{ var age:Int } extension Player{ func repetitions(task: () -> ()) { for i in 0..self { task() } } }
協定
其實就是接口描寫
protocol SomeProtocol { var mustBeSettable: Int { get set } var doesNotNeedToBeSettable: Int { get } func someTypeMethod() }
協定繼續
protocol InheritingProtocol: SomeProtocol, AnotherProtocol { // protocol definition goes here }
泛型
這個函數的泛型版本應用了節點類型定名(平日此情形下用字母T來表現)來取代現實類型名(如Int、String或Double)。節點類型名其實不是表現T必需是任何類型,然則其劃定a和b必需是統一類型的T,而不論T表現任何類型。只要swapTwoValues函數在每次挪用時所傳入的現實類型決議了T所代表的類型。
func swapTwoValues<T>(inout a: T, inout b: T) { let temporaryA = a a = b b = temporaryA }
運算符重載
這裡演示重載+號運算符
struct Vector2D { var x = 0.0, y = 0.0 } @infix func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) }
@prefix @assignment func ++ (inout vector: Vector2D) -> Vector2D { vector += Vector2D(x: 1.0, y: 1.0) return vector }
自界說運算符
特性的運算符只能應用這些字符 / = - + * % < >!& | ^。~
operator prefix +++ {} @prefix @assignment func +++ (inout vector: Vector2D) -> Vector2D { vector += vector return vector }
聯合性(associativity)的值默許為none,可用left,right,none,優先級(precedence)默許為100。
operator infix +- { associativity left precedence 140 } func +- (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y - right.y) } let firstVector = Vector2D(x: 1.0, y: 2.0) let secondVector = Vector2D(x: 3.0, y: 4.0) let plusMinusVector = firstVector +- secondVector // plusMinusVector 此時的值為 (4.0, -2.0)
來自:http://jser.me