Skip to content

Instantly share code, notes, and snippets.

@kingcos
Last active January 12, 2018 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingcos/31443fdd91b9ef34429e0fb54fa3f7a7 to your computer and use it in GitHub Desktop.
Save kingcos/31443fdd91b9ef34429e0fb54fa3f7a7 to your computer and use it in GitHub Desktop.
Swifter Tips - 1 - Notes: http://www.jianshu.com/p/85dbf5a524e8
import UIKit
func addTo(_ adder: Int) -> (Int) -> Int {
return {
num in
return num + adder
}
}
func greaterThan(_ comparer: Int) -> (Int) -> Bool {
return { $0 > comparer }
}
let addTwo = addTo(2)
print(addTwo(10))
let greaterThan10 = greaterThan(10)
print(greaterThan10(10))
// OUTPUT:
// 12
// false
// Target-Action
protocol TargetAction {
func performAction()
}
struct TargetActionWrapper<T: AnyObject>: TargetAction {
weak var target: T?
let action: (T) -> () -> ()
func performAction() {
if let t = target {
action(t)()
}
}
}
enum ControlEvent {
case touchUpInside
case valueChanged
// ...
}
class Control {
var actions = [ControlEvent : TargetAction]()
func setTarget<T: AnyObject>(_ target: T, action: @escaping (T) -> () -> (), controlEvent: ControlEvent) {
actions[controlEvent] = TargetActionWrapper(target: target, action: action)
}
func removeTargetForControlEvent(_ controlEvent: ControlEvent) {
actions[controlEvent] = nil
}
func performActionForControlEvent(_ controlEvent: ControlEvent) {
actions[controlEvent]?.performAction()
}
}
import UIKit
class ReverseIterator<T>: IteratorProtocol {
typealias Element = T
var array: [Element]
var currentIndex = 0
init(_ array: [Element]) {
self.array = array
currentIndex = array.count - 1
}
func next() -> Element? {
if currentIndex < 0 {
return nil
} else {
let element = array[currentIndex]
currentIndex -= 1
return element
}
}
}
struct ReverseSequence<T>: Sequence {
typealias Iterator = ReverseIterator<T>
var array: [T]
init(_ array: [T]) {
self.array = array
}
func makeIterator() -> Iterator {
return Iterator(array)
}
}
let array = [0, 1, 2, 3, 4]
for i in ReverseSequence(array) {
print(i)
}
// OUTPUT:
// 4
// 3
// 2
// 1
// 0
var iterator = ReverseSequence(array).makeIterator()
while let obj = iterator.next() {
print(obj)
}
// OUTPUT:
// 4
// 3
// 2
// 1
// 0
import UIKit
func logIfTrue(_ predicate: () -> Bool) {
if predicate() {
print("True")
}
}
logIfTrue { () -> Bool in
return 2 > 1
}
logIfTrue { return 2 > 1 }
logIfTrue { 2 > 1 }
func logIfTrue(_ predicate: @autoclosure () -> Bool) {
if predicate() {
print("True")
}
}
logIfTrue(2 > 1)
var level: Int?
var startLevel = 1
// func ??<T>(optional: T?, defaultValue: @autoclosure () throws -> T) rethrows -> T
// func ??<T>(optional: T?, defaultValue: @autoclosure () throws -> T?) rethrows -> T?
var currentLevel = level ?? startLevel
// func &&(lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows -> Bool
// func ||(lhs: Bool, rhs: @autoclosure () throws -> Bool) rethrows -> Bool
var valueA = true && false
var valueB = true || false
import UIKit
func doWork(block: () -> ()) {
block()
}
//doWork {
// print(#function)
//}
func doWorkAsync(_ block: @escaping () -> ()) {
DispatchQueue.main.async {
block()
}
}
class S {
var foo = "foo"
func method1() {
doWork {
print(foo)
}
foo = "bar"
}
func method2() {
doWorkAsync {
print(self.foo)
}
foo = "bar"
}
func method3() {
doWorkAsync {
[weak self] in
print(self?.foo ?? "nil")
}
foo = "bar"
}
}
//S().method1()
//S().method2()
S().method3()
protocol P {
func work(b: @escaping () -> ())
}
class C: P {
func work(b: @escaping () -> ()) {
DispatchQueue.main.async {
print("in C")
b()
}
}
}
import UIKit
func incrementor(variable: inout Int) -> Int {
variable += 1
return variable
}
var luckyNumber = 7
incrementor(variable: &luckyNumber)
print(luckyNumber)
func makeIncrementor(addNumber: Int) -> ((inout Int) -> ()) {
func incrementor(variable: inout Int) -> () {
variable += addNumber
}
return incrementor
}
let addFive = makeIncrementor(addNumber: 5)
addFive(&luckyNumber)
print(luckyNumber)
// OUTPUT:
// 8
// 13
import UIKit
extension Array {
subscript(input: [Int]) -> ArraySlice<Element> {
get {
var result = ArraySlice<Element>()
for i in input {
assert(i < self.count, "Index out of range")
result.append(self[i])
}
return result
}
set {
for (index, i) in input.enumerated() {
assert(i < self.count, "Index out of range")
self[i] = newValue[index]
}
}
}
}
var arr = [1, 2, 3, 4, 5]
print(arr[[0, 2, 3]])
// OUTPUT:
// [1, 3, 4]
import UIKit
struct Person<T> {}
typealias Farmer<T> = Person<T>
typealias WorkId = String
typealias Worker = Person<WorkId>
let a = Worker()
let b = Farmer<WorkId>()
protocol Cat {
func run()
}
protocol Dog {
func eat()
}
typealias Pat = Cat & Dog
struct PetA: Pat {
func run() {}
func eat() {}
}
import UIKit
protocol Food {}
protocol Animal {
associatedtype F: Food
func eat(_ food: F)
}
struct Meat: Food {}
struct Grass: Food {}
struct Tiger: Animal {
func eat(_ food: Meat) {}
}
struct Sheep: Animal {
func eat(_ food: Grass) {}
}
func isDangerous<T: Animal>(animal: T) -> Bool {
if animal is Tiger {
return true
} else {
return false
}
}
import UIKit
class Cat {
var name: String
init() {
name = "Kitty"
}
}
class Tiger: Cat {
var action: String
override init() {
action = "Bite"
// super.init()
}
}
let t = Tiger()
print(t.name)
// OUTPUT:
// Kitty
import UIKit
class MyClass {
static var name = "NAME"
// class func test() {
static func test() {
print(#function)
}
}
print(MyClass.name)
MyClass.test()
// OUTPUT:
// NAME
// test()
import UIKit
enum IntOrString {
case intValue(Int)
case stringValue(String)
}
let mixed: [IntOrString] = [.intValue(1), .stringValue("two"), .intValue(3)]
for value in mixed {
switch value {
case let .intValue(i):
print(i * 2)
case let .stringValue(s):
print(s.capitalized)
}
}
// OUTPUT:
// 2
// Two
// 6
import UIKit
struct RegexHelper {
let regex: NSRegularExpression
init(_ pattern: String) throws {
try regex = NSRegularExpression(pattern: pattern, options: .caseInsensitive)
}
func match(_ input: String) -> Bool {
let matches = regex.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
return matches.count > 0
}
}
precedencegroup MatchPrecedence {
associativity: none
higherThan: DefaultPrecedence
}
infix operator =~: MatchPrecedence
func =~(lhs: String, rhs: String) -> Bool {
do {
return try RegexHelper(rhs).match(lhs)
} catch _ {
return false
}
}
let mailPattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
print("test@maimieng.com" =~ mailPattern)
// OUTPUT:
// true
import UIKit
func ~=(pattern: NSRegularExpression, input: String) -> Bool {
return pattern.numberOfMatches(in: input,
options: [],
range: NSRange(location: 0, length: input.characters.count)) > 0
}
prefix operator ~/
prefix func ~/(pattern: String) throws -> NSRegularExpression {
return try NSRegularExpression(pattern: pattern)
}
let contact = ("maimieng.com", "2821836721v@gmail.com")
let mailRegex: NSRegularExpression
let siteRegex: NSRegularExpression
mailRegex = try ~/"^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
siteRegex = try ~/"^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w\\.-]*)*\\/?$"
switch contact {
case (siteRegex, mailRegex):
print("YES site, YES mail")
case (siteRegex, _):
print("YES site, NOT mail")
case (_, mailRegex):
print("NOT site, YES mail")
default:
print("NOT site, NOT mail")
}
// OUTPUT:
// YES site, YES mail
import UIKit
class Class {
class func method() {
print("Hello")
}
}
let type: Class.Type = Class.self
type.method()
let anyClass: AnyClass = Class.self
(anyClass as! Class.Type).method()
// OUTPUT:
// Hello
// Hello
import UIKit
protocol Copyable {
func copy() -> Self
}
class Class: Copyable {
var num = 1
required init() {}
func copy() -> Self {
let result = type(of: self).init()
result.num = num
return result
}
}
let objA = Class()
objA.num = 1
let objB = objA.copy()
let objC = objA
objB.num = 10
objC.num = 100
print(objA.num)
print(objB.num)
print(objC.num)
// OUTPUT:
// 100
// 10
// 100
import UIKit
class Pet {}
class Cat: Pet {}
class Dog: Pet {}
func printPet(_ pet: Pet) {
print("Pet")
}
func printPet(_ cat: Cat) {
print("Cat")
}
func printPet(_ dog: Dog) {
print("Dog")
}
printPet(Pet())
printPet(Cat())
printPet(Dog())
// OUTPUT:
// Pet
// Cat
// Dog
func printThemA(_ pet: Pet, _ cat: Cat) {
printPet(pet)
printPet(cat)
}
printThemA(Dog(), Cat())
// OUTPUT:
// Pet
// Cat
func printThemB(_ pet: Pet, _ cat: Cat) {
if let aCat = pet as? Cat {
printPet(aCat)
} else if let aDog = pet as? Dog {
printPet(aDog)
}
printPet(cat)
}
printThemB(Dog(), Cat())
// OUTPUT:
// Dog
// Cat
class Parent {
final func method() {
print("BEFORE")
methodImpl()
print("AFTER")
}
required func methodImpl() {
fatalError("This must be implemented.")
}
}
class Child: Parent {
override func methodImpl() {
// do sth...
}
}
import UIKit
let data = 0...3
let result = data.lazy.map { (i: Int) -> Int in
print("Handling...")
return i * 2
}
for i in result {
print(i)
}
// OUTPUT:
// Handling...
// 0
// Handling...
// 2
// Handling...
// 4
// Handling...
// 6
import UIKit
struct Person {
let name: String
let age: Int
}
let xm = Person(name: "maimieng", age: 21)
let r = Mirror(reflecting: xm)
print(r.displayStyle ?? "nil")
print(r.children.count)
for child in r.children {
print("\(child.label ?? "nil") - \(child.value)")
}
dump(xm)
// OUTPUT:
// struct
// 2
// name - maimieng
// age - 21
// ▿ __lldb_expr_1.Person
// - name: "maimieng"
// - age: 21
func valueFrom(_ object: Any, key: String) -> Any? {
let mirrot = Mirror(reflecting: object)
for child in mirrot.children {
let (targetKey, targetMirror) = (child.label, child.value)
if key == targetKey {
return targetMirror
}
}
return nil
}
if let name = valueFrom(xm, key: "name") as? String {
print(name)
}
// OUTPUT:
// maimieng
import UIKit
protocol A2 {
func method1() -> String
}
extension A2 {
func method1() -> String {
return "Hi"
}
func method2() -> String {
return "Hi"
}
}
struct B2: A2 {
func method1() -> String {
return "Hello"
}
func method2() -> String {
return "Hello"
}
}
let b2 = B2()
print(b2.method1())
print(b2.method2())
let a2 = b2 as A2
print(a2.method1())
print(a2.method2())
// OUTPUT:
// Hello
// Hello
// Hello
// Hi
import UIKit
class Node<T> {
let value: T?
let next: Node<T>?
init(value: T?, next: Node<T>?) {
self.value = value
self.next = next
}
}
let list = Node(value: 1,
next: Node(value: 2,
next: Node(value: 3,
next: Node(value: 4, next: nil))))
indirect enum LinkedList<Element: Comparable> {
case empty
case node(Element, LinkedList<Element>)
func removing(_ element: Element) -> LinkedList<Element> {
guard case let .node(value, next) = self else {
return .empty
}
return value == element ? next : LinkedList.node(value, next.removing(element))
}
}
let linkedList = LinkedList<Int>.node(1, .node(2, .node(3, .node(4, .empty))))
let result = linkedList.removing(2)
print(result)
// OUTPUT:
// node(1, __lldb_expr_3.LinkedList<Swift.Int>.node(3, __lldb_expr_3.LinkedList<Swift.Int>.node(4, __lldb_expr_3.LinkedList<Swift.Int>.empty)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment