-
Notifications
You must be signed in to change notification settings - Fork 1
/
Literal.swift
113 lines (88 loc) · 2.79 KB
/
Literal.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//
// Literal.swift
// Pods
//
// Created by Leavez on 20/04/2017.
//
//
import CoreGraphics
import Foundation
/// By implementing ExpressibleByArrayLiteral, code can be written like below:
///
/// ```
/// let p: CGPoint = [0, 1]
///
/// view.frame = [10, 20, 100, 100]
///
/// attributedString.setAttributes(attrs, range: [0, 1])
///
/// ```
extension CGPoint: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: CGFloat...) {
assert(elements.count == 2)
let numbers = clip(elements, to: 2, defaultValue: 0)
self.init(x: numbers[0], y: numbers[1])
}
}
extension CGSize: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: CGFloat...) {
assert(elements.count == 2)
let numbers = clip(elements, to: 2, defaultValue: 0)
self.init(width: numbers[0], height: numbers[1])
}
}
extension CGRect: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: CGFloat...) {
assert(elements.count == 4)
let numbers = clip(elements, to: 4, defaultValue: 0)
self.init(x: numbers[0], y: numbers[1], width:numbers[2], height:numbers[3])
}
}
extension CGVector: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: CGFloat...) {
assert(elements.count == 2)
let numbers = clip(elements, to: 2, defaultValue: 0)
self.init(dx: numbers[0], dy: numbers[1])
}
}
extension NSRange: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Int...) {
assert(elements.count == 2)
let numbers = clip(elements, to: 2, defaultValue: 0)
self.init(location: numbers[0], length: numbers[1])
}
}
private func clip<T>(_ array: [T], to count:Int, defaultValue:T) -> [T] {
if array.count == count {
return array
} else if array.count < count {
return array + (0..<(count-array.count)).map{ _ in defaultValue }
} else {
return Array(array[0..<count])
}
}
// These type below is support ExpressibleByArrayLiteral natively
//
// - IndexPath
// - NSSet, Set, NSOrderedSet, NSCountedSet, CharacterSet
extension CharacterSet: ExpressibleByStringLiteral {
public init(extendedGraphemeClusterLiteral value: String) {
self.init(charactersIn: value)
}
public init(stringLiteral value: String) {
self.init(charactersIn: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(charactersIn: value)
}
}
#if os(iOS)
import UIKit
extension UIEdgeInsets: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: CGFloat...) {
assert(elements.count == 4)
let numbers = clip(elements, to: 4, defaultValue: 0)
self.init(top: numbers[0], left: numbers[1], bottom:numbers[2], right:numbers[3])
}
}
#endif