Skip to content

Instantly share code, notes, and snippets.

@jeremiegirault
Created June 14, 2017 15:07
Show Gist options
  • Save jeremiegirault/613e362b23c455538fc875f7e51bf8e1 to your computer and use it in GitHub Desktop.
Save jeremiegirault/613e362b23c455538fc875f7e51bf8e1 to your computer and use it in GitHub Desktop.
Swift helper for compatibility
//
// Swift4Compat.swift
// openrider
//
// Created by Jeremie Girault on 14/06/2017.
// Copyright © 2017 EC1. All rights reserved.
//
import UIKit
#if swift(>=4)
extension UILayoutPriority: ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral {
public init(floatLiteral value: Float) { self.init(rawValue: value) }
public init(integerLiteral value: Int) { self.init(rawValue: Float(value)) }
public static func + (lhs: UILayoutPriority, rhs: UILayoutPriority) -> UILayoutPriority {
return UILayoutPriority(rawValue: lhs.rawValue + rhs.rawValue)
}
public static func - (lhs: UILayoutPriority, rhs: UILayoutPriority) -> UILayoutPriority {
return UILayoutPriority(rawValue: lhs.rawValue - rhs.rawValue)
}
}
#else
extension UILayoutPriority {
public static let required = UILayoutPriorityRequired
public static let defaultHigh = UILayoutPriorityDefaultHigh
public static let defaultLow = UILayoutPriorityDefaultLow
public static let fittingSizeLevel = UILayoutPriorityFittingSizeLevel
}
public struct NSAttributedStringKey: RawRepresentable, Hashable {
public let rawValue: String
public init(rawValue: String) { self.rawValue = rawValue }
public init(_ rawValue: String) { self.rawValue = rawValue }
public static func == (lhs: NSAttributedStringKey, rhs: NSAttributedStringKey) -> Bool { return rhs.rawValue == lhs.rawValue }
public var hashValue: Int { return rawValue.hashValue }
}
extension NSAttributedStringKey {
public static let font = NSAttributedStringKey(NSFontAttributeName)
public static let foregroundColor = NSAttributedStringKey(NSForegroundColorAttributeName)
}
fileprivate extension Dictionary where Key == NSAttributedStringKey, Value == Any {
var compatDictionary: [String: Any] {
var dic = [String: Any]()
for (key, value) in self {
dic[key.rawValue] = value
}
return dic
}
}
extension NSAttributedString {
public func enumerateAttribute(_ attrName: NSAttributedStringKey,
in enumerationRange: NSRange,
options opts: NSAttributedString.EnumerationOptions = [],
using block: (Any?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateAttribute(attrName.rawValue, in: enumerationRange, options: opts, using: block)
}
public convenience init(string: String, attributes: [NSAttributedStringKey: Any]) {
self.init(string: string, attributes: attributes.compatDictionary)
}
}
extension NSMutableAttributedString {
public func addAttributes(_ attributes: [NSAttributedStringKey: Any], range: NSRange) {
addAttributes(attributes.compatDictionary, range: range)
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment