Skip to content

Instantly share code, notes, and snippets.

@artemkrachulov
Last active March 16, 2017 13:58
Show Gist options
  • Save artemkrachulov/15077d121f60d116055eec97de1a37a5 to your computer and use it in GitHub Desktop.
Save artemkrachulov/15077d121f60d116055eec97de1a37a5 to your computer and use it in GitHub Desktop.
What to use
// In Swift a method can be marked with rethrows keyword. It means that it throws an error only if one of its arguments throws an error.
func bar(callback: () throws -> Void) rethrows {
try callback()
}
//using String to throw an error.
extension String: Error {}
func bar() throws {
throw "Something went wrong!"
}
// Forced Unwrapping URLs
// Returns `URL` with guided fail
public enum SocketEndPoint: String {
case events = "http://nowhere.com/events"
case live = "http://nowhere.com/live"
public var url: URL {
guard let url = URL(string: self.rawValue) else {
fatalError("Unconstructable URL: \(self.rawValue)")
}
return url
}
}
// His initializer
fileprivate init() {
self.eventSocket = WebSocket(url: SocketEndPoint.events.url))
self.liveSocket = WebSocket(url: SocketEndPoint.live.url))
self.eventSocket.delegate = self
self.liveSocket.delegate = self
}
// I’d like to propose a new operator for optional assignment in Swift.
//The idea is that by using this operator (e.g. by doing a ?= b), the optional on the right would be assigned to the variable on the left only when it has something to assign (i.e. when it's not nil).
// The implementation could be something as follows:
/// Optional Assignment Operator
infix operator ?=: AssignmentPrecedence
func ?=<T>(left: inout T, right: T?) {
if right != nil {
left = right!
}
}
func ?=<T>(left: inout T?, right: T?) {
if right != nil {
left = right
}
}
/// A type that has an empty value representation, as opposed to `nil`.
public protocol EmptyValueRepresentable {
/// Provide the empty value representation of the conforming type.
static var emptyValue: Self { get }
/// - returns: `true` if `self` is the empty value.
var isEmpty: Bool { get }
/// `nil` if `self` is the empty value, `self` otherwise.
/// An appropriate default implementation is provided automatically.
func nilIfEmpty() -> Self?
}
extension EmptyValueRepresentable {
public func nilIfEmpty() -> Self? {
return self.isEmpty ? nil : self
}
}
extension Array: EmptyValueRepresentable {
public static var emptyValue: [Element] { return [] }
}
extension Set: EmptyValueRepresentable {
public static var emptyValue: Set<Element> { return Set() }
}
extension Dictionary: EmptyValueRepresentable {
public static var emptyValue: Dictionary<Key, Value> { return [:] }
}
extension String: EmptyValueRepresentable {
public static var emptyValue: String { return "" }
}
public extension Optional where Wrapped: EmptyValueRepresentable {
/// If `self == nil` returns the empty value, otherwise returns the value.
public func valueOrEmpty() -> Wrapped {
switch self {
case .some(let value):
return value
case .none:
return Wrapped.emptyValue
}
}
/// If `self == nil` returns the empty value, otherwise returns the result of
/// mapping `transform` over the value.
public func mapOrEmpty(_ transform: (Wrapped) -> Wrapped) -> Wrapped {
switch self {
case .some(let value):
return transform(value)
case .none:
return Wrapped.emptyValue
}
}
}
//https://gist.github.com/riteshhgupta/358db2ed3b6968ef18880cb28bdb6963
extension Optional {
// `then` function executes the closure if there is some value
func then(_ handler: (Wrapped) -> Void) {
switch self {
case .some(let wrapped): return handler(wrapped)
case .none: break
}
}
}
import Foundation
extension Optional
{
@discardableResult
func ifSome(_ handler: (Wrapped) -> Void) -> Optional {
switch self {
case .some(let wrapped): handler(wrapped); return self
case .none: return self
}
}
@discardableResult
func ifNone(_ handler: () -> Void) -> Optional {
switch self {
case .some: return self
case .none(): handler(); return self
}
}
}
struct Person {
let name: String
}
var p: Person? = Person(name: "Joe")
p.ifSome { print($0) }.ifNone { print("none") } // prints Person
p = nil
p.ifSome { print($0) }.ifNone { print("none") } // prints none
// https://oleb.net/blog/2016/12/optionals-string-interpolation/?utm_campaign=This%2BWeek%2Bin%2BSwift&utm_medium=email&utm_source=This_Week_in_Swift_114
infix operator ???: NilCoalescingPrecedence
public func ???<T>(optional: T?, defaultValue: @autoclosure () -> String) -> String {
switch optional {
case let value?: return String(describing: value)
case nil: return defaultValue()
}
}
public func ???<T>(optional: T?, defaultValue: @autoclosure () -> String) -> String {
return optional.map { String(describing: $0) } ?? defaultValue()
}
var someValue: Int? = 5
print("The value is \(someValue ??? "unknown")")
// → "The value is 5"
someValue = nil
print("The value is \(someValue ??? "unknown")")
// → "The value is unknown"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment