Created
October 24, 2016 06:26
-
-
Save xiangzhuyuan/c3d4a7a7ee04ebbe261c16475a30bb6c to your computer and use it in GitHub Desktop.
A tour of swift3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //: Playground - noun: a place where people can play | |
| import UIKit | |
| var str = "Hello, playground" | |
| print("hello world") | |
| // -- | |
| var myVariable = 42 | |
| myVariable = 52 | |
| let myConstants = 42 | |
| // -- | |
| let implicitInteger = 32 | |
| let implicitDouble = 32.2 | |
| let explicitDouble:Double = 22.2 | |
| // -- | |
| let label = "this is a label " | |
| let width = 92 | |
| let widthLabel = label + String(width) | |
| // -- | |
| let apples = 3 | |
| let oranges = 5 | |
| let friuts = "I have \(apples + oranges) fruits!" | |
| var shoppingList = ["catfish", "water", "tuplis"] | |
| shoppingList[0] == "catfish" | |
| shoppingList[0] = "catfish1" | |
| var occupations = [ | |
| "a":"aaa", | |
| "b": "bbb" | |
| ] | |
| occupations["a"] | |
| // -- | |
| let emptyArray = [String]() | |
| var emptyDic = [String: Float]() | |
| emptyDic["a"] = 1.1 | |
| emptyDic | |
| // -- | |
| let individualScores = [33,44,66,33] | |
| var teamScore = 0 | |
| for score in individualScores { | |
| if score > 30{ | |
| teamScore += 1 | |
| }else{ | |
| teamScore += Int(0.5) | |
| } | |
| } | |
| print(teamScore) | |
| // -- | |
| // use if and let together, to work wuth values that might be missing | |
| // question mark after type -> optional | |
| var optionalString: String? = "hello" | |
| print(optionalString == nil) | |
| var optionalName: String? = nil | |
| //var optionalName: String? = "John apple" | |
| var greeting = "hello!" | |
| if let name = optionalName{ | |
| greeting = "hello, \(name)" | |
| } | |
| // -- | |
| // optional value default value | |
| let nickName: String? = nil | |
| let fullNmae: String = "John" | |
| let informalGreeting = "Hi \(nickName ?? fullNmae)" | |
| // -- | |
| let vegetable = "red pepper" | |
| switch vegetable{ | |
| case "celery": | |
| print("hi") | |
| case "hsit": | |
| print("b") | |
| case "shifdf": | |
| print("xxc") | |
| default: | |
| print("default") | |
| } | |
| let interestingNumbers = [ | |
| "Prime": [2,3,5,7,11,13], | |
| "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) | |
| // -- | |
| var n = 2 | |
| while n < 100 { | |
| n = n * 2 | |
| } | |
| print(n) | |
| var m = 2 | |
| repeat{ | |
| m = m * 2 | |
| }while m < 100 | |
| print(m) | |
| // -- | |
| var total = 0 | |
| for i in 0..<4 { | |
| total += 1 | |
| } | |
| print(total) | |
| // -- | |
| func greet(person: String, day: String) -> String { | |
| return "hello, \(person), today is \(day)" | |
| } | |
| greet(person: "Bod", day: "Tuesday") | |
| // -- | |
| func greet(_ person:String, on day:String)->String{ | |
| return "Hello \(person), today is \(day)" | |
| } | |
| greet("xiang", on: "Sunday") | |
| //error: argument labels '(_:, _:)' do not match any available overloads | |
| //greet("marshal", "sunday") | |
| // -- | |
| func calculateStatistics(scores: [Int]) -> (min:Int, max:Int, sum:Int){ | |
| var min = scores[0] | |
| var max = scores[0] | |
| var sum = 0 | |
| for score in scores{ | |
| if score > max{ | |
| max = score | |
| }else if score < min{ | |
| min = score | |
| } | |
| sum += score | |
| } | |
| return (min,max,sum) | |
| } | |
| let statistics = calculateStatistics(scores: [5,3,100,9]) | |
| print(statistics.max) | |
| print(statistics.2) | |
| // -- | |
| func sumOF(numbers: Int...)->Int{ | |
| var sum = 0 | |
| for number in numbers{ | |
| sum += number | |
| } | |
| return sum | |
| } | |
| sumOF() | |
| sumOF(numbers: 3,3,4,5,6,7) | |
| // -- | |
| func returnFifteen() -> Int{ | |
| var y = 100 | |
| func add(){ | |
| y += 5 | |
| } | |
| add() | |
| return y | |
| } | |
| returnFifteen() | |
| func makeInrement()->((Int) -> Int){ | |
| func addOne(number:Int)-> Int{ | |
| return 1 + number | |
| } | |
| return addOne | |
| } | |
| var increment = makeInrement() | |
| increment(11) | |
| // -- | |
| func hasAnyMathes(list: [Int], condition:(Int)->Bool) -> Bool{ | |
| for item in list { | |
| if condition(item){ | |
| return true | |
| } | |
| } | |
| return false | |
| } | |
| func lessThenTen(number:Int) -> Bool{ | |
| return number < 10 | |
| } | |
| var numbers = [20,3,19,7] | |
| hasAnyMathes(list: numbers, condition: lessThenTen) | |
| // -- | |
| numbers.map({ | |
| (number: Int) -> Int in | |
| let result = 3 * number | |
| return result | |
| }) | |
| let mappedNumbers = numbers.map({number in 3*number}) | |
| print(mappedNumbers) | |
| // -- | |
| let sortedNumbers = numbers.sorted { $0 > $1} | |
| print(sortedNumbers) | |
| // -- | |
| class Shape{ | |
| var numberOfSlides = 0 | |
| func simpleDescription() -> String { | |
| return "A shape with \(numberOfSlides) sides." | |
| } | |
| var name:String | |
| init(_ name:String){ | |
| self.name = name | |
| } | |
| } | |
| var shape = Shape("") | |
| shape.numberOfSlides = 8 | |
| print(shape.simpleDescription()) | |
| class Square : Shape{ | |
| var s_name: String | |
| override init(_ name: String) { | |
| self.s_name = name | |
| super.init(name) | |
| } | |
| var sideLength: Double = 0.0 | |
| init(sideLength:Double, name:String){ | |
| self.s_name = name | |
| self.sideLength = sideLength | |
| super.init(name) | |
| numberOfSlides = 3 | |
| } | |
| var perimeter: Double { | |
| get{ | |
| return 3.0 * sideLength | |
| } | |
| set{ | |
| sideLength = newValue / 3.0 | |
| } | |
| } | |
| override func simpleDescription() -> String { | |
| return "this is a override" | |
| } | |
| } | |
| var square = Square("Square") | |
| print(square.simpleDescription()) | |
| // -- | |
| class TrianglesAndSquare { | |
| var square:Square{ | |
| willSet{ | |
| square.sideLength = newValue.sideLength | |
| } | |
| } | |
| init(size:Double,name:String){ | |
| square = Square(sideLength: size, name: name) | |
| } | |
| } | |
| var aSquare = TrianglesAndSquare( size:10, name: "this a squrea") | |
| print(aSquare.square.sideLength) | |
| enum Rank:Int{ | |
| case ace = 1 | |
| case two, three, four, five, six,seven,eight, nine ,ten | |
| case jack, queen,king | |
| func simpleDesc ()->String{ | |
| switch self{ | |
| case .ace: | |
| return "ace" | |
| case .jack: | |
| return "jack" | |
| case .queen: | |
| return "queen" | |
| case .king: | |
| return "king" | |
| default: | |
| return String(self.rawValue) | |
| } | |
| } | |
| } | |
| let ace = Rank.ace | |
| let aceRawValue = ace.rawValue | |
| Rank.eight | |
| Rank.eight.rawValue | |
| if let convertedRank = Rank(rawValue: 3) | |
| { | |
| let threeDescription = convertedRank.simpleDesc() | |
| } | |
| enum Suit{ | |
| case spades, hears, diamonds, clubs | |
| func simpleDescription()->String{ | |
| switch self { | |
| case .spades: | |
| return "spades" | |
| case .diamonds: | |
| return "diamonds" | |
| case .hears: | |
| return "hearts" | |
| case .clubs: | |
| return "club" | |
| } | |
| } | |
| } | |
| let hearts = Suit.hears | |
| let heartsDesc = hearts.simpleDescription() | |
| // -- | |
| struct Card { | |
| var rank:Rank | |
| var suit:Suit | |
| func simpleDesc() -> String { | |
| return "The \(rank.simpleDesc()) of \(suit.simpleDescription())" | |
| } | |
| } | |
| let threeOfSpades = Card(rank:.three, suit:.spades) | |
| let threeOfSpadesDescription = threeOfSpades.simpleDesc() | |
| // -- Protocols and Extensions | |
| protocol ExampleProtocol { | |
| var simpleDesc: String { get } | |
| mutating func adjust() | |
| } | |
| // -- | |
| class SimpleClass:ExampleProtocol{ | |
| func adjust() { | |
| simpleDesc += " 100% now adjusted" | |
| } | |
| var simpleDesc: String = "A very simple Desc" | |
| var anotherProp: Int = 60043 | |
| } | |
| var a = SimpleClass() | |
| a.adjust() | |
| let aDesc = a.simpleDesc | |
| // -- | |
| struct SimpleStrucure:ExampleProtocol{ | |
| var simpleDesc: String = "a simple structure" | |
| mutating func adjust() { | |
| simpleDesc += " (adjusted)" | |
| } | |
| } | |
| var b = SimpleStrucure() | |
| b.adjust() | |
| let bDesc = b.simpleDesc | |
| // -- | |
| enum SimpleEnum:ExampleProtocol{ | |
| case base, shit | |
| var simpleDesc: String { | |
| return self.getDesc() | |
| } | |
| mutating func adjust() { | |
| self = SimpleEnum.shit | |
| } | |
| func getDesc()-> String{ | |
| switch self{ | |
| case .base: | |
| return "aaaaa" | |
| case .shit: | |
| return "bbbbb" | |
| } | |
| } | |
| } | |
| var aE = SimpleEnum.base | |
| //aE.adjust() | |
| let aD = aE.simpleDesc | |
| var aB = SimpleEnum.shit | |
| //aB.adjust() | |
| let aBB = aB.simpleDesc | |
| // --- | |
| extension Int: ExampleProtocol{ | |
| mutating internal func adjust() { | |
| self += 42 | |
| } | |
| internal var simpleDesc: String { | |
| return "the number of \(self)" | |
| } | |
| } | |
| print (7.simpleDesc) | |
| // -- | |
| // | |
| //do { | |
| // try <#throwing expression#> | |
| //} catch <#pattern#> { | |
| // <#statements#> | |
| //} | |
| enum PrinterError:Error{ | |
| case outOFPaper | |
| case noToner | |
| case onFire | |
| } | |
| func send(job:Int, toPrinter printerNmae:String) throws ->String{ | |
| if printerNmae == "Never has toner"{ | |
| throw PrinterError.noToner | |
| } | |
| return "job sent" | |
| } | |
| do { | |
| let printerRsponse = try send(job: 1040, toPrinter: "bi sheng") | |
| print(printerRsponse) | |
| } catch{ | |
| print(error) | |
| } | |
| do { | |
| let printerRsponse = try send(job: 1040, toPrinter: "Never has toner") | |
| print(printerRsponse) | |
| } catch PrinterError.onFire { | |
| print(" on fire") | |
| } catch { | |
| print(error) | |
| } | |
| // -- | |
| let printSuccess = try? send(job:1884, toPrinter: "Mergenthaler") | |
| let printFailure = try? send(job:1885, toPrinter: "Never has toner") | |
| // - | |
| var fridgeIsOpen = false | |
| let fridgeContent = ["Milk", "Eggs","leftovers"] | |
| func fridgeContains(_ food:String) -> Bool{ | |
| fridgeIsOpen = true | |
| defer { | |
| fridgeIsOpen = false | |
| } | |
| let result = fridgeContent.contains(food) | |
| return result | |
| } | |
| fridgeContains("bannana") | |
| print(fridgeIsOpen) | |
| // -- | |
| func makeArray<Item>(repeating item:Item, numberOfTimes: Int)->[Item]{ | |
| var result = [Item]() | |
| for _ in 0..<numberOfTimes { | |
| result.append(item) | |
| } | |
| return result | |
| } | |
| makeArray(repeating: "knock", numberOfTimes: 4) | |
| enum OptionalValue<Wrapped> { | |
| case none | |
| case some(Wrapped) | |
| } | |
| var possibleInteger: OptionalValue<Int> = .none | |
| possibleInteger = .some(100) | |
| // -- | |
| func anyCommonElements<T: Sequence, U:Sequence>(_ lhs: T, _ rhs:U)-> Bool | |
| where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element { | |
| for lhsItem in lhs { | |
| for rhsItem in rhs { | |
| if lhsItem == rhsItem { | |
| return true | |
| } | |
| } | |
| } | |
| return false | |
| } | |
| anyCommonElements([1,2,3], [3]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment