Files
yingmeng-ios-switf/yinmeng-ios/Extension/List/List+.swift
2024-02-24 13:49:51 +08:00

50 lines
973 B
Swift

//
// List+.swift
// yinmeng-ios
//
// Created by MaiMang on 2024/2/24.
//
import Foundation
extension Array where Element: Equatable {
mutating func remove(_ element: Element) {
if let index = firstIndex(of: element) {
remove(at: index)
}
}
mutating func addObjects(_ elements: [Element]) {
for value in elements {
self.append(value)
}
}
mutating func replaceObject(_ element: Element, index: Int) {
if self.count == index {
self.append(element)
}
else if self.count > index {
self.insert(element, at: index)
self.remove(at: index + 1)
}
}
}
public extension Collection {
subscript(safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
extension Encodable {
var dictionary: [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}