Skip to content

Instantly share code, notes, and snippets.

View Andy0570's full-sized avatar
🎯
Focusing

独木舟的木 Andy0570

🎯
Focusing
  • Shanghai, China
  • 07:41 (UTC +08:00)
View GitHub Profile
import Foundation
extension String {
// MARK: 计算字符串的 MD5 哈希值
var md5: String? {
let length = Int(CC_MD5_DIGEST_LENGTH)
guard let data = self.data(using: String.Encoding.utf8) else { return nil }
@Andy0570
Andy0570 / String+json.swift
Created November 18, 2020 03:20
JSON 字符串解析
import Foundation
extension String {
init?(json: Any) {
guard let data = Data(json: json) else { return nil }
self.init(decoding: data, as: UTF8.self)
}
func jsonToDictionary() -> [String: Any]? {
self.data(using: .utf8)?.jsonToDictionary()
@Andy0570
Andy0570 / Data+json.swift
Created November 18, 2020 03:19
JSON Data 解析
import Foundation
extension Data {
init?(json: Any) {
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .fragmentsAllowed) else { return nil }
self.init(data)
}
func jsonToDictionary() -> [String: Any]? {
(try? JSONSerialization.jsonObject(with: self, options: .allowFragments)) as? [String: Any]
@Andy0570
Andy0570 / UniColor+hex.swift
Created November 18, 2020 03:17
从字符串中提取颜色
#if os(iOS) || os(tvOS)
import UIKit
typealias UniColor = UIColor
#else
import Cocoa
typealias UniColor = NSColor
#endif
private extension Int {
func duplicate4bits() -> Int {
@Andy0570
Andy0570 / LoadSave.swift
Created November 18, 2020 03:16
保存数据到 UserDefaults 偏好设置
import Foundation
extension Int {
init?(key: String) {
guard UserDefaults.standard.value(forKey: key) != nil else { return nil }
self.init(UserDefaults.standard.integer(forKey: key))
}
func store(key: String) {
UserDefaults.standard.set(self, forKey: key)
import Foundation
extension URL {
func withQueries(_ queries: [String: String]) -> URL? {
var components = URLComponents(url: self, resolvingAgainstBaseURL: true)
components?.queryItems = queries.compactMap { URLQueryItem(name: $0.0, value: $0.1) }
return components?.url
}
}
@Andy0570
Andy0570 / UIImage+Extensions.swift
Last active November 18, 2020 02:59
通过颜色生成图片
extension UIImage {
class func imageWithColor(color: UIColor) -> UIImage {
let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
@Andy0570
Andy0570 / UIColor+Image.swift
Last active November 18, 2020 03:00
通过颜色生成图片
extension UIColor {
func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { (rendererContext) in
self.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
}
}