Skip to content

Instantly share code, notes, and snippets.

@thanhluu
Last active May 26, 2016 15:16
Show Gist options
  • Save thanhluu/565c82e47833bcf6f26bcc9f8555dc0c to your computer and use it in GitHub Desktop.
Save thanhluu/565c82e47833bcf6f26bcc9f8555dc0c to your computer and use it in GitHub Desktop.
Standard Library Functions
let values = [1,2,3,4,5]
var newArray = [Int]()
for number in values {
newArray.append(number * 2)
}
let tripledValues = values.map { $0 * 3 }
// Map
extension Array {
func map<T>(transform: Element -> T) -> [T] {
var result = [T]()
for x in self {
result.append(transform(x))
}
return result
}
}
let intergerValues = ["1", "2", "3", "a", "4"].map { Int($0) }
import Foundation
struct Formatter {
static let formatter = NSDateFormatter()
static func dateFromString(dateString: String) -> NSDate? {
formatter.dateFormat = "d MMM yyyy"
return formatter.dateFromString(dateString)
}
}
let dateStrings = ["10 Oct 1988", "11 Jan 1947", "28 Mar 2002"]
let dates = dateStrings.map { Formatter.dateFromString($0) }
// Flat Map
struct Post {
var content: String
var tags: [String]
}
let blog = [
Post(content: "Hello, world!", tags: ["first", "programming"]),
Post(content: "Just another short post", tags: ["general"])
]
blog.map { $0.content }
let tags = blog.map { $0.tags }
let flattenedTags = blog.flatMap { $0.tags }
extension Array {
func flatMap<T>(transform: Element -> [T]) -> [T] {
var result = [T]()
for x in self {
result.appendContentsOf(transform(x))
}
return result
}
}
// Example 2
import UIKit
struct Account {
let username: String
let billingAddress: String?
}
let allUsers = [
Account(username: "pasanpr", billingAddress: nil),
Account(username: "benjakuben", billingAddress: "1234 Imaginary Street"),
Account(username: "instantNadel", billingAddress: "5678 Doesn't Live Here Dr."),
Account(username: "sketchings", billingAddress: nil),
Account(username: "paradoxed", billingAddress: "1122 Nope Lane")
]
let validAddresses = allUsers.flatMap { $0.billingAddress }
validAddresses
// Filter
let evenNumbers = (0...100).filter { $0 % 2 == 0 }
evenNumbers
extension Array {
func filter(includeElement: Element -> Bool) -> [Element] {
var result = [Element]()
for x in self where includeElement(x) {
result.append(x)
}
return result
}
}
let pUser = allUsers.filter { $0.username.characters.first == "p" }
// Reduce
let scores = [10, 12, 11, 10, 12, 9]
let totalScore = scores.reduce(0, combine: {total, score in total + score })
extension Array {
func reduce<T>(inital: T, combine: (T, Element) -> T) -> T {
var result = inital
for x in self {
result = combine(result, x)
}
return result
}
}
let dataSet = (1...100).filter { $0 % 3 == 0 && $0 % 7 == 0 }
let identifier = dataSet.reduce("", combine: {str, num in str + "\(num)"})
identifier
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment