Swift初探
來自: http://my.oschina.net/xinxingegeya/blog/608514
?Swift初探
Xcode 7.2
下面swift一些基本的語法。把這些代碼寫下來,發現swift和一些語言很像,比如javascript和scala。如果對這些語言比較熟悉的話,一看代碼就會懂。
總的來說swift的語法還是比較fashion。好評~~~
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let name = "hello world" //編譯器會自動推斷類型,該類型是Int let implicitInt = 70 //編譯器會自動推斷類型,該類型是double let implicitDouble = 10.0 //定義一個常量,并指定類型為double let explicitDouble: Double = 70 let height:Float = 5 let label = "the width is" let width = 90 //值永遠不會被隱式轉換為其他類型,這里使用String 顯式轉換一個字符串 let widthLable = label + String(width) print(widthLable) let apples = 3 let oranges = 5 // \(apples)是一種簡單的方式來轉換字符串 let appliSummary = "I have \(apples) apples;" let fruitSummary = "I have \(apples + oranges) pieces of fruits;" //創建一個數組 let shoplist = ["catfish","water","tulips","blue paint"]; //使用[String]表明是一種數組類型 var shoppingList: [String] = ["Eggs", "Milk"] //使用下標來訪問數組元素 print(shoplist[1]) //創建一個空數組 let emptyArray = []; print(emptyArray) //創建一個空的數組 let emptyStringArray = [String]() print(emptyStringArray) let individualScores = [12,12,13,25] var teamScore = 0 //swift中基本的for循環控制流 for score in individualScores { if score > 13{ teamScore += 3 } else{ teamScore += 1 } } print(teamScore) //使用?表示該變量的值是可選的 var optionalString:String? = "hello" optionalString = nil var optionalName:String? = nil var greeting = "Hello!" //如果變量的可選值是 nil,條件會判斷為 false,大括號中的代碼會被跳過。如果不是nil, //會將值賦給 let 后面的常量,這樣代碼塊中就可以使用這個值了。 if let name = optionalName { greeting = "Hello,\(name)" } else { greeting = "Hello everyone" } //switch語法 let vegetable = "red pepper" switch vegetable{ case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber","watercress": let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" default: let vegetableComment = "Everything tastes good in soup." } let vegetable2 = "watercress" //switch必須有一個default switch vegetable2{ case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber","watercress": let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" default: let vegetableComment = "Everything tastes good in soup." } //定義字典數組 let interestingNumbers = [ "prime":[2,3,5,7], "fibonacci":[1,1,2,3,5,8], "square":[1,4,9,16,25] ] var largest = 0 //遍歷數組 //字典類型的元素需要兩個變量來表示每個鍵值對 for (kind,numbers) in interestingNumbers{ for number in numbers{ if number > largest{ largest = number } } } print(largest) //1...3 是 Closed Range Operator => 1 2 3 var sum = 0 for i in 1...3{ sum += i } print(sum) sum = 0 //1..<3 是 Half-Open Range Operator => 1 2 for i in 1..<3 { sum += i } print(sum) //函數的定義 //使用右向箭頭表示返回值 func greet(name:String, day:String) ->String{ return "Hello \(name),today is \(day)"; } greet("LiYi", day: "2016-1-1") greet("world",day: "2016-1-1") //函數返回類型為元組 func getGasPrices() -> (Double,Double,Double){ return (3.56,3.23,3.21) } getGasPrices() //swift的可變參數列表 func sumOf(numbers:Int...)->Int{ var sum = 0 for number in numbers{ sum += number } return sum } sumOf() sumOf(42,597,12) //在函數內部定義一個函數 func returnFifteen() -> Int { var y = 10 func add() { y += 5 } //調用函數內部的函數 add() return y } returnFifteen() //=========函數作為返回值 //定義一個函數,返回值是一個函數類型 //函數類型是 (Int -> Int) ,表示該函數接收一個入參Int,返回值是Int func makeIncrementer() -> (Int -> Int){ func addOne(number:Int)->Int{ return 1 + number } return addOne } var increment = makeIncrementer() increment(1) //定義一個函數 makeAdd ,其返回值也是一個函數類型, //(Int,Int) -> Int 表示返回類型,是一個接收兩個Int參數,返回Int的函數 func makeAdd()-> (Int,Int) -> Int { func add(a:Int ,b:Int) -> Int{ return a + b } return add; } var add = makeAdd() add(1,2) //=========函數作為參數 func hasAnyMatches(list:[Int],condition:Int -> Bool) -> Bool { for item in list{ if condition(item){ return true; } } return false } func lessThanTen(number:Int)->Bool{ return number < 10 } hasAnyMatches([20,19,7,12], condition: lessThanTen) var numbers = [20,19,7,12] //(number:Int) -> Int 是一個匿名閉包的入參和返回值 //使numbers數組中的元素都變成了三倍 numbers.map( { (number:Int) -> Int in let result = 3 * number return result } ) //map 函數 numbers.map( { (number:Int) -> Int in if number % 2==0{ let result = 3 * number return result } else { return 0 } } ) //filter 函數 numbers.filter({ (number:Int) -> Bool in return number % 2 == 0 }) //類的定義 class Shape{ //定義一個常量 let happy = true //定義一個變量 var numberOfSides = 0 func simpleDscription() -> String{ return "A shape with \(numberOfSides) sides" } func toHappy()->Bool{ return happy } } //創建類的實例 var shape = Shape() shape.numberOfSides = 10 shape.simpleDscription() shape.toHappy() //定義類的構造函數 class NamedShape{ var numberOfSides:Int = 0 var name: String //定義類的構造函數 init(name:String){ self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides" } } var namedShape = NamedShape(name: "hello world") namedShape.name namedShape.simpleDescription() //繼承 類的繼承 class Square : NamedShape{ var sideLength : Double init(sideLength: Double ,name :String){ self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double{ return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)" } } let test = Square(sideLength: 5.12, name: "my test square") test.area() test.simpleDescription() class EquilateralTriangle : NamedShape{ var sideLength : Double = 0.0 init(sideLength: Double, name: String){ self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } //定義屬性的setter 和 getter 方法 var perimeter : Double { get{ return 3.0 * sideLength } set{ sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triagle with sides of length \(sideLength)" } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") triangle.perimeter triangle.perimeter = 9.9 triangle.sideLength //定義一個類,類中有一個函數 class Counter { var count: Int = 0 //該方法的第二個參數有兩個參數名 //第一個參數名是numberOfTimes,給方法的外部調用者使用 //第二個參數名是times,給方法內部使用 func incrementBy(amount:Int,numberOfTimes times: Int){ count += amount * times } } //創建一個實例 var counter = Counter() counter.incrementBy(2, numberOfTimes: 7) //定義一個枚舉 //枚舉原始值的類型是Int,所以你只需要設置第一個原始值。 //剩下的原始值會按照順序賦值。你也可以使用字符串或者浮點數作為枚舉的原始值。 enum Rank: Int { //指定該枚舉實例的原始值為1 case Ace = 1 case Two ,Three ,Four , Five , Six ,Seven , Eight ,Nine ,Ten case Jack,Queen,King func simpelDescription() -> String{ switch self{ case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queue" case .King: return "king" default: return String(self.rawValue) } } } let ace = Rank.Ace //調用 rawValue 方法 let aceRawValue = ace.rawValue ace.simpelDescription() //定義不需要原始值的枚舉 enum Suit { case Spades,Hearts,Diamonds,Clubs func simepleDescription ()-> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsHashValue = hearts.hashValue let heartDescription = hearts.simepleDescription() //創建一個結構體 struct Card { var rank : Rank var suit : Suit func simpleDescription() -> String { return "The \(rank.simpelDescription()) of \(suit.simepleDescription())" } } //使用 struct 來創建一個結構體。 //結構體和類有很多相同的地方,比如方法和構造器。 //它們結構體之間最大的一個區別就是,結構體是傳值,類是傳引用。 let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() //該枚舉也不需要原始值 //一個枚舉成員的實例可以有實例值。 //相同枚舉成員的實例可以有不同的值。 //創建實例的時候傳入值即可。 //實例值和原始值是不同的:枚舉成員的原始值對于所有實例都是相同的 //而且你是在定義枚舉的時候設置原始值。 enum ServerResponse { case Result(String,String) case Error(String) } //創建一個枚舉值的實例 let success = ServerResponse.Result("6:00 am", "8:09 pm") //創建一個枚舉值的實例 let failure = ServerResponse.Error("out of cheese") //success是一個枚舉實例 switch success { case let .Result(sunrise, sunset): let serverResponse = "sunrise is at \(sunrise) and sunset is at \(sunset)" case let .Error(error): let serverResponse = "Failure...\(error)" } //============接口和擴展 //使用protocol來聲明一個接口 protocol ExampleProtocol{ var simpleDescription : String { get } mutating func adjust() } //類、枚舉和結構體都可以實現接口 class SimpleClass: ExampleProtocol{ var simpleDescription :String = "a very simple class" var anotherProperty : Int = 123 func adjust() { simpleDescription += " now 100% adjusted" } } var a = SimpleClass() a.adjust() let desc = a.simpleDescription //該結構體實現協議 struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "a very simple structure" //mutating 關鍵字用來標記一個會修改結構體的方法 mutating func adjust(){ simpleDescription += " (adjusted)" } } // 枚舉繼承協議 enum SimpleEnum: ExampleProtocol{ case First(String) case Second(String) //屬性的get方法 var simpleDescription:String{ get{ switch self{ case let .First(text): return text default: return "hi" } } } mutating func adjust(){ print("description: hi") } } var s = SimpleEnum.First("dingding") s.simpleDescription s.adjust() //使用 extension 來為現有的類型添加功能,比如添加一個計算屬性的方法。 //你可以使用擴展來給任意類型添加協議 //甚至是你從外部庫或者框架中導入的類型 extension Int : ExampleProtocol{ var simpleDescription : String { return "the number \(self)" } mutating func adjust() { self += 42 } } 7.simpleDescription // 定義一個泛型函數 func repeatItem<T>(item : T,times: Int) -> [T] { //定義一個空的數組 var result = [T]() for i in 0...times { //數組元素的追加 result.append(item) } return result } repeatItem(3, times: 4)
============END============
本文由用戶 seqn0777 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!