Util.swift 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2015 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. import Foundation
  19. import Realm
  20. #if BUILDING_REALM_SWIFT_TESTS
  21. import RealmSwift
  22. #endif
  23. // MARK: Internal Helpers
  24. // Swift 3.1 provides fixits for some of our uses of unsafeBitCast
  25. // to use unsafeDowncast instead, but the bitcast is required.
  26. internal func noWarnUnsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
  27. return unsafeBitCast(x, to: type)
  28. }
  29. /// Given a list of `Any`-typed varargs, unwrap any optionals and
  30. /// replace them with the underlying value or NSNull.
  31. internal func unwrapOptionals(in varargs: [Any]) -> [Any] {
  32. return varargs.map { arg in
  33. if let someArg = arg as Any? {
  34. return someArg
  35. }
  36. return NSNull()
  37. }
  38. }
  39. internal func notFoundToNil(index: UInt) -> Int? {
  40. if index == UInt(NSNotFound) {
  41. return nil
  42. }
  43. return Int(index)
  44. }
  45. internal func throwRealmException(_ message: String, userInfo: [AnyHashable: Any]? = nil) -> Never {
  46. NSException(name: NSExceptionName(rawValue: RLMExceptionName), reason: message, userInfo: userInfo).raise()
  47. fatalError() // unreachable
  48. }
  49. internal func throwForNegativeIndex(_ int: Int, parameterName: String = "index") {
  50. if int < 0 {
  51. throwRealmException("Cannot pass a negative value for '\(parameterName)'.")
  52. }
  53. }
  54. internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? {
  55. let regex = try? NSRegularExpression(pattern: pattern, options: [])
  56. return regex?.stringByReplacingMatches(in: string, options: [],
  57. range: NSRange(location: 0, length: string.utf16.count),
  58. withTemplate: template)
  59. }
  60. internal func cast<U, V>(_ value: U, to: V.Type) -> V {
  61. if let v = value as? V {
  62. return v
  63. }
  64. return unsafeBitCast(value, to: to)
  65. }
  66. extension Object {
  67. // Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject`
  68. // but actually operate on `RLMObjectBase`. Do not expose cast value to user.
  69. internal func unsafeCastToRLMObject() -> RLMObject {
  70. return unsafeBitCast(self, to: RLMObject.self)
  71. }
  72. }
  73. // MARK: CustomObjectiveCBridgeable
  74. /// :nodoc:
  75. public func dynamicBridgeCast<T>(fromObjectiveC x: Any) -> T {
  76. if T.self == DynamicObject.self {
  77. return unsafeBitCast(x as AnyObject, to: T.self)
  78. } else if let bridgeableType = T.self as? CustomObjectiveCBridgeable.Type {
  79. return bridgeableType.bridging(objCValue: x) as! T
  80. } else if let bridgeableType = T.self as? RealmEnum.Type {
  81. return bridgeableType._rlmFromRawValue(x) as! T
  82. } else {
  83. return x as! T
  84. }
  85. }
  86. /// :nodoc:
  87. public func dynamicBridgeCast<T>(fromSwift x: T) -> Any {
  88. if let x = x as? CustomObjectiveCBridgeable {
  89. return x.objCValue
  90. } else if let bridgeableType = T.self as? RealmEnum.Type {
  91. return bridgeableType._rlmToRawValue(x)
  92. } else {
  93. return x
  94. }
  95. }
  96. // Used for conversion from Objective-C types to Swift types
  97. internal protocol CustomObjectiveCBridgeable {
  98. static func bridging(objCValue: Any) -> Self
  99. var objCValue: Any { get }
  100. }
  101. // FIXME: needed with swift 3.2
  102. // Double isn't though?
  103. extension Float: CustomObjectiveCBridgeable {
  104. internal static func bridging(objCValue: Any) -> Float {
  105. return (objCValue as! NSNumber).floatValue
  106. }
  107. internal var objCValue: Any {
  108. return NSNumber(value: self)
  109. }
  110. }
  111. extension Int8: CustomObjectiveCBridgeable {
  112. internal static func bridging(objCValue: Any) -> Int8 {
  113. return (objCValue as! NSNumber).int8Value
  114. }
  115. internal var objCValue: Any {
  116. return NSNumber(value: self)
  117. }
  118. }
  119. extension Int16: CustomObjectiveCBridgeable {
  120. internal static func bridging(objCValue: Any) -> Int16 {
  121. return (objCValue as! NSNumber).int16Value
  122. }
  123. internal var objCValue: Any {
  124. return NSNumber(value: self)
  125. }
  126. }
  127. extension Int32: CustomObjectiveCBridgeable {
  128. internal static func bridging(objCValue: Any) -> Int32 {
  129. return (objCValue as! NSNumber).int32Value
  130. }
  131. internal var objCValue: Any {
  132. return NSNumber(value: self)
  133. }
  134. }
  135. extension Int64: CustomObjectiveCBridgeable {
  136. internal static func bridging(objCValue: Any) -> Int64 {
  137. return (objCValue as! NSNumber).int64Value
  138. }
  139. internal var objCValue: Any {
  140. return NSNumber(value: self)
  141. }
  142. }
  143. extension Optional: CustomObjectiveCBridgeable {
  144. internal static func bridging(objCValue: Any) -> Optional {
  145. if objCValue is NSNull {
  146. return nil
  147. } else {
  148. return .some(dynamicBridgeCast(fromObjectiveC: objCValue))
  149. }
  150. }
  151. internal var objCValue: Any {
  152. if let value = self {
  153. return dynamicBridgeCast(fromSwift: value)
  154. } else {
  155. return NSNull()
  156. }
  157. }
  158. }
  159. // MARK: AssistedObjectiveCBridgeable
  160. internal protocol AssistedObjectiveCBridgeable {
  161. static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self
  162. var bridged: (objectiveCValue: Any, metadata: Any?) { get }
  163. }