jsdw_ios/QuickLocation/Core/Extension/Array+Extension.swift

92 lines
2.7 KiB
Swift
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// 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)
}
}
extension Array {
mutating func moveToFirst(where condition: (Element) -> Bool) {
guard let index = firstIndex(where: condition) else { return }
//
let item = remove(at: index)
insert(item, at: 0)
}
}