β

swift高级特性一瞥

Kingiol Ding 131 阅读
// Playground - noun: a place where people can play

import UIKit

// 1
func swap<T>(inout a: T, inout with b: T) {
    (a, b) = (b, a)
}

var a = "Marin", b = "Todorov"
swap(&a, &b)
[a, b]
// 2
func flexStrings(s1: String = "", s2: String = "") -> String {
    return s1 + s2 == "" ? "none" : s1 + s2
}

flexStrings()
flexStrings(s1: "hello")
flexStrings(s1: "hello", s2: "world")
// 3
func sumAny(anys: Any...) -> String {
    return String((anys.map({item in
        switch item {
        case "" as String, 0 as Int:
            return -10
        case let s as String where s.toInt() > 0:
            return s.toInt()!
        case is Int:
            return item as Int
        default:
            return 0
        }
        }) as [Int]).reduce(0) {
            $0 + $1
        })
}

sumAny()
sumAny(Double(), 10, "-10", 2)
sumAny("Marin Todorow", 2, 22, "-3", "10", "", 0, 33, -5)
// 4
func countFrom(from: Int, #to: Int) {
    print(from)
    if from < to {
        countFrom(from + 1, to: to)
    }
}
countFrom(1, to: 5)
// 5
func reverseString(input: String, output: String = "") -> String {
    if input.isEmpty {
        return output
    }else {
        return reverseString(
        input.substringToIndex(input.endIndex.predecessor()),
        output: output + input.substringFromIndex(input.endIndex.predecessor()))
    }
}
reverseString("Marin Todorov")
// 6
func charMult(char: Character, result: String, length: Double) -> String {
    if Int64(countElements(result)) < Int64(length) {
        return charMult(char, result+char, length)
    }else {
        return result
    }
}

@infix func * (left: Character, right: Double) -> String {
    return charMult(left, "", right)
}

"-" * 10 + ">"
"%" + "-" * 6
"Z" * 20
// 7
func doWork() -> Bool {
    return arc4random() % 10 > 5
}

func reportSuccess() -> Bool {
    println("success!")
    return true
}

func reportError() -> Bool {
    println("error")
    return true
}

doWork() && reportSuccess() || reportError()
// 8
extension Array {

    func swapElementAtIndex(index: Int) -> (Int -> Array) {
        return { withIndex in
            var result = self
            if index < self.count && withIndex < self.count {
                (result[index], result[withIndex]) = (result[withIndex], result[index])
            }
            return result
        }
    }

    var arrayWithElementAtIndexToFront:(Int) -> Array {
        return swapElementAtIndex(0 as Int)
    }

    var arrayWithElementAtIndexToBack: (Int) -> Array {
        return swapElementAtIndex((self.count - 1) as Int)
    }

}

let list = [1, 4, 5, 6, 20, 50]
list.arrayWithElementAtIndexToBack(2)
list.arrayWithElementAtIndexToFront(4)
// 9
enum Suit {
    case Clubs, Diamonds, Hearts, Spades
}

enum Rank {
    case Jack, Queen, King, Ace
    case Num(Int)
}

struct Card {
    let suit: Suit
    let rank: Rank
}

func countHand(cards: [Card], previousCard: Card = Card(suit: Suit.Spades, rank: Rank.Num(0))) -> Int {
    if cards.isEmpty { return 0 }

    let fn: () -> Int = { return countHand(Array(dropFirst(cards)), previousCard: cards[0]) }
    switch (previousCard.suit, previousCard.rank, cards[0].suit, cards[0].rank) {
    case (Suit.Diamonds, Rank.Num(5), _, Rank.Ace):
        return 100 + fn()
    case (Suit.Hearts, _, _, Rank.Num(let a)) where a % 2 == 1:
        return a * 2 + fn()
    default:
        return fn()
    }
}

countHand([
    Card(suit:Suit.Hearts, rank:Rank.Num(10)),
    Card(suit:Suit.Hearts, rank:Rank.Num(6)),
    Card(suit:Suit.Diamonds, rank:Rank.Num(5)),
    Card(suit:Suit.Clubs, rank:Rank.Ace),
    Card(suit:Suit.Diamonds, rank:Rank.Jack)
    ])
作者:Kingiol Ding
原文地址:swift高级特性一瞥, 感谢原作者分享。

发表评论