Swift generic function parameter as Class - ios

I'm not sure that this not duplicate. I have protocol and several classs that confurm to it.
protocol DbObject: class {
class func tableName() -> String
init(set: FMResultSet)
func save(db: FMDatabase)
}
And here how I use it:
func updateTable<T where T:DbObject>(nodes: [T]) {
self.db.executeUpdate("DELETE from \(T.tableName())")
for elem in nodes {
elem.save(self.db)
}
}
func loadAllFromObjectTable<T where T:DbObject>(cl: T) -> [T] {
var objArr = [T]()
if let set = db.executeQuery("select * from \(T.tableName())") {
while (set.next() ?? false) {
let obj = T(set: set)
objArr.append(obj)
}
}
return objArr
}
But I wanna that function loadAllFromObjectTable get as parameter class that confirms protocol, not object. How can I achieve that?
EDIT:
From here https://stackoverflow.com/a/26229630/820795
func loadAllFromObjectTable<T where T:DbObject>(_: T.Type) -> [T] {
var objArr = [T]()
if let set = db.executeQuery("select from \(T.tableName())") {
while (set.next() ?? false) {
if let obj = T(set: set)
objArr.append(obj)
}
}
return objArr
}
And usage:
manager.loadAllFromObjectTable(SignNote.self)

Related

How to combine two foreach to one in Swift?

I have one function which is having some logic which have 2 foreach loop but i want to make code compact so I am trying to use compactmap
func getData() -> [String] {
var ids = [String]()
self.item?.connections?.forEach { connection in
connection.validLine?.forEach { line in
if let _ = line.connection?.links[LinkKey.dataGroups],
let dataGroups = line.dataGroupsCache, dataGroups.isContinue {
ids += checkinGroups.connections?.compactMap { $0.id } ?? []
}
}
}
return ids
}
so instead of 2 foreach i am trying to make in one by using self.item?.connections?.compactMap({ $0.validline }) but I am getting error saying "Type of expression is ambiguous without more context"
I don't see how you can do it without to forEach or compactMap. Here is a possible solution:
func getData() -> [String] {
return item?.connections?.compactMap { connection in
connection.validLine?.compactMap { line in
guard let _ = line.connection?.links[LinkKey.dataGroups], line.dataGroupsCache?.isContinue == true else { return nil }
return checkinGroups.connections?.compactMap(\.id)
}
}
}
Here's a translation of your post into something that is compilable and a direct translation into a version that doesn't use forEach.
I changed connectionIds to ids in your example because otherwise, you might as well just return [].
class Example {
func getData() -> [String] {
var ids = [String]()
self.item?.connections?.forEach { connection in
connection.validLine?.forEach { line in
if let _ = line.connection?.links[LinkKey.dataGroups],
let dataGroups = line.dataGroupsCache, dataGroups.isContinue {
ids += checkinGroups.connections?.compactMap { $0.id } ?? []
}
}
}
return ids
}
func getDataʹ() -> [String] {
guard let connections = item?.connections else { return [] }
let numberOfProperLines = connections.flatMap { $0.validLine ?? [] }
.filter { line in
if let _ = line.connection?.links[LinkKey.dataGroups],
let dataGroups = line.dataGroupsCache, dataGroups.isContinue {
return true
} else {
return false
}
}
.count
return (0..<numberOfProperLines).flatMap { _ in checkinGroups.connections?.compactMap(\.id) ?? [] }
}
var checkinGroups: CheckInGroups!
var item: Item!
}
enum LinkKey: Int {
case dataGroups
}
struct Item {
let connections: [Connection]?
}
struct Connection {
let id: String?
let validLine: [Line]?
let links: [LinkKey: Void]
}
struct Line {
let dataGroupsCache: DataGroups?
let connection: Connection?
}
struct DataGroups {
let isContinue: Bool
}
struct CheckInGroups {
let connections: [Connection]?
}

is it possible to use Generic dynamic in Swift

protocol Base {
associatedtype M
var data:M { get set }
func update(data:M)
}
class ViewA : Base {
var data: String = ""
func update(data: String) {}
}
class ViewB : Base {
var data: Int = 2
func update(data: Int) {}
}
var dataArr : [Any] = ["1",2]
var viewArr : [Any] = [ViewA(), ViewB()]
func updatData() {
func update<C, T>(view:C, data:T) where C : Base, C.M == T {
view.update(data: data)
}
for i in 0..<2 {
let view = viewArr[i]
let data = dataArr[I]
// ! there is a errr here, Protocol 'Any' as a type cannot conform to 'Base'
update(view: view, data: data)
}
}
My Views conform to this 'Base' protocol which define what type of data my view use
And I want to implement this updatData function dynamic tell if data can be send to view (base on viwe.m type is same to data's type)
But it is seems to be impossible in Swift?
Array of Any object pass as Base Protocol create conflict.
so add one more class for Base class of ViewA and ViewB
protocol Base {
associatedtype M
var data: M { get set }
func update(data: M)
}
class Base1: Base {
typealias M = Any
var data: Any = ""
func update(data: Any) {
print("Udate \(data)")
}
}
class ViewA: Base1 {
//typealias M = String
//var data: String = ""
override func update(data: Any) {
print("test")
}
}
class ViewB: Base1 {
//typealias M = Int
//var data: Int = 2
override func update(data: Any) {
print(data)
print("Udate")
}
}
var dataArr: [Any] = ["1", 2]
var viewArr: [Any] = [ViewA(), ViewB()]
func updatData() {
func update<C, T>(view: C, data: T) where C: Base, C.M == T {
view.update(data: data)
}
for i in 0..<2 {
let view = viewArr[i]
let data = dataArr[i]
update(view: view as! Base1, data: data)
}
}
You want to create a type erased Base concrete type here: AnyBase:
public final class AnyBase: Base {
fileprivate let _boxed: _Box<M>
public init<Concrete: Base>(_ concrete: Concrete) where Concrete.M == M {
self._boxed = _ConcreteBox(concrete)
}
// Base conformance
public var data: M { _boxed.data }
public func update(data: M) {
_boxed.update(data: data)
}
// Type erasure
fileprivate class _Box<T>: Base {
init() {
guard type(of: self) != _Box.self else { fatalError("Can't create _Box instances, create a sub class instance instead ") }
}
// Base conformance
var base: M {
get { fatalError("Must override") }
set { fatalError("Must override") }
}
func update(data: M) {
fatalError("Must override")
}
}
fileprivate final class _ConcreteBox<Concrete: Base>: _Box<Concrete.M> where M == Concrete.M {
let _concrete: Concrete
init(_ concrete: Concrete) {
self._concrete = concrete
super.init()
}
// Base conformance
override var data: {
get { _concrete.data }
set { _concrete.data = newValue }
}
override func update(data: M) {
_concrete.update(data: data)
}
}
}
Now you can store different concrete instances of Base<M> in an array by adopting the type erased AnyBase<M> instead of using Any in your arrays.

Observation is not getting fired in Swift 4.2

Any ideas why Swift is not smart enough to infer the parameters passed to the observeWrapper function.
Code:
let implementation = QuestionJSONStrategy(name: questionGroup.course.rawValue)
_ = observeWrapper(implementation)
showQuestion()
}
func observeWrapper<T: NSObject & QuestionStrategy>(_ object: T) -> NSKeyValueObservation {
return object.observe(\.questionIndex, options: .new) { _, change in
guard let newValue = change.newValue else { return }
print(newValue)
}
}
QuestionStrategy Protocol:
#objc protocol QuestionStrategy :AnyObject {
var questions :[Question] { get set}
var questionIndex :Int { get set }
init(name :String)
func nextQuestion() -> Question
}
QuestionJSONStrategy Class:
#objc public class QuestionJSONStrategy :NSObject, QuestionStrategy {
var questions: [Question] = [Question]()
#objc dynamic var questionIndex: Int = 0

ArrayType in extension where clause

extension Array where Element: _ArrayType, Element.Generator.Element: Any {
func transpose() -> [Element] {
if self.isEmpty { return [Element]() }
let count = self[0].count
var out = [Element](repeating: Element(), count: count)
for outer in self {
for (index, inner) in outer.enumerated() {
out[index].append(inner)
}
}
return out
}
}
I am getting this error in Swift 3.0 after converting it from Swift 2.2. The elements of the array are also array. So how to define it in Swift 3.0?
extension Array where Element : Collection, Element.Index == Int, Element.IndexDistance == Int {
func transpose() -> [[Element.Iterator.Element]] {
typealias InnerElement = Element.Iterator.Element
if self.isEmpty { return [] }
let count = self[0].count
var out = [[InnerElement]](repeating: [InnerElement](), count: count)
for outer in self {
for (index, inner) in outer.enumerated() {
out[index].append(inner)
}
}
return out
}
}

RealmSwift: Convert Results to Swift Array

What I want to implement:
class func getSomeObject() -> [SomeObject]? {
let objects = Realm().objects(SomeObject)
return objects.count > 0 ? objects : nil
}
How can I return object as [SomeObject] instead if Results?
Weird, the answer is very straightforward. Here is how I do it:
let array = Array(results) // la fin
If you absolutely must convert your Results to Array, keep in mind there's a performance and memory overhead, since Results is lazy. But you can do it in one line, as results.map { $0 } in swift 2.0 (or map(results) { $0 } in 1.2).
I found a solution. Created extension on Results.
extension Results {
func toArray<T>(ofType: T.Type) -> [T] {
var array = [T]()
for i in 0 ..< count {
if let result = self[i] as? T {
array.append(result)
}
}
return array
}
}
and using like
class func getSomeObject() -> [SomeObject]? {
let objects = Realm().objects(SomeObject).toArray(SomeObject) as [SomeObject]
return objects.count > 0 ? objects : nil
}
With Swift 4.2 it's as simple as an extension:
extension Results {
func toArray() -> [Element] {
return compactMap {
$0
}
}
}
All the needed generics information is already a part of Results which we extend.
To use this:
let someModelResults: Results<SomeModel> = realm.objects(SomeModel.self)
let someModelArray: [SomeModel] = someModelResults.toArray()
This an another way of converting Results into Array with an extension with Swift 3 in a single line.
extension Results {
func toArray() -> [T] {
return self.map { $0 }
}
}
For Swift 4 and Xcode 9.2
extension Results {
func toArray<T>(type: T.Type) -> [T] {
return flatMap { $0 as? T }
}
}
With Xcode 10 flatMap is deprecated you can use compactMap for mapping.
extension Results {
func toArray<T>(type: T.Type) -> [T] {
return compactMap { $0 as? T }
}
}
Swift 3
extension Results {
func toArray<T>(ofType: T.Type) -> [T] {
var array = [T]()
for i in 0 ..< count {
if let result = self[i] as? T {
array.append(result)
}
}
return array
}
}
Usage
class func getSomeObject() -> [SomeObject]? {
let defaultRealm = try! Realm()
let objects = defaultRealm.objects(SomeObject.self).toArray(ofType : SomeObject.self) as [SomeObject]
return objects.count > 0 ? objects : nil
}
Alternative : Using generics
class func getSomeObject() -> [T]? {
let objects = Realm().objects(T.self as! Object.Type).toArray(ofType : T.self) as [T]
return objects.count > 0 ? objects : nil
}
it's not a good idea to convert Results to Array, because Results is lazy. But if you need try this:
func toArray<T>(ofType: T.Type) -> [T] {
return flatMap { $0 as? T }
}
but better way is to pass Results wherever you need. Also you can convert Results to List instead of Array.
List(realm.objects(class))
if the first func is not working you can try this one:
var refrenceBook:[RefrenceProtocol] = []
let faceTypes = Array(realm.objects(FaceType))
refrenceBook = faceTypes.map({$0 as FaceType})
Solution for Swift 4, Realm 3
extension Results {
func toArray<T>(ofType: T.Type) -> [T] {
let array = Array(self) as! [T]
return array
}
}
Now converting can be done as below
let array = Realm().objects(SomeClass).toArray(ofType: SomeClass.self)
I'm not sure, if there is any efficient way to do this.
But you can do it by create a Swift array and append it in the loop.
class func getSomeObject() -> [SomeObject]? {
var someObjects: [SomeObject] = []
let objects = Realm().objects(SomeObject)
for object in objects{
someObjects += [object]
}
return objects.count > 0 ? someObjects : nil
}
If you feel it's too slow. I recommend you to pass around Realm Results object directly.
extension Results {
var array: [Element]? {
return self.count > 0 ? self.map { $0 } : nil
}
}
So, you can use like:
Realm().objects(SomeClass.self).filter("someKey ENDSWITH %#", "sth").array
extension Results {
func materialize() -> [Element] {
return Array(self)
}
}
Using Swift 5 and RealmSwift v10.20.0
This methods works:
private func convertToArray<R>(results: Results<R>) -> [R] where R: Object {
var arrayOfResults: [R] = []
for result in results {
arrayOfResults.append(result)
}
return arrayOfResults
}

Resources