Skip to content

Instantly share code, notes, and snippets.

View tranhieutt's full-sized avatar

Tran Trung Hieu tranhieutt

View GitHub Profile
let squaress = values.map {$0*$0}
@tranhieutt
tranhieutt / othermap.swift
Last active July 4, 2017 08:04
[Swift] - map - extension
let scores :[NSNumber] = [0,28,124]
let words = scores.map {NumberFormatter.localizedString(from: $0, number:.spellOut) }
print(words)
//Console: ["zero", "twenty-eight", "one hundred twenty-four"]
//
let milesToPoint = ["Point1":120.0,"Point2":45.0,"Point3":55.0]
let kmToPoint = milesToPoint.map{name,miles in miles*1.67}
//console: [200.39999999999998, 75.149999999999991, 91.849999999999994]
@tranhieutt
tranhieutt / filter.swift
Created July 4, 2017 08:10
[Swift] - Filter
let digits = [1,4,10,13]
let event = digits.filter { number -> Bool in
number % 2 == 0
}
//short way
let otherEvent = digits.filter {$0%2==0}
@tranhieutt
tranhieutt / reduce.swift
Created July 4, 2017 08:17
[Swift] - reduce
let items = [2.0, 4.0, 6.0, 8.0]
let total = items.reduce(10.0,+)
//Console: 30.0
/// Returns the result of combining the elements of the sequence using the
/// given closure.
///
/// Use the `reduce(_:_:)` method to produce a single value from the elements
/// of an entire sequence. For example, you can use this method on an array
/// of numbers to find their sum or product.
///
/// The `nextPartialResult` closure is called sequentially with an
/// accumulating value initialized to `initialResult` and each element of
/// the sequence. This example shows how to find the sum of an array of
@tranhieutt
tranhieutt / reduce.swift
Created July 4, 2017 08:24
[Swift] - reduce
let addItem = ["abc","f","a"]
let csv = addItem.reduce("zyz") { (text, name) -> String in
"\(text),\(name)"
}
//Console: zyz,abc,f,a
@tranhieutt
tranhieutt / flatMap.swift
Created July 4, 2017 08:29
[Swift] - flatmap
let collections = [[5,3,6],[5,6,8]]
let flat = collections.flatMap {$0}
print(flat)
//Console: [5, 3, 6, 5, 6, 8]
//Remove optional
let peple : [String?] = ["Tom", nil,"Teddy", nil]
let valid = peple.flatMap{$0}
//Console: ["Tom", "Teddy"]
@tranhieutt
tranhieutt / flatMapfilter.swift
Last active July 4, 2017 08:46
[Swift] - flapMap combine filter
//1. flapMap vs filter
let otherCollection = [[5,6,4],[5,8],[9,8,7]]
let onlyEven = otherCollection.flatMap { intArray in
intArray.filter({$0%2 == 0})
}
print(onlyEven)
//Console: [6, 4, 8, 8]
//or short-way
let onlyEventShort = otherCollection.flatMap{$0.filter{$0%2 == 0}}
@tranhieutt
tranhieutt / protocol(basic).swift
Created July 7, 2017 08:21
[Swift] - protocol(basic)
protocol Area {
var area: Double {get}
}
struct Square: Area {
let side: Double
var area: Double {
return side*side
}
}
struct Triangle: Area {
let base: Double
let height: Double