forked from iAmMccc/SmartCodable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArraySafe.swift
More file actions
95 lines (80 loc) · 2.01 KB
/
ArraySafe.swift
File metadata and controls
95 lines (80 loc) · 2.01 KB
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
//
// ArraySafe+Extension.swift
// BTFoundation
//
// Created by Mccc on 2020/4/7.
//
import Foundation
/** 说明
数组安全的处理
使用方式
let item = arr[1000~]
let items = arr[(1...2)~]
返回时一个可选值
*/
// ~
postfix operator ~
public postfix func ~ (value: Int?) -> BTSafeArray? {
return BTSafeArray(value: value)
}
public postfix func ~ (value: Range<Int>?) -> BTSafeRange? {
return BTSafeRange(value: value)
}
public postfix func ~ (value: CountableClosedRange<Int>?) -> BTSafeRange? {
guard let value = value else {
return nil
}
return BTSafeRange(value: Range<Int>(value))
}
// Struct
public struct BTSafeArray {
var index: Int
init?(value: Int?) {
guard let value = value else {
return nil
}
self.index = value
}
}
public struct BTSafeRange {
var range: Range<Int>
init?(value: Range<Int>?) {
guard let value = value else {
return nil
}
self.range = value
}
}
// subscript
public extension Array {
/// 单个
subscript(index: BTSafeArray?) -> Element? {
get {
if let index = index?.index {
return (self.startIndex..<self.endIndex).contains(index) ? self[index] : nil
}
return nil
}
set {
if let index = index?.index, let newValue = newValue {
if (self.startIndex ..< self.endIndex).contains(index) {
self[index] = newValue
}
}
}
}
/// 范围
subscript(bounds: BTSafeRange?) -> ArraySlice<Element>? {
get {
if let range = bounds?.range {
return self[range.clamped(to: self.startIndex ..< self.endIndex)]
}
return nil
}
set {
if let range = bounds?.range, let newValue = newValue {
self[range.clamped(to: self.startIndex ..< self.endIndex)] = newValue
}
}
}
}