83 lines
2.4 KiB
Swift
Executable File
83 lines
2.4 KiB
Swift
Executable File
//
|
|
// Array+Extension.swift
|
|
// PaiLiBo
|
|
//
|
|
// Created by SeanXu on 2019/10/25.
|
|
// Copyright © 2019 GuoXiaoMei. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
extension Sequence {
|
|
func group<GroupingType: Hashable>(by key: (Iterator.Element) throws -> GroupingType) rethrows -> [[Iterator.Element]] {
|
|
try reduce(into: []) { result, element in
|
|
if let lastElement = result.last?.last, try key(lastElement) == key(element) {
|
|
result[result.index(before: result.endIndex)].append(element)
|
|
} else {
|
|
result.append([element])
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
extension Array where Element: Equatable {
|
|
|
|
public mutating func removeObject(_ object : Iterator.Element) {
|
|
if let index = firstIndex(of: object) {
|
|
remove(at: index)
|
|
}
|
|
}
|
|
|
|
public mutating func insertObject(_ object : Iterator.Element) {
|
|
if let _ = firstIndex(of: object) {
|
|
return
|
|
} else {
|
|
append(object)
|
|
}
|
|
}
|
|
|
|
public func toJsonArray() -> String{
|
|
|
|
guard self.count > 0 else {
|
|
return ""
|
|
}
|
|
|
|
let mutaleSting:NSMutableString = "["
|
|
for (index,obj) in self.enumerated(){
|
|
if obj is String{
|
|
mutaleSting.append("\"")
|
|
mutaleSting.append(obj as! String)
|
|
mutaleSting.append("\"")
|
|
if index < self.count - 1{
|
|
mutaleSting.append(",")
|
|
}
|
|
if index == self.count-1 {
|
|
mutaleSting.append("]")
|
|
}
|
|
}
|
|
}
|
|
return mutaleSting as String
|
|
}
|
|
|
|
public func dicArrayToJsonString() -> String {
|
|
if (!JSONSerialization.isValidJSONObject(self)) {
|
|
print("无法解析出JSONString")
|
|
return " "
|
|
}
|
|
if let data = try? JSONSerialization.data(withJSONObject: self, options: []), let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue) as String? {
|
|
return JSONString
|
|
}
|
|
return " "
|
|
}
|
|
}
|
|
|
|
extension Array {
|
|
public static var safeValue: Array<Element> { return [] }
|
|
public func safeElement(_ index: Int) -> Element? {
|
|
return index >= 0 && index < endIndex ? self[index] : nil
|
|
}
|
|
public subscript(safe index: Int) -> Element? {
|
|
return safeElement(index)
|
|
}
|
|
}
|