Consider the following:
protocol SomeProtocol: Equatable {}
// then, elsewhere...
var someValue: Any?
func setSomething<T>(_ value: T) where T: SomeProtocol {
someValue = value
}
func getSomething<T>() -> T? where T: SomeProtocol {
return someValue as? T
}
These functions work fine but essentially act like computed properties. Is there any way to implement something like the following?
var something<T>: T where T: SomeProtocol {
get { return someValue as? T }
set { someValue = newValue }
}
Thank you for reading. Apologies if this question has already been asked elsewhere, I have searched but sometimes my search fu is weak.
Swift Computed Property For example, class Calculator { // define stored property var num1: Int = 0 ... } Here, num1 is a stored property, which stores some value for an instance of Calculator . Here, sum is a computed property that doesn't store a value, rather it computes the addition of two values.
Example: Swift Generic Function In the above example, we have created a generic function named displayData() with the type parameter <T> . we have passed a string value, so the placeholder parameter T is automatically replaced by String . the placeholder is replaced by Int .
Generics allow you to declare a variable which, on execution, may be assigned to a set of types defined by us. In Swift, an array can hold data of any type. If we need an array of integers, strings, or floats, we can create one with the Swift standard library.
Swift enables us to create generic types, protocols, and functions, that aren't tied to any specific concrete type — but can instead be used with any type that meets a given set of requirements.
You need to define the computed property on a generic type, the computed property itself cannot define a generic type parameter.
struct Some<T:SomeProtocol> {
var someValue:Any
var something:T? {
get {
return someValue as? T
}
set {
someValue = newValue
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With