swiftSwift相关学习中的Swift

Swift 中的一句话干一件事

2016-03-30  本文已影响844人  NinthDay

1 对数组中所有元素进行加倍操作

(1...1024).map{$0 * 2}

2 对数组所有元素进行求和

(1...<1024).reduce(0,combine:+)// 0为初始值 + 为闭包操作简写

3 验证字符串中是否存在某个子串

复杂版本:

let words = ["Swift","iOS","cocoa","OSX","tvOS"]
let tweet = "This is an example tweet larking about Swift"

let valid =  !words.filter({tweet.containsString($0)}).isEmpty
valid // true

对map,reduce,filter函数底层实现不够了解,请点击我写的Why coding like this 系列文章

想了想,还是对上面这个例子简单介绍下,首先我们使用filter函数,顾名思义就是进行“过滤”操作,过滤的条件就是tweet.containsString($0) ,即tweet字符串包含$0,问题又来了,$0表示什么?了解过闭包的童鞋应该知道,即传入闭包的第一个参数,也就是遍历数组的当前元素;words.filter({tweet.containsString($0)})会返回满足条件的所有元素组成的集合,调用isEmpty确认集合是否为空,!取反。

简明版本:

words.contains(tweet.containsString) 
//或者先对tweet字符串进行操作
tweet.characters
  .split(" ")
  .lazy
  .map(String.init)
  .contains(Set(words).contains)

4 读取文件

let path = NSBundle.mainBundle().pathForResource("test", ofType: "txt")

// 先读取文件到String 中,然后通过换行`\n`来分割字符串到数组中
let lines = try? String(contentsOfFile: path!).characters.split{$0 == "\n"}.map(String.init)
if let lines=lines {
    lines[0] // O! for a Muse of fire, that would ascend
    lines[1] // The brightest heaven of invention!
    lines[2] // A kingdom for a stage, princes to act
    lines[3] // And monarchs to behold the swelling scene.
}

5 生日快乐

let name = "uraimo"
(1...4).forEach{print("Happy Birthday " + (($0 == 3) ? "dear \(name)":"to You"))}

6 屏蔽数组中满足特定条件的元素

extension SequenceType{
    typealias Element = Self.Generator.Element
    
    func partitionBy(fu: (Element)->Bool)->([Element],[Element]){
        var first=[Element]()
        var second=[Element]()
        for el in self {
            if fu(el) {
                first.append(el)
            }else{
                second.append(el)
            }
        }
        return (first,second)
    }
}

let part = [82, 58, 76, 49, 88, 90].partitionBy{$0 < 60}
part // ([58, 49], [82, 76, 88, 90])

以上方法并非是一句话哦,所以还要寻求另外的方式:


extension SequenceType{
    
    func anotherPartitionBy(fu: (Self.Generator.Element)->Bool)->([Self.Generator.Element],[Self.Generator.Element]){
        return (self.filter(fu),self.filter({!fu($0)}))
    }
}

let part2 = [82, 58, 76, 49, 88, 90].anotherPartitionBy{$0 < 60}
part2 // ([58, 49], [82, 76, 88, 90])

基本满足,但是效率不行,因为遍历了数组两次。

下面依靠reduce方法进行操作:

var part3 = [82, 58, 76, 49, 88, 90].reduce( ([],[]), combine: {
    (a:([Int],[Int]),n:Int) -> ([Int],[Int]) in
    (n<60) ? (a.0+[n],a.1) : (a.0,a.1+[n]) 
})
part3 // ([58, 49], [82, 76, 88, 90])

7 从服务器获取XML文件并解析

其实也可以是获取JSON文件并解析,童鞋们可自行尝试

let xmlDoc = try? AEXMLDocument(xmlData: NSData(contentsOfURL: NSURL(string:"https://www.ibiblio.org/xml/examples/shakespeare/hen_v.xml")!)!)

if let xmlDoc=xmlDoc {
    var prologue = xmlDoc.root.children[6]["PROLOGUE"]["SPEECH"]
    prologue.children[1].stringValue // Now all the youth of England are on fire,
    prologue.children[2].stringValue // And silken dalliance in the wardrobe lies:
    prologue.children[3].stringValue // Now thrive the armourers, and honour's thought
    prologue.children[4].stringValue // Reigns solely in the breast of every man:
    prologue.children[5].stringValue // They sell the pasture now to buy the horse,
}

8 找到列表中最大或最小值

//Find the minimum of an array of Ints
[10,-22,753,55,137,-1,-279,1034,77].sort().first
[10,-22,753,55,137,-1,-279,1034,77].reduce(Int.max, combine: min)
[10,-22,753,55,137,-1,-279,1034,77].minElement()

//Find the maximum of an array of Ints
[10,-22,753,55,137,-1,-279,1034,77].sort().last
[10,-22,753,55,137,-1,-279,1034,77].reduce(Int.min, combine: max)
[10,-22,753,55,137,-1,-279,1034,77].maxElement()

9 并行操作

该特性在swift并不可行,但是可以使用GCD来构建。

10 Sieve of Erathostenes

reversed

11 不适用临时变量进行交换两个数

除了加减法,乘数法和异或法,swift只需要元组即可简单实现.......

var a=1,b=2

(a,b) = (b,a)
a //2
b //1

参考文章:10 Swift One Liners To Impress Your Friends

上一篇下一篇

猜你喜欢

热点阅读