Swift学习(1)

2016-12-08  本文已影响0人  LeeTrombone
import UIKit

// repeat...while循环,相当于do...while
var m = 100
repeat {
    m = m * 2
} while m < 100
print(m)

// for...in循环
var total = 0
for i in 0 ..< 4 {
    total += i
}
print(total)

// 多个返回值的方法
func calculate(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 = calculate(scores: [5,3,25,33,2])
print(statistics.sum)
print(statistics.0)

// 传多个同类型的参数
func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf(numbers: 4,3,2,45,33)

// 方法中定义方法
func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
returnFifteen()

// 返回值是一个方法
func makeIncrement() -> ((Int) -> Int) {
    func addOne(number: Int) -> Int {
        return number + 1
    }
    return addOne
}
var increment = makeIncrement()
increment(7)

// 参数要传一个方法的方法
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
}
var numbers = [20, 9, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)

// 数组的map
numbers.map { (number: Int) -> Int in
    let result = 3 * number
    return result
}
let mappedNumers = numbers.map({ number in 3 * number})
print(mappedNumers)
let sortedNumbers = numbers.sort {$0 > $1}
print(sortedNumbers)

// 类
class NumberParser {
    func singleNumberToChinese(number: Character) -> String {
        switch number {
        case "0":
            return "零"
        case "1":
            return "一"
        case "2":
            return "二"
        case "3":
            return "三"
        case "4":
            return "四"
        case "5":
            return "五"
        case "6":
            return "六"
        case "7":
            return "七"
        case "8":
            return "八"
        case "9":
            return "九"
        default:
            return ""
        }
    }
}

// 类的实例化
let convertor = NumberParser()
let zeroString = convertor.singleNumberToChinese(number: "0")
print(zeroString)

// 变量
var string = "swift"
string = "Taylor"

// 类的继承
class NumbersParser: NumberParser {
    
    // 单例
    static let sharedInstance = NumbersParser()
    
    func numberToChinese(number: Int) -> String {
        let numbers = String(number).characters
        var finalString = ""
        for singleNumber in numbers {
            let string = singleNumberToChinese(number: singleNumber)
            finalString = "\(finalString)\(string)"
        }
        return finalString
    }
}

let conventor = NumbersParser()
let yearString = conventor.numberToChinese(number: 2016)
print(yearString)

// 单例用法
let numberString = NumbersParser.sharedInstance.numberToChinese(number: 1234)
print(numberString)

// 类的重载
class YearParser: NumbersParser {
    static let sharedYearParserInstance = YearParser()
    
    override func numberToChinese(number: Int) -> String {
        let numbersString = super.numberToChinese(number: number)
        return "\(numbersString) 年"
    }
}

let yearStr = YearParser.sharedYearParserInstance.numberToChinese(number: 2016)
print(yearStr)

// protocol
protocol SleepDelegate {
    func canISleep() -> Bool
}

class Cat {
    // ?表示delegate并不一定存在
    var delegate: SleepDelegate?
    
    func wantToSleep() {
        // 首先对其进行拆包,只有delegate这个属性真的存在的时候,才能通过拆包
        if let delegate = delegate {
            if delegate.canISleep() {
                print("Go To Sleep")
            } else {
                print("NO")
            }
        }
    }
}

class Human: SleepDelegate {
    func canISleep() -> Bool {
        return false
    }
}

let myCat = Cat()
myCat.delegate = Human()
myCat.wantToSleep()

// enum枚举
enum China: Int {
    
    case Beijing = 0
    case Shanghai
    
    var description: String {
        switch self {
        case .Beijing:
            return "北京"
        case .Shanghai:
            return "上海"
        }
    }
    
}

class City {
    var name = China.Beijing
}

let beijing = City()
print(beijing.name.description)

// 直接输出enum的值
print(China.Shanghai.description)
// 类
class Shape {
    var numberOfSides = 0
    var name: String
    init(name: String) {
        self.name = name
    }
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}
var shape = Shape(name: "square")
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
print(shapeDescription)
print(shape.name)

class Square: Shape {
    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.3, name: "square")
test.area()
test.simpleDescription()

class EquilateralTriangle: Shape {
    var sideLength: Double = 0.0
    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 3
    }
    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
            sideLength = newValue / 3.0
        }
    }
    override func simpleDescription() -> String {
        return "An equilateral triangle with sides of length \(sideLength)"
    }
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)

class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }
    
    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)

let optionalSquare: Square? = Square(sideLength: 2.5, name: "Optional Square")
let sideLength = optionalSquare?.sideLength
// 枚举
enum Rank: Int {
    case ace = 1
    case two, three, four, five, sex, seven, eight, nine, ten
    case jack, queen, king
    
    func simpleDescription() -> 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

if let convertedRank = Rank(rawValue: 3) {
    let threeDescription = convertedRank.simpleDescription()
}

enum Suit {
    case spades, hearts, diamonds, clubs
    func simpleDescription() -> String {
        switch self {
        case .spades:
            return "spades"
        case .hearts:
            return "hearts"
        case .diamonds:
            return "diamonds"
        case .clubs:
            return "clubs"
        }
    }
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()

enum ServerResponse {
    case result(String, String)
    case failure(String)
}
let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("out of cheese")
switch failure {
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset)")
case let .failure(message):
    print("Failure... \(message)")
}
// 结构体
struct Card {
    var rank: Rank
    var suit: Suit
    
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}

let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
// 协议protocol
protocol ExampleProtocol {
    var simpleDescription: String {get}
    mutating func adjust()
}

class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class"
    var anthorProperty: Int = 69105
    func adjust() {
        simpleDescription += " Now 100% adjusted."
    }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription

struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    
    mutating func adjust() {
        self += 42
    }
}
print(7.simpleDescription)
var seven = 7
seven.adjust()

let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
// 异常
enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire
}

func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    }
    return " Job sent"
}

do {
    let printerResponse = try send(job: 1040, toPrinter: "Never Has Toner")
    print(printerResponse)
} catch PrinterError.onFire {
    print("I'll just put this over here, with the rest of the fire")
} catch let printerError as PrinterError {
    print("Printer error: \(printerError)")
} catch {
    print(error)
}

let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = 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(food: "banana")
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(lhs: [1, 2, 3], [3])

let minValue = Int16.min
let maxValue = UInt8.max

let justOverOneMillion = 1_000_000.000_000_1

typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min

let http404Error = (404, "Not Found")

let possibleString: String? = "An optional string."
let forcedString: String = possibleString!

let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString
上一篇下一篇

猜你喜欢

热点阅读