How do I express this setter pattern in Swift? - objective-c

We usually do things lik
- (void)setFoo:(Foo *)foo
{
_foo = foo;
// other computation
}
Getter and Setters give me warning that I cant set my own property. I am guessing it needs a computed property. What would be the best way to translate this idiom in Swift?

If you're doing computation tightly integrated with setting the internal storage of foo, especially if setting the storage is conditional on such computation, the computed-property/stored-property pair #matt suggests is probably the solution you need.
Otherwise—if you need to need to do work unconditionally in response to the setting of a property—what you're looking for is Swift's property observers feature.
var foo: Foo {
willSet(newFoo) {
// do work that happens before the internal storage changes
// use 'newFoo' to reference the value to be stored
}
didSet {
// do work that happens after the internal storage changes
// use 'oldValue' to reference the value from before the change
}
}

You can "shadow" a public computed variable with a stored private variable, like this:
private var _foo : Foo!
var foo : Foo {
get {
return _foo
}
set (newfoo) {
_foo = newfoo
}
}
That is the analogy to what Objective-C #synthesize does. But you should also ask yourself whether you really need this. In most cases, you don't.

Related

What do you call a variable that has a getter and setter defined, with no backing variable?

What is it called when you define a variable/property with a getter and setter, such that the language does not automatically generate a backing variable?
E.g. in Swift, we could define a modalViewController property that doesn't create a backing variable:
extension MyViewController {
var modalViewController: UIViewController? {
get { return self.presentedViewController }
set { self.present(newValue, animated: true) }
}
}
What's the proper term to describe the modalViewController property?
I know that if it's only gettable, it would be called a computed property:
extension Int {
var isEven: Bool {
get { return self % 2 == 0 }
}
}
However, I'm looking for a term for something that is both settable and gettable.
The reason I'm looking for a term is that I want to ask a question related to these types of properties, and would like to use common, non-ambiguous language. I thought this would be called a virtual property, but it doesn't appear to be the proper name as virtual has a different meaning in OOP.
Even though they have a setter too, Swift (at least) calls these "computed properties" (emphasis added):
In addition to stored properties, classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

What is the use of open properties in Kotlin?

I have been learning Kotlin and have come across the concept of open properties. Coming from C++, the concept of "open" makes sense, and extending that logic to properties does as well. However, I can't think of any case where an open val/var is actually necessary or useful. I understand when they make sense for interfaces, but not concrete classes. Furthermore, overriding getters/setters makes sense, but not redefining the property with a new backing field. For example, say you have this kind of class structure:
open class Foo {
open var str = "Hello"
}
class Bar : Foo() {
override var str = "world"
init {
println(str)
println(super.str) // Shows that Bar actually contains "hello" and "world"
}
}
To me, it would seem to be a far better design to make Foo take str as a constructor argument, for instance:
open class Foo(var str = "Hello") // Maybe make a secondary constructor
class Bar : Foo("world") // Bar has only 1 string
This is both more concise, and seems to often be a better design. This is also the way it tends to be done in C++, so maybe I just don't see the benefit of the other way. The only possible time I can see overriding a val/var with a new one is if it for some reason needs to use super's value, like in
override val foo = super.foo * 2
Which still seems pretty contrived.
When have you found this useful? Does it allow for greater efficiency or ease of use?
open fields let you re-define getter and setter methods. It's practically pointless if you just return constants. However altering getter / setter behavior has (infinite) potential, so I'll just throw some ideas:
// propagate get/set to parent class
class Bar : Foo() {
override var str
get() = super.str.toUpperCase()
set(value) {
super.str = value
}
}
// creates a backing field for this property
class Bar : Foo() {
override var str = "World"
get() = field.toLowerCase()
// no need to define custom set if we don't need it in this case
// set(value) { field = value }
}
// instead of writing custom get/set, you can also use delegates
class Bar : Foo() {
override var str by Delegates.observable("world"){ prop, old, new ->
println("${prop.name} changed from $old to $new")
}
}

Kotlin: automatic getter not accessible in lambda

Kotlin supposedly creates getters and setters automatically, but...
class Foo {
var id = 1
}
class Bar {
var foos = listOf(Foo())
fun printFooIds() {
foos.forEach { println(it.id) } // works
foos.forEach { println(it.getId()) } // error "Unresolved reference: getId"
}
}
Why the error? How can we access the auto-generated getter here?
When you write down foo.id (or it.id) in Kotlin, you are accessing the property through its getter, whether it's the default one that returns the backing field or a custom one you wrote for it.
val id = foo.id // this calls the getter
foo.id = 1 // this calls the setter
What you're seeing isn't an error, you're supposed to be using foo.id to read the property when you're writing Kotlin code.
Reading a property both with the property access syntax foo.id and foo.getId() is only an option when you're accessing Java properties from Kotlin. The second call is the original Java syntax of course, and the first is a Kotlin-to-Java interop feature to make the syntax more Kotlin-friendly.
Similarly, for Java-to-Kotlin interop, you will see the property as a getter-setter pair from Java, and use it like this:
foo.getId()
foo.setId(1)

Creating an enum in Swift, exportable to ObjC, based on another enum: String

I have an enum Foo: String in Swift (therefore not exportable to Objective-C) and I'm trying to create another enum FooObjc in Swift to kinda "wrap" the existent one so that it is 1) available to use in Objective-C and 2) convertable back and forth (Foo <=> FooObjc). The original Foo enum is part of a framework that I don't want to modify. Of course, it's very easy to do what I want if I use a class instead, like this:
#objc public class FooObjc: NSObject {
public private(set) var foo: Foo
#objc public var string: String {
return foo.rawValue
}
#objc public init?(string: NSString) {
guard let foo = Foo(rawValue: string as String) else {
return nil
}
self.foo = foo
}
internal init(foo: Foo) {
self.foo = foo
}
}
(PS: not able to inherit from NSString because the Swift compiler still doesn't accept creating initializers for that class)
Ok, but I definitely don't like this approach because then my Objective-C code will be string-typed. I really want to use an enum instead because after all, that's what it is. This is the least bad working version I could get:
#objc public enum FooObjc: Int, RawRepresentable {
case undefined = -1
case bar
case baz
// omitting many more cases
internal init?(_ foo: Foo?) {
if let foo = foo {
self = fooMapping.filter { $1 == foo }.map { $0.key }.first!
} else {
self = .undefined
}
}
// MARK: - RawRepresentable
public typealias RawValue = String
public init?(rawValue: RawValue) {
let filter = fooMapping.filter { $1?.rawValue == rawValue }
guard filter.count > 0 else {
return nil
}
self = filter.map { $0.key }.first!
}
public var rawValue: RawValue {
switch (self) {
case .undefined: return "undefined"
case .bar: return Foo.bar.rawValue
case .baz: return Foo.baz.rawValue
// omitting many more cases
}
}
}
private let fooMapping: [FooObjc: Foo?] = [
.undefined : nil,
.bar : .bar,
.baz : .baz
// omitting many more cases
]
Notice that:
the fooMapping is useful to avoid one switch-case for each initializer
this undefined case was necessary because in Swift you can have optional enum properties, in Objective-C you can't, so this case will directly map to a Foo? which value is nil.
What worries me here is that I had to write the same cases from the original Foo three times... I'm completely satisfied if I repeat it only twice, but I wasn't able to use the fooMapping in the rawValue property because then I get a cycle between these two.
Note: I'm not sure if this is relevant to the question, but in the original enum, some of the cases have special String attributions, e.g. we have simply case bar but we also have case baz = "something".
So, the question is: does anyone have suggestions to improve this approach or even suggest something completely new that would avoid so much code repetition?
Thank you very much!
What worries me here is that I had to write the same cases from the original Foo three times
Consider an array ["bar", "baz" ...]. By looking at the index of a string in this array and making the necessary adjustments, you can translate from a string to an integer (and thence, via raw value, to a case). By indexing into the array and making the necessary adjustments, you can translate from an integer to a string (and thence, via raw value, to a case). So you will only have to write out the string values once. This eliminates two of your repetitions.
You will still have to write out the case names in the enum declaration, because there's no other way to tell Objective-C the names of the cases. The way to eliminate that repetition, obviously, is to be willing to change the implementation of Foo itself so that it becomes Objective-C-compatible. But you have stated up front that you refuse to do that, so now you must pay the price.

Best design for lookup-and-possibly-change method

I am designing a class that stores (caches) a set of data. I want to lookup a value, if the class contains the value then use it and modify a property of the class. I am concerned about the design of the public interface.
Here is how the class is going to be used:
ClassItem *pClassItem = myClass.Lookup(value);
if (pClassItem)
{ // item is found in class so modify and use it
pClassItem->SetAttribute(something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass).
To get round that the following could be considered:
bool found = myClass.Lookup(value);
if (found)
{ // item is found in class so modify and use it
myClass.ModifyAttribute(value, something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
However this is inefficient as Modify will have to do the lookup again. This would suggest a lookupAndModify type of method:
bool found = myClass.LookupAndModify(value, something);
if (found)
{ // item is found in class
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
But rolling LookupAndModify into one method seems like very poor design. It also only modifies if value is found and so the name is not only cumbersome but misleading as well.
Is there another better design that gets round this issue? Any design patterns for this (I couldn't find anything through google)?
Actually std::set<>::insert() does precisely this. If the value exists, it returns the iterator pointing to the existing item. Otherwise, the iterator where the insertion was made is returned.
It is likely that you are using a similar data structure for fast lookups anyway, so a clean public interface (calling site) will be:
myClass.SetAttribute(value, something)
which always does the right thing. MyClass handles the internal plumbing and clients don't worry about whether the value exists.
Two things.
The first solution is close.
Don't however, return ClassItem *. Return an "opaque object". An integer index or other hash code that's opaque (meaningless) to the client, but usable by the myClass instance.
Then lookup returns an index, which modify can subsequently use.
void *index = myClass.lookup( value );
if( index ) {
myClass.modify( index, value );
}
else {
myClass.add( value );
}
After writing the "primitive" Lookup, Modify and Add, then write your own composite operations built around these primitives.
Write a LookupAndModify, TryModify, AddIfNotExists and other methods built from your lower-level pieces.
This assumes that you're setting value to the same "something" in both the Modify and Add cases:
if (!myClass.AddIfNotExists(value, something)) {
// use myClass
}
Otherwise:
if (myClass.TryModify(value, something)) {
// use myClass
} else {
myClass.Add(value, otherSomething);
}