List.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 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. import Realm.Private
  21. /// :nodoc:
  22. /// Internal class. Do not use directly.
  23. public class ListBase: RLMListBase {
  24. // Printable requires a description property defined in Swift (and not obj-c),
  25. // and it has to be defined as override, which can't be done in a
  26. // generic class.
  27. /// Returns a human-readable description of the objects contained in the List.
  28. @objc public override var description: String {
  29. return descriptionWithMaxDepth(RLMDescriptionMaxDepth)
  30. }
  31. @objc private func descriptionWithMaxDepth(_ depth: UInt) -> String {
  32. return RLMDescriptionWithMaxDepth("List", _rlmArray, depth)
  33. }
  34. /// Returns the number of objects in this List.
  35. public var count: Int { return Int(_rlmArray.count) }
  36. }
  37. /**
  38. `List` is the container type in Realm used to define to-many relationships.
  39. Like Swift's `Array`, `List` is a generic type that is parameterized on the type it stores. This can be either an `Object`
  40. subclass or one of the following types: `Bool`, `Int`, `Int8`, `Int16`, `Int32`, `Int64`, `Float`, `Double`, `String`, `Data`,
  41. and `Date` (and their optional versions)
  42. Unlike Swift's native collections, `List`s are reference types, and are only immutable if the Realm that manages them
  43. is opened as read-only.
  44. Lists can be filtered and sorted with the same predicates as `Results<Element>`.
  45. Properties of `List` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`.
  46. */
  47. public final class List<Element: RealmCollectionValue>: ListBase {
  48. // MARK: Properties
  49. /// The Realm which manages the list, or `nil` if the list is unmanaged.
  50. public var realm: Realm? {
  51. return _rlmArray.realm.map { Realm($0) }
  52. }
  53. /// Indicates if the list can no longer be accessed.
  54. public var isInvalidated: Bool { return _rlmArray.isInvalidated }
  55. // MARK: Initializers
  56. /// Creates a `List` that holds Realm model objects of type `Element`.
  57. public override init() {
  58. super.init(array: Element._rlmArray())
  59. }
  60. internal init(rlmArray: RLMArray<AnyObject>) {
  61. super.init(array: rlmArray)
  62. }
  63. // MARK: Index Retrieval
  64. /**
  65. Returns the index of an object in the list, or `nil` if the object is not present.
  66. - parameter object: An object to find.
  67. */
  68. public func index(of object: Element) -> Int? {
  69. return notFoundToNil(index: _rlmArray.index(of: dynamicBridgeCast(fromSwift: object) as AnyObject))
  70. }
  71. /**
  72. Returns the index of the first object in the list matching the predicate, or `nil` if no objects match.
  73. - parameter predicate: The predicate with which to filter the objects.
  74. */
  75. public func index(matching predicate: NSPredicate) -> Int? {
  76. return notFoundToNil(index: _rlmArray.indexOfObject(with: predicate))
  77. }
  78. /**
  79. Returns the index of the first object in the list matching the predicate, or `nil` if no objects match.
  80. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  81. */
  82. public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
  83. return index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  84. }
  85. // MARK: Object Retrieval
  86. /**
  87. Returns the object at the given index (get), or replaces the object at the given index (set).
  88. - warning: You can only set an object during a write transaction.
  89. - parameter index: The index of the object to retrieve or replace.
  90. */
  91. public subscript(position: Int) -> Element {
  92. get {
  93. throwForNegativeIndex(position)
  94. return dynamicBridgeCast(fromObjectiveC: _rlmArray.object(at: UInt(position)))
  95. }
  96. set {
  97. throwForNegativeIndex(position)
  98. _rlmArray.replaceObject(at: UInt(position), with: dynamicBridgeCast(fromSwift: newValue) as AnyObject)
  99. }
  100. }
  101. /// Returns the first object in the list, or `nil` if the list is empty.
  102. public var first: Element? { return _rlmArray.firstObject().map(dynamicBridgeCast) }
  103. /// Returns the last object in the list, or `nil` if the list is empty.
  104. public var last: Element? { return _rlmArray.lastObject().map(dynamicBridgeCast) }
  105. // MARK: KVC
  106. /**
  107. Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's
  108. objects.
  109. */
  110. @nonobjc public func value(forKey key: String) -> [AnyObject] {
  111. return _rlmArray.value(forKeyPath: key)! as! [AnyObject]
  112. }
  113. /**
  114. Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the
  115. collection's objects.
  116. - parameter keyPath: The key path to the property whose values are desired.
  117. */
  118. @nonobjc public func value(forKeyPath keyPath: String) -> [AnyObject] {
  119. return _rlmArray.value(forKeyPath: keyPath) as! [AnyObject]
  120. }
  121. /**
  122. Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
  123. - warning: This method can only be called during a write transaction.
  124. - parameter value: The object value.
  125. - parameter key: The name of the property whose value should be set on each object.
  126. */
  127. public override func setValue(_ value: Any?, forKey key: String) {
  128. return _rlmArray.setValue(value, forKeyPath: key)
  129. }
  130. // MARK: Filtering
  131. /**
  132. Returns a `Results` containing all objects matching the given predicate in the list.
  133. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  134. */
  135. public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
  136. return Results<Element>(_rlmArray.objects(with: NSPredicate(format: predicateFormat,
  137. argumentArray: unwrapOptionals(in: args))))
  138. }
  139. /**
  140. Returns a `Results` containing all objects matching the given predicate in the list.
  141. - parameter predicate: The predicate with which to filter the objects.
  142. */
  143. public func filter(_ predicate: NSPredicate) -> Results<Element> {
  144. return Results<Element>(_rlmArray.objects(with: predicate))
  145. }
  146. // MARK: Sorting
  147. /**
  148. Returns a `Results` containing the objects in the list, but sorted.
  149. Objects are sorted based on the values of the given key path. For example, to sort a list of `Student`s from
  150. youngest to oldest based on their `age` property, you might call
  151. `students.sorted(byKeyPath: "age", ascending: true)`.
  152. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  153. floating point, integer, and string types.
  154. - parameter keyPath: The key path to sort by.
  155. - parameter ascending: The direction to sort in.
  156. */
  157. public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> {
  158. return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
  159. }
  160. /**
  161. Returns a `Results` containing the objects in the list, but sorted.
  162. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  163. floating point, integer, and string types.
  164. - see: `sorted(byKeyPath:ascending:)`
  165. */
  166. public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
  167. where S.Iterator.Element == SortDescriptor {
  168. return Results<Element>(_rlmArray.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
  169. }
  170. // MARK: Aggregate Operations
  171. /**
  172. Returns the minimum (lowest) value of the given property among all the objects in the list, or `nil` if the list is
  173. empty.
  174. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  175. - parameter property: The name of a property whose minimum value is desired.
  176. */
  177. public func min<T: MinMaxType>(ofProperty property: String) -> T? {
  178. return _rlmArray.min(ofProperty: property).map(dynamicBridgeCast)
  179. }
  180. /**
  181. Returns the maximum (highest) value of the given property among all the objects in the list, or `nil` if the list
  182. is empty.
  183. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  184. - parameter property: The name of a property whose maximum value is desired.
  185. */
  186. public func max<T: MinMaxType>(ofProperty property: String) -> T? {
  187. return _rlmArray.max(ofProperty: property).map(dynamicBridgeCast)
  188. }
  189. /**
  190. Returns the sum of the values of a given property over all the objects in the list.
  191. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  192. - parameter property: The name of a property whose values should be summed.
  193. */
  194. public func sum<T: AddableType>(ofProperty property: String) -> T {
  195. return dynamicBridgeCast(fromObjectiveC: _rlmArray.sum(ofProperty: property))
  196. }
  197. /**
  198. Returns the average value of a given property over all the objects in the list, or `nil` if the list is empty.
  199. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  200. - parameter property: The name of a property whose average value should be calculated.
  201. */
  202. public func average(ofProperty property: String) -> Double? {
  203. return _rlmArray.average(ofProperty: property).map(dynamicBridgeCast)
  204. }
  205. // MARK: Mutation
  206. /**
  207. Appends the given object to the end of the list.
  208. If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing
  209. the receiver.
  210. - warning: This method may only be called during a write transaction.
  211. - parameter object: An object.
  212. */
  213. public func append(_ object: Element) {
  214. _rlmArray.add(dynamicBridgeCast(fromSwift: object) as AnyObject)
  215. }
  216. /**
  217. Appends the objects in the given sequence to the end of the list.
  218. - warning: This method may only be called during a write transaction.
  219. */
  220. public func append<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == Element {
  221. for obj in objects {
  222. _rlmArray.add(dynamicBridgeCast(fromSwift: obj) as AnyObject)
  223. }
  224. }
  225. /**
  226. Inserts an object at the given index.
  227. - warning: This method may only be called during a write transaction.
  228. - warning: This method will throw an exception if called with an invalid index.
  229. - parameter object: An object.
  230. - parameter index: The index at which to insert the object.
  231. */
  232. public func insert(_ object: Element, at index: Int) {
  233. throwForNegativeIndex(index)
  234. _rlmArray.insert(dynamicBridgeCast(fromSwift: object) as AnyObject, at: UInt(index))
  235. }
  236. /**
  237. Removes an object at the given index. The object is not removed from the Realm that manages it.
  238. - warning: This method may only be called during a write transaction.
  239. - warning: This method will throw an exception if called with an invalid index.
  240. - parameter index: The index at which to remove the object.
  241. */
  242. public func remove(at index: Int) {
  243. throwForNegativeIndex(index)
  244. _rlmArray.removeObject(at: UInt(index))
  245. }
  246. /**
  247. Removes all objects from the list. The objects are not removed from the Realm that manages them.
  248. - warning: This method may only be called during a write transaction.
  249. */
  250. public func removeAll() {
  251. _rlmArray.removeAllObjects()
  252. }
  253. /**
  254. Replaces an object at the given index with a new object.
  255. - warning: This method may only be called during a write transaction.
  256. - warning: This method will throw an exception if called with an invalid index.
  257. - parameter index: The index of the object to be replaced.
  258. - parameter object: An object.
  259. */
  260. public func replace(index: Int, object: Element) {
  261. throwForNegativeIndex(index)
  262. _rlmArray.replaceObject(at: UInt(index), with: dynamicBridgeCast(fromSwift: object) as AnyObject)
  263. }
  264. /**
  265. Moves the object at the given source index to the given destination index.
  266. - warning: This method may only be called during a write transaction.
  267. - warning: This method will throw an exception if called with invalid indices.
  268. - parameter from: The index of the object to be moved.
  269. - parameter to: index to which the object at `from` should be moved.
  270. */
  271. public func move(from: Int, to: Int) {
  272. throwForNegativeIndex(from)
  273. throwForNegativeIndex(to)
  274. _rlmArray.moveObject(at: UInt(from), to: UInt(to))
  275. }
  276. /**
  277. Exchanges the objects in the list at given indices.
  278. - warning: This method may only be called during a write transaction.
  279. - warning: This method will throw an exception if called with invalid indices.
  280. - parameter index1: The index of the object which should replace the object at index `index2`.
  281. - parameter index2: The index of the object which should replace the object at index `index1`.
  282. */
  283. public func swapAt(_ index1: Int, _ index2: Int) {
  284. throwForNegativeIndex(index1, parameterName: "index1")
  285. throwForNegativeIndex(index2, parameterName: "index2")
  286. _rlmArray.exchangeObject(at: UInt(index1), withObjectAt: UInt(index2))
  287. }
  288. // MARK: Notifications
  289. /**
  290. Registers a block to be called each time the collection changes.
  291. The block will be asynchronously called with the initial results, and then called again after each write
  292. transaction which changes either any of the objects in the collection, or which objects are in the collection.
  293. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
  294. the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
  295. documentation for more information on the change information supplied and an example of how to use it to update a
  296. `UITableView`.
  297. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
  298. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  299. perform blocking work.
  300. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
  301. other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
  302. single notification. This can include the notification with the initial collection.
  303. For example, the following code performs a write transaction immediately after adding the notification block, so
  304. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  305. will reflect the state of the Realm after the write transaction.
  306. ```swift
  307. let results = realm.objects(Dog.self)
  308. print("dogs.count: \(dogs?.count)") // => 0
  309. let token = dogs.observe { changes in
  310. switch changes {
  311. case .initial(let dogs):
  312. // Will print "dogs.count: 1"
  313. print("dogs.count: \(dogs.count)")
  314. break
  315. case .update:
  316. // Will not be hit in this example
  317. break
  318. case .error:
  319. break
  320. }
  321. }
  322. try! realm.write {
  323. let dog = Dog()
  324. dog.name = "Rex"
  325. person.dogs.append(dog)
  326. }
  327. // end of run loop execution context
  328. ```
  329. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  330. updates, call `invalidate()` on the token.
  331. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  332. - parameter block: The block to be called whenever a change occurs.
  333. - returns: A token which must be held for as long as you want updates to be delivered.
  334. */
  335. public func observe(_ block: @escaping (RealmCollectionChange<List>) -> Void) -> NotificationToken {
  336. return _rlmArray.addNotificationBlock { _, change, error in
  337. block(RealmCollectionChange.fromObjc(value: self, change: change, error: error))
  338. }
  339. }
  340. }
  341. extension List where Element: MinMaxType {
  342. /**
  343. Returns the minimum (lowest) value in the list, or `nil` if the list is empty.
  344. */
  345. public func min() -> Element? {
  346. return _rlmArray.min(ofProperty: "self").map(dynamicBridgeCast)
  347. }
  348. /**
  349. Returns the maximum (highest) value in the list, or `nil` if the list is empty.
  350. */
  351. public func max() -> Element? {
  352. return _rlmArray.max(ofProperty: "self").map(dynamicBridgeCast)
  353. }
  354. }
  355. extension List where Element: AddableType {
  356. /**
  357. Returns the sum of the values in the list.
  358. */
  359. public func sum() -> Element {
  360. return sum(ofProperty: "self")
  361. }
  362. /**
  363. Returns the average of the values in the list, or `nil` if the list is empty.
  364. */
  365. public func average() -> Double? {
  366. return average(ofProperty: "self")
  367. }
  368. }
  369. extension List: RealmCollection {
  370. /// The type of the objects stored within the list.
  371. public typealias ElementType = Element
  372. // MARK: Sequence Support
  373. /// Returns a `RLMIterator` that yields successive elements in the `List`.
  374. public func makeIterator() -> RLMIterator<Element> {
  375. return RLMIterator(collection: _rlmArray)
  376. }
  377. #if swift(>=4)
  378. /**
  379. Replace the given `subRange` of elements with `newElements`.
  380. - parameter subrange: The range of elements to be replaced.
  381. - parameter newElements: The new elements to be inserted into the List.
  382. */
  383. public func replaceSubrange<C: Collection, R>(_ subrange: R, with newElements: C)
  384. where C.Iterator.Element == Element, R: RangeExpression, List<Element>.Index == R.Bound {
  385. let subrange = subrange.relative(to: self)
  386. for _ in subrange.lowerBound..<subrange.upperBound {
  387. remove(at: subrange.lowerBound)
  388. }
  389. for x in newElements.reversed() {
  390. insert(x, at: subrange.lowerBound)
  391. }
  392. }
  393. #else
  394. /**
  395. Replace the given `subRange` of elements with `newElements`.
  396. - parameter subrange: The range of elements to be replaced.
  397. - parameter newElements: The new elements to be inserted into the List.
  398. */
  399. public func replaceSubrange<C: Collection>(_ subrange: Range<Int>, with newElements: C)
  400. where C.Iterator.Element == Element {
  401. for _ in subrange.lowerBound..<subrange.upperBound {
  402. remove(at: subrange.lowerBound)
  403. }
  404. for x in newElements.reversed() {
  405. insert(x, at: subrange.lowerBound)
  406. }
  407. }
  408. #endif
  409. /// The position of the first element in a non-empty collection.
  410. /// Identical to endIndex in an empty collection.
  411. public var startIndex: Int { return 0 }
  412. /// The collection's "past the end" position.
  413. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
  414. /// zero or more applications of successor().
  415. public var endIndex: Int { return count }
  416. public func index(after i: Int) -> Int { return i + 1 }
  417. public func index(before i: Int) -> Int { return i - 1 }
  418. /// :nodoc:
  419. public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken {
  420. let anyCollection = AnyRealmCollection(self)
  421. return _rlmArray.addNotificationBlock { _, change, error in
  422. block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error))
  423. }
  424. }
  425. }
  426. #if swift(>=4.0)
  427. // MARK: - MutableCollection conformance, range replaceable collection emulation
  428. extension List: MutableCollection {
  429. #if swift(>=4.1)
  430. public typealias SubSequence = Slice<List>
  431. #else
  432. public typealias SubSequence = RandomAccessSlice<List>
  433. #endif
  434. /**
  435. Returns the objects at the given range (get), or replaces the objects at the
  436. given range with new objects (set).
  437. - warning: Objects may only be set during a write transaction.
  438. - parameter index: The index of the object to retrieve or replace.
  439. */
  440. public subscript(bounds: Range<Int>) -> SubSequence {
  441. get {
  442. return SubSequence(base: self, bounds: bounds)
  443. }
  444. set {
  445. replaceSubrange(bounds.lowerBound..<bounds.upperBound, with: newValue)
  446. }
  447. }
  448. /**
  449. Removes the specified number of objects from the beginning of the list. The
  450. objects are not removed from the Realm that manages them.
  451. - warning: This method may only be called during a write transaction.
  452. */
  453. public func removeFirst(_ number: Int = 1) {
  454. let count = Int(_rlmArray.count)
  455. guard number <= count else {
  456. throwRealmException("It is not possible to remove more objects (\(number)) from a list"
  457. + " than it already contains (\(count)).")
  458. return
  459. }
  460. for _ in 0..<number {
  461. _rlmArray.removeObject(at: 0)
  462. }
  463. }
  464. /**
  465. Removes the specified number of objects from the end of the list. The objects
  466. are not removed from the Realm that manages them.
  467. - warning: This method may only be called during a write transaction.
  468. */
  469. public func removeLast(_ number: Int = 1) {
  470. let count = Int(_rlmArray.count)
  471. guard number <= count else {
  472. throwRealmException("It is not possible to remove more objects (\(number)) from a list"
  473. + " than it already contains (\(count)).")
  474. return
  475. }
  476. for _ in 0..<number {
  477. _rlmArray.removeLastObject()
  478. }
  479. }
  480. /**
  481. Inserts the items in the given collection into the list at the given position.
  482. - warning: This method may only be called during a write transaction.
  483. */
  484. public func insert<C: Collection>(contentsOf newElements: C, at i: Int) where C.Iterator.Element == Element {
  485. var currentIndex = i
  486. for item in newElements {
  487. insert(item, at: currentIndex)
  488. currentIndex += 1
  489. }
  490. }
  491. #if swift(>=4.1.50)
  492. /**
  493. Removes objects from the list at the given range.
  494. - warning: This method may only be called during a write transaction.
  495. */
  496. public func removeSubrange<R>(_ boundsExpression: R) where R: RangeExpression, List<Element>.Index == R.Bound {
  497. let bounds = boundsExpression.relative(to: self)
  498. for _ in bounds {
  499. remove(at: bounds.lowerBound)
  500. }
  501. }
  502. #else
  503. /**
  504. Removes objects from the list at the given range.
  505. - warning: This method may only be called during a write transaction.
  506. */
  507. public func removeSubrange(_ bounds: Range<Int>) {
  508. removeSubrange(bounds.lowerBound..<bounds.upperBound)
  509. }
  510. /// :nodoc:
  511. public func removeSubrange(_ bounds: ClosedRange<Int>) {
  512. removeSubrange(bounds.lowerBound...bounds.upperBound)
  513. }
  514. /// :nodoc:
  515. public func removeSubrange(_ bounds: CountableRange<Int>) {
  516. for _ in bounds {
  517. remove(at: bounds.lowerBound)
  518. }
  519. }
  520. /// :nodoc:
  521. public func removeSubrange(_ bounds: CountableClosedRange<Int>) {
  522. for _ in bounds {
  523. remove(at: bounds.lowerBound)
  524. }
  525. }
  526. /// :nodoc:
  527. public func removeSubrange(_ bounds: DefaultRandomAccessIndices<List>) {
  528. removeSubrange(bounds.startIndex..<bounds.endIndex)
  529. }
  530. /// :nodoc:
  531. public func replaceSubrange<C: Collection>(_ subrange: ClosedRange<Int>, with newElements: C)
  532. where C.Iterator.Element == Element {
  533. removeSubrange(subrange)
  534. insert(contentsOf: newElements, at: subrange.lowerBound)
  535. }
  536. /// :nodoc:
  537. public func replaceSubrange<C: Collection>(_ subrange: CountableRange<Int>, with newElements: C)
  538. where C.Iterator.Element == Element {
  539. removeSubrange(subrange)
  540. insert(contentsOf: newElements, at: subrange.lowerBound)
  541. }
  542. /// :nodoc:
  543. public func replaceSubrange<C: Collection>(_ subrange: CountableClosedRange<Int>, with newElements: C)
  544. where C.Iterator.Element == Element {
  545. removeSubrange(subrange)
  546. insert(contentsOf: newElements, at: subrange.lowerBound)
  547. }
  548. /// :nodoc:
  549. public func replaceSubrange<C: Collection>(_ subrange: DefaultRandomAccessIndices<List>, with newElements: C)
  550. where C.Iterator.Element == Element {
  551. removeSubrange(subrange)
  552. insert(contentsOf: newElements, at: subrange.startIndex)
  553. }
  554. #endif
  555. }
  556. #else
  557. // MARK: - RangeReplaceableCollection support
  558. extension List: RangeReplaceableCollection {
  559. /**
  560. Removes the last object in the list. The object is not removed from the Realm that manages it.
  561. - warning: This method may only be called during a write transaction.
  562. */
  563. public func removeLast() {
  564. guard _rlmArray.count > 0 else {
  565. throwRealmException("It is not possible to remove an object from an empty list.")
  566. return
  567. }
  568. _rlmArray.removeLastObject()
  569. }
  570. }
  571. #endif
  572. // MARK: - Codable
  573. #if swift(>=4.1)
  574. extension List: Decodable where Element: Decodable {
  575. public convenience init(from decoder: Decoder) throws {
  576. self.init()
  577. var container = try decoder.unkeyedContainer()
  578. while !container.isAtEnd {
  579. append(try container.decode(Element.self))
  580. }
  581. }
  582. }
  583. extension List: Encodable where Element: Encodable {
  584. public func encode(to encoder: Encoder) throws {
  585. var container = encoder.unkeyedContainer()
  586. for value in self {
  587. try container.encode(value)
  588. }
  589. }
  590. }
  591. #endif
  592. // MARK: - AssistedObjectiveCBridgeable
  593. extension List: AssistedObjectiveCBridgeable {
  594. internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> List {
  595. guard let objectiveCValue = objectiveCValue as? RLMArray<AnyObject> else { preconditionFailure() }
  596. return List(rlmArray: objectiveCValue)
  597. }
  598. internal var bridged: (objectiveCValue: Any, metadata: Any?) {
  599. return (objectiveCValue: _rlmArray, metadata: nil)
  600. }
  601. }
  602. // MARK: - Unavailable
  603. extension List {
  604. @available(*, unavailable, renamed: "remove(at:)")
  605. public func remove(objectAtIndex: Int) { fatalError() }
  606. }