Created
June 30, 2022 19:02
-
-
Save kiarashvosough1999/97aa10eb8cb966a91249e043865363da to your computer and use it in GitHub Desktop.
Castable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
infix operator ->>: DefaultPrecedence | |
public protocol Castable { | |
func forceCast<U>(to type: U.Type) -> U | |
func AS<U>(to type: U.Type) -> U? | |
func cast<U>(to type: U.Type) -> U? | |
func unsafeBitCast<U>(to type: U.Type) throws -> U | |
func unsafeDownCast<U>(to type: U.Type) throws -> U where U: AnyObject | |
static func ->> <U>(lhs: Self, rhs: U.Type) -> U? | |
} | |
public extension Castable where Self: AnyObject { | |
func unsafeDownCast<U>(to type: U.Type) throws -> U where U: AnyObject { | |
Swift.unsafeDowncast(self, to: type.self) | |
} | |
} | |
public extension Castable { | |
func isReferenceType() -> Bool { | |
return Swift.type(of: self) is AnyClass | |
} | |
static func ->> <U>(lhs: Self, rhs: U.Type) -> U? { | |
lhs as? U | |
} | |
func forceCast<U>(to type: U.Type) -> U { | |
self as! U | |
} | |
func AS<U>(to type: U.Type) -> U? { | |
self as? U | |
} | |
func cast<U>(to type: U.Type) -> U? { | |
self as? U | |
} | |
func unsafeBitCast<U>(to type: U.Type) throws -> U { | |
if MemoryLayout<Self>.size != MemoryLayout<U>.size { | |
throw ProtoError.castingError(reason: .bitcastTwoVariableWithDifferentBitCount) | |
} | |
return Swift.unsafeBitCast(self, to: U.self) | |
} | |
func unsafeDownCast<U>(to type: U.Type) throws -> U where U: AnyObject { | |
throw ProtoError.castingError(reason: .downCastingNonRefrencableVariable) | |
} | |
} | |
extension NSObject: Castable {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment