What is a good alternative for static stored properties of generic types in swift?

swift extension static stored property
swift generics
static member cannot be used on protocol metatype
swift generic singleton
stored property in protocol swift
swift stored property
extensions must not contain stored properties
can we use stored property in extension

Since static stored properties are not (yet) supported for generic types in swift, I wonder what is a good alternative.

My specific use-case is that I want to build an ORM in swift. I have an Entity protocol which has an associatedtype for the primary key, since some entities will have an integer as their id and some will have a string etc. So that makes the Entity protocol generic.

Now I also have an EntityCollection<T: Entity> type, which manages collections of entities and as you can see it is also generic. The goal of EntityCollection is that it lets you use collections of entities as if they were normal arrays without having to be aware that there's a database behind it. EntityCollection will take care of querying and caching and being as optimized as possible.

I wanted to use static properties on the EntityCollection to store all the entities that have already been fetched from the database. So that if two separate instances of EntityCollection want to fetch the same entity from the database, the database will be queried only once.

Do you guys have any idea how else I could achieve that?

Static/Class stored properties in generic types? - Using Swift, What is a good alternative for static stored properties of generic types in swift? From the user's perspective, defining a static constant in a generic is a common scenario and should be well supported. There are two types of properties in Swift: stored properties and computed properties. Stored properties store values (constant or variable) as part of an instance or type, whereas computed properties don’t have a stored value. Hint: This post has been updated to Swift 4

I'm not sure if I like this yet or not, but I used a static computed property:

private extension Array where Element: String {
    static var allIdentifiers: [String] {
        get {
            return ["String 1", "String 2"]
        }
    }
}

Thoughts?

swift: What is a good alternative for static stored properties of generic , Since static stored properties are not (yet) supported for generic types in swift, I wonder what is a good alternative.My specific use-case is that I want to build an  In addition to properties, you can use instance variables as a backing store for the values stored in a property. Swift unifies these concepts into a single property declaration. A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly.

An hour ago i have a problem almost like yours. I also want to have a BaseService class and many other services inherited from this one with only one static instance. And the problem is all services use their own model (ex: UserService using UserModel..)

In short I tried following code. And it works!.

class BaseService<Model> where Model:BaseModel {
    var models:[Model]?;
}

class UserService : BaseService<User> {
    static let shared = UserService();

    private init() {}
}

Hope it helps.

I think the trick was BaseService itself will not be used directly so NO NEED TO HAVE static stored property. (P.S. I wish swift supports abstract class, BaseService should be)

Protocol-oriented programming & generics, What is a good alternative for static stored properties of generic types in swift? Thank you very much for taking your time to read this, I hope you have a great day ^^ iForget: A Swift + SwiftUI tutorials using iBeacon for reminding important​  Functions are first-class objects in Swift, meaning that they can be assigned to variables, stored in properties, and passed as arguments or returned as values from other functions. What distinguishes function types from other values is that they’re callable , meaning that you can invoke them to produce new values.

It turns out that, although properties are not allowed, methods and computed properties are. So you can do something like this:

class MyClass<T> {
    static func myValue() -> String { return "MyValue" }
}

Or:

class MyClass<T> {
    static var myValue: String { return "MyValue" }
}

`shared` members and metatypes for generic types - Pitches, In this tutorial, we will explore protocols - an alternative to subclassing that allows you to achieve similar Note that enums cannot contain stored properties. in the first example and static dispatch in the second on protocols in Swift. Refer to the following Apple documentation for a good example of this. From the Apple docs: “Types that conform to the Equatable protocol can be compared for equality using the equal-to operator (==) or inequality using the not-equal-to operator (!=).” That’s why my generic function “exists” works with Swift types like String, Integer, Float, and Double. All these types define the == and != operators.

Well I also ran into the same problem and was able to device a logical work around for it. I had to create a static instance of urlsession using a generic class as handler.

class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    let neworkHandler = NetworkHandler<String>()
    neworkHandler.download()
    neworkHandler.download()
}


class SessionConfigurator: NSObject{
static var configuration:URLSessionConfiguration{
    let sessionConfig = URLSessionConfiguration.background(withIdentifier: "com.bundle.id")
    sessionConfig.isDiscretionary = true
    sessionConfig.allowsCellularAccess = true
    return sessionConfig
}
static var urlSession:URLSession?


class NetworkHandler<T> :NSObject, URLSessionDelegate{
  func download(){
    if SessionConfigurator.urlSession == nil{
    SessionConfigurator.urlSession = URLSession(configuration:SessionConfigurator.configuration, delegate:self, delegateQueue: OperationQueue.main)
    }
}

Stored properties and extensions: a pure Swift approach, Type . This shared metatype would provide storage for properties. protocol P { static func doSomething() } shared extension Foo: MyProtocol common or unbound but those are the best alternatives I've come up with so far. Swift 4 provides a flexible property called 'Lazy Stored Property' where it won't calculate the initial values when the variable is initialized for the first time. 'lazy' modifier is used before the variable declaration to have it as a lazy stored property.

4. Object Types, How many times have you wished a stored property within your of the extended class will share the same static value from the Holder struct. Generics (C# Programming Guide) 07/20/2015; 3 minutes to read +8; In this article. Generics introduce the concept of type parameters to .NET, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

Extensions May not contain Stored properties, A static/class property, on the other hand, is accessed through the type, and is class MyClass { var s = "" func store(s:String) { self.s = s } } let m = MyClass() let f A mutating instance method can even replace this instance with another It is important to understand that generics do not in any way relax Swift's strict typing. Swift 4 also provides 'deinitialization' process for performing memory management operations once the instances are deallocated. Initializer Role for Stored Properties. Stored property have to initialize the instances for its classes and structures before processing the instances.

Swift Enumerations, A static stored property in a protocol extension would require separate The reason that Swift doesn't currently support static stored properties on generic types is Replace new tab page with a personal dashboard featuring to-do, weather,  Persist Data. In this lesson, you save a meal list across FoodTracker app sessions. Understanding and implementing data persistence is a vital part of iOS app development. iOS has many persistent data storage solutions; in this lesson, you’ll use NSCoding as the data persistence mechanism in the FoodTracker app. NSCoding is a protocol that enables a lightweight solution for archiving objects

Comments
  • I think this would compile but create a new copy each time and behave like a non-static property
  • Swift does not support multiple inheritance and this requires subclassing . So this solution does not scale to mixins .
  • This will return a new copy every time, defeating the purpose of having a static property!
  • @user1366265 Not necessarily. With a little juggling (especially if thread safety is an issue), you can cache the value, usually in a global variable.
  • This is not ideal as you say but then swift shortcomings are there .. so this is a workaround.
  • That doesn't work for me since I'm working with GENERIC types and those types don't allow static stored properties. That's exactly why I'm posting this question...
  • Maybe you can change cache be a global variable of type [AnyObject] and within EntityCollection methods casted to [T]?
  • The goal is to have a protocol and an extension for it. Not a concrete class.