How to define static constant in a generic class in swift?
You can define global constant with fileprivate
or private
access level in the same .swift
file where your generic class is defined. So it will not be visible outside of this file and will not pollute global (module) namespace.
If you need to access this constant from outside of current file then declare it as internal
(default access level) or public
and name it like ClassConstant
so it will be obvious that it relates to Class
.
Read more about access levels in Swift 3.
How to create an Single Class coexist with Generic in Swift
You can declare a generic type using a static computed property as follows:
class Single<T: Hashable> {
static var sharedInstance: Single? {
if self.sharedInstance != nil {
return self.sharedInstance
} else {
return Single()
}
}
var dic: [T: Any] = [:]
}
Is it necessary to pass a type parameter to static functions in a generic class?
GenericClass
is not a concrete type in Swift. There's no way to talk about it any more than you can talk about the type Array
without providing its type parameter. (The specific feature Swift lacks that would allow this is called "higher-kinded types.")
Static methods are tied to the concrete type (GenericClass<T>
) not to the higher-kinded type (GenericClass
). In order to access the static methods, it needs to know the actual type you want.
While it's true you're not currently using the type parameter in this class method, there is nothing stopping you (or a subclass!) from doing so. Since you have no way to promise that T
will never occur in this method, there's no way for Swift to allow you to ignore it.
swift - how to declare a static class within the project
It's not the class itself, the contents must be marked as static
class Theme {
// static constant
static let foo = "foo"
// static variable
static var foo2 : String { return "foo2" }
// static method
class func bar(x: Int) -> Int
{
return 2 * x
}
}
let a = Theme.foo // "foo"
let b = Theme.foo2 // "foo2"
let y = Theme.bar(10) // 20
How to add type methods to generic types in Swift?
When encountering an issue with generics that doesn’t work the way expect it’s often useful, to help understand the issue, to think about what would happen if you replaced a placeholder with different concrete types.
So for example, suppose you defined the following (this won’t compile for the reason you give, but imagine it did):
class C<T> {
static var a: [T] = []
static func addElement(i: T) {
a.append(i)
}
}
Really, when you write class C<T>
, you aren’t writing a class. You’re writing a blueprint for an infinite number of possible classes – C<Int>
, C<String>
, C<AnythingElse>
.
Under these circumstances, suppose you wrote C.addElement(1)
– so T
would be Int
. Then later, you wrote C.addElement("one")
. Would C.a
now contain one item, or two? What would the type of a
be?
Probably the most reasonable answer would be that there would be a C<Int>.a
with one element, and a C<String>.a
with one element. But this could get very confusing, and it doesn’t seem like there are use cases to justify this kind of functionality.
Generally, static methods and properties are best used rarely, and you may find you are better off with non-static members and methods, combined with a singleton pattern (or maybe not even that). If you still find the need for static-like functions, you may be better off using a generic free function (e.g. func emptyArchive<T: C>(c: C) { }
).
How do I define generic typealias for Swift to return specific types of objects?
As mentioned in the comments, T
is not defined at class-scope. You need to specify the generic type with the class declaration so it can be used across your class.
Try this:
class PersistentStoreCoordinatorMock<T: NSManagedObject>: Storageable {
var objects = [T]() // here I need to define return array
func findAll(of type: T.Type, predicate: NSPredicate) -> [T] {
findAllWasCalled = true
return objects //here I need to return this when that function was called
}
}
Access static variables within class in Swift
This is solved elegantly in Swift 5.1
you can access it via
Self.yourConstant
Reference: https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md
Related Topics
Switching a @State Property to a @Binding Property Interferes with Animation
Unresponsive Uibutton in Subview Added to Uistackview
Codable Enum with Multiple Keys and Associated Values
Differences Between Filtering Realm with Nspredicate and Block
Swift: Nstextfield Allow Only Specified Characters
Why Use Class Only Protocols in Swift
Add a Xib File to a Swift Package
How to Create Apple Watchos5 Complication
Swift Vscode Class in Other File Not Recognized
Resulting Mtltexture Lighter Than Cgimage
Color Keying Video with Gpuimage on a Scnplane in Arkit
How to Change Text Color of Actionsheet in Swiftui
Swift Generic Constraints in Init
Formula to Pick Every Pixel in a Bitmap Without Repeating
Best Way to Avoid Capturing a Copy of the Value in Closure
Xcode - Build Setting "Excluded_Source_File_Names" Not Working