Why declare readonly property in protocol? - ios

Why declare readonly property in protocol if we can set value trough class or struct? I can not understand usage of this.
In "The Swift Programming Book" version 2.0
“If the protocol only requires a property to be gettable, the requirement can be satisfied by any kind of property, and it is valid for the property to be also settable if this is useful for your own code.”

So that it's not settable from outside the class/struct. Imagine your API returned some instance of a protocol that has a get and set property (in your protocol), then anyone getting this instance would be able to set the value!
Also get and set properties can't be constants:
protocol RWProt {
var value : Int { get set }
}
// Error: Type 'Value' does not conform to protocol 'RWProt'
struct Value : RWProt {
let value = 0
}
This however works:
protocol Read {
var value : Int { get }
}
struct Value : Read {
var value = 0
mutating func change() {
value++
}
}
The protocol only needs the value to be gettable, so get protocols properties are not get only but rather get or set
Okay, here is another example:
import Foundation
public protocol ExternalInterface {
var value : Int { get }
}
private struct PrivateStuff : ExternalInterface {
var value = 0
mutating func doSomePrivateChangingStuff() {
value = Int(arc4random())
}
}
public func getInterfaceToPrivateStuff() -> ExternalInterface {
var stuff = PrivateStuff()
stuff.doSomePrivateChangingStuff()
return stuff
}
// In another file:
let interfaceToSomethingICantChange = getInterfaceToPrivateStuff()
// error: cannot assign to property: 'value' is a get-only property
interfaceToSomethingICantChange.value = 0

Related

Understanding Swift default valued properties inside a Protocol extension

I have this sample protocol having a default valued property with extension.
protocol SampleProtocol{
var sample:String?{get set}
}
extension SampleProtocol{
var sample:String?{ get { return nil } set{} }
}
Now, my TestClass implements SampleProtocol as below.
class TestClass:SampleProtocol {
var sample: String?{
return "TestClass"
}
}
And there's one helper method that prints a sample value from the SampleProtocol.
func printValue(_ value: SampleProtocol){
print(value.sample)
}
Now the problem is
let testObj = TestClass()
print(testObj.sample) // prints "TestClass"
printValue(testObj) // prints nil
From the above result, I need to understand why when the testObj is typecasted into SampleProtcol, it is considering default implementation from extension instead of the implementation from the TestClass?
The problem is that the TestClass is not implementing the SampleProtocol so when you pass it in the printValue method that takes a SampleProtocol, it will call the default implementation in the protocol extension(since the instance you pass does not implement the protocol method).
In the SampleProtocol you have defined the variable as {get set} but in the TestClass variable you have only provided a getter, this does not match the requirements (If you remove the protocol extension you will see an error that the class does not conform to the protocol).
It will work if you provide a setter:
class TestClass: SampleProtocol {
var sample: String? {
get {
return "TestClass"
} set { }
}
}

How do I get get set to work with protocols?

I'm confused when using get set in protocols. Using only get works fine, but the set part doesnt'.
protocol MainViewModelProtocol {
var localDoor: LocalDoorCoreDataObject { get set }
}
extension MainViewModelProtocol {
var localDoor: LocalDoorCoreDataObject {
get { return MainViewModel.instance.localDoor }
set { localDoor = newValue }
}
}
final class MainViewModel: MainViewModelProtocol {
var localDoor: LocalDoorCoreDataObject = LocalDoorCoreDataObject()
...
Then when I use it in the viewController
self.mainViewModel.localDoor = $0
But this gives me the error
Cannot assign to property: 'mainViewModel' is a get-only property
How do I set it up properly?
EDIT
Initiation of the viewModel is done with factory based dependency injection
protocol MainViewModelInjected {
var mainViewModel: MainViewModelProtocol { get }
}
extension MainViewModelInjected {
var mainViewModel: MainViewModelProtocol { return MainViewModel.instance }
}
It is totally depends on how you create object for mainViewModel.
Let's create some cases with your code:
import UIKit
typealias LocalDoorCoreDataObject = String
protocol MainViewModelProtocol {
var localDoor: LocalDoorCoreDataObject { get set }
}
extension MainViewModelProtocol {
var localDoor: LocalDoorCoreDataObject {
get { return MainViewModel.instance.localDoor }
set { localDoor = newValue }
}
}
final class MainViewModel: MainViewModelProtocol {
static let instance = MainViewModel()
var localDoor: LocalDoorCoreDataObject = LocalDoorCoreDataObject()
}
protocol MainViewModelInjected {
var mainViewModel: MainViewModelProtocol { get }
}
extension MainViewModelInjected {
var mainViewModel: MainViewModelProtocol { return MainViewModel.instance }
}
Case 1
Here we are creating an object and assigning object through getter as a closure.
So, here mainViewModel has only getter not setter i.e. it'a get-only property.
var mainViewModel: MainViewModelProtocol { MainViewModel.instance }
mainViewModel.localDoor = "assign some thing" // Error: Cannot assign to property: 'mainViewModel' is a get-only property
Case 2
Here we are directly assigning object to mainViewModelOther. So, this will be a normal property and you can make changes in properties of model.
var mainViewModelOther: MainViewModelProtocol = MainViewModel.instance
mainViewModelOther.localDoor = "assign some thing"
Case 3
You can also create a class that will hold your model object, and created another object of your class. You can make changes in properties of model.
class MyClass {
var mainViewModel: MainViewModelProtocol = MainViewModel.instance
}
let myClassObj = MyClass()
myClassObj.mainViewModel.localDoor = "assign some thing"
TL;DR
Mark your MainViewModelProtocol as being class-only (i.e. protocol MainViewModelProtocol: class { ... }) to solve the issue.
The long answer
To understand why marking your MainViewModelProtocol as class-only fixes the problem, we need to take couple steps back and look at how structs and classes are stored internally.
Case 1: MainViewModelProtocol is a reference-type (i.e. class)
First, let's consider the case where MainViewModel is a class: Classes are reference-types, which means that after you retrieve the your view model through the mainViewModel property, you have a pointer to the same view model that is stored inside your view controller. Modifying the referenced type will also modify the view model of the view itself (since they both point to the same object). As an example
/* ... */
class MainViewModel: MainViewModelProtocol { /* ... */ }
var viewModel = myViewController.mainViewModel
viewModel.localDoor = /* something */
modifies the view model that's shared between the local variable viewModel and the view controller. This is exactly what you want.
Case 2: MainViewModelProtocol is a value type (i.e. struct)
Now let's consider if the MainViewModel was a struct: structs are value-types, so retrieving the view model through the mainViewModel computed property essentially clones the view model. Now you might modify the retrieved view model as much as you like locally, but there is no way assign it back to your view controller
/* ... */
struct MainViewModel: MainViewModelProtocol { /* ... */ }
var viewModel = myViewController.mainViewModel
viewModel.localDoor = /* something */
just modifies the local copy of the view model stored in the viewModel variable. There is no way to assign the local variable back to myViewController.
Conclusion
I hope this illustrates why your pattern only works with reference-types and not value types.
Now the Swift compiler needs to be conservative and consider both cases since it doesn't know if all types conforming to MainViewModelProtocol will be classes or structs (consider public protocols vended as a library to which library-users can conform). If you add the class-constraint to the protocol, you tell the compiler that using the pattern from Case 1 is totally fine – just grab a shared instance and modify it – and that there is no need for a setter to modify the view model.
No need to mark MainViewModelProtocol as class only, when the compiler says :
Cannot assign to property: 'mainViewModel' is a get-only property
it's actually complaining about your view controller implementation. I assume mainViewModel is a computed property so you can't assign it.
I managed to reproduce your error with the following playground :
typealias LocalDoorCoreDataObject = String
protocol MainViewModelProtocol {
var localDoor: LocalDoorCoreDataObject { get set }
}
extension MainViewModelProtocol {
var localDoor: LocalDoorCoreDataObject {
get { return MainViewModel.instance.localDoor }
set { localDoor = newValue }
}
}
final class MainViewModel: MainViewModelProtocol {
static let instance = MainViewModel()
var localDoor: LocalDoorCoreDataObject = LocalDoorCoreDataObject()
}
final class FakeVC {
var mainViewModel: MainViewModelProtocol {
MainViewModel.instance
}
}
var viewController = FakeVC()
viewController.mainViewModel.localDoor = "foo" // Cannot assign to property: 'mainViewModel' is a get-only property
I got rid of the error by changing FakeVC implementation to :
final class FakeVC {
var mainViewModel: MainViewModelProtocol = MainViewModel()
}

How to add variable in existing class in swift?

I know that in swift we can use Extensions to add new methods to existing classes.
But what about if i want to add a variable?
extension UIViewController {
var myVar = "xyz"
}
It gives like :
Extensions must not contain stored properties
We can't add the stored properties to extensions directly but we can have the computed variables.
extension UIViewController {
var myVar: String {
return "xyz"
}
}
Extensions in Swift can:
Add computed instance properties and computed type properties
...
For more please visit
https://docs.swift.org/swift-book/LanguageGuide/Extensions.html
You can only add computed properties to extensions as follows...
extension UIViewController {
var someProperty = "xyz" : String {
return "xyz"
}
}
If you wish to use it the way you are defining it, you might need to subclass your UIViewController
class YourCustomViewController: UIViewController {
var someProperty: String = "xyz"
}
you can only use computed variables:
for example we have the type Int in swift, and we want it extend in a way that swift generates a random number from 0 to our number :
extension Int
{
var arc4random : Int{
if self > 0
{return Int(arc4random_uniform(UInt32(UInt(self))))}
else if self < 0
{return -Int(arc4random_uniform(UInt32(UInt(abs(self)))))}
else
{return 0}
}
}
and usage :
myArray.count.arc4random
here my array.count is an Int , and arc4random is the computed variable we have defined in our extension, u cant store a value in it
You can try ( This is a readOnly computed property )
extension UIViewController {
var someProperty : String {
return "xyz"
}
}

Protocol Conformance of "Inherited" Property [duplicate]

protocol BasePresenterProtocol : class {}
protocol DashboardPresenterProtocol : BasePresenterProtocol {}
final class DashboardPresenter {
weak var view: DashboardPresenterProtocol?
init() {
self.view = DashboardViewController()
}
func test() {
print("Hello")
}
}
extension DashboardPresenter: DashboardViewProtocol { }
protocol BaseViewProtocol : class {
weak var view: BasePresenterProtocol? { get set }
}
protocol DashboardViewProtocol : BaseViewProtocol {
}
class DashboardViewController {
}
extension DashboardViewController: DashboardPresenterProtocol { }
In the above code, I get an error at following line
extension DashboardPresenter: DashboardViewProtocol { }
that, DashboardPresenter doesn't confirm to protocol DashboardViewProtocol, but I have declared weak var view: DashboardPresenterProtocol? in DashboardPresenter . Although I have declared
Why am I getting this error ? Please let me know what I am doing wrong in this code.
You cannot implement a read-write property requirement of type BasePresenterProtocol? with a property of type DashboardPresenterProtocol?.
Consider what would happen if this were possible, and you upcast an instance of DashboardPresenter to DashboardViewProtocol. You would be able to assign anything that conforms to BasePresenterProtocol to a property of type DashboardPresenterProtocol? – which would be illegal.
For this reason, a read-write property requirement has to be invariant (although it's worth noting that a readable-only property requirement should be able to be covariant – but this currently isn't supported).

Swift and property inheritance from superclass [duplicate]

This question already has answers here:
Overriding superclass property with different type in Swift
(15 answers)
Closed 6 years ago.
I have A class. And its subclass B. I need to override type of its property. Also that will be ok to to change a protocol. How can I do that?
class A {
var property: String (or SomeProtocolA)
}
class B: A {
var property: Int (or SomeProtocolB)
}
Maybe its possible to add support second protocol for property in subclass?
You can't, and this is indicative of poor design.
Suppose Class A had a function:
class A {
var property: String (or SomeProtocolA)
func getMyString() -> String {
return property
}
}
and now class B inherits it, whilst "overwriting" property:
class B : A {
var property: Int(or SomeProtocolB)
// func getMyString() -> String { //inherited from superclass
// return property //type error, expected String, returning Int
//}
}
You can do this, but in VERY limited situations. The only ways that this is allowed is under the following circumstances:
The property must be get only.
The overriding type must be a subclass of the original type (so no struct, protocol or enum).
Here is an example overriding with strings:
class A {
var property: NSString {
return ""
}
}
class B: A {
override var property: NSMutableString {
return NSMutableString(string: "")
}
}

Resources