Swift computed property to return copy of underlying array - swift

I have a model class written in Objective-C that I'm converting to Swift. It contains an NSMutableArray internally, but the method signature for the getter, as well as the actual return value, are NSArray. When called, it creates an immutable copy to return.
Essentially, I want callers to be able to iterate/inspect the container, but not modify it. I have this test snippet:
class Container {
internal var myItems = [String]()
func sayHello() {
"I have: \(myItems)"
}
}
let cont = Container()
cont.myItems.append("Neat") // ["Neat"]
cont.sayHello() // This causes sayHello() to print: "I have: [Neat]"
var isThisACopy = cont.myItems
isThisACopy.append("Huh") // ["Neat", "Huh"]
cont.sayHello() // This ALSO causes sayHello() to print: "I have: [Neat]"
I've been trying to find a way to override the getter for myItems so that it returns an immutable copy, but can't seem to determine how.
Attempt #1
This produces a compiler error: Function produces expected type '_ArrayBuffer<(String)>'; did you mean to call it with '()'?
internal var myItems = [String]() {
var copy = [String]()
for item in ... { // What to use in the ...?
copy.append(item)
}
return copy
}
Attempt #2
This also produces a compiler error, because I'm (understandably) redefining the generated getter Invalid redeclaration of 'myItems()':
internal func myItems() -> [String] {
var copy = [String]()
for item in myItems {
copy.append(item)
}
return copy
}

Try this:
class Container {
private var _myItems: [String] = ["hello"]
internal var myItems: [String] {
return _myItems
}
}
let cont = Container()
cont.myItems.append("Neat") //not allowed
It uses a private stored property and a computed property that returns an immutable copy. It's not possible for a stored property to use custom getters.

A better way to expose mutable properties as immutable:
class Container {
private (set) internal var myItems: [String]
}

Related

Accessing a lazy property on a struct mutates the struct

I have a lazy property in a struct and every time I access it, it mutates the struct.
var numbers = [1,2,3]
struct MyStruct {
lazy var items = numbers
}
class MyClass {
var myStructPropery: MyStruct = MyStruct() {
didSet {
print(myStructPropery)
}
}
}
var myClass = MyClass()
myClass.myStructPropery.items
myClass.myStructPropery.items
myClass.myStructPropery.items
Result:
Print (didSet) will be called every time.
The ideal behaviour should be first time mutation only (since that's how lazy variables behave). Is this a bug in Swift or am I doing something wrong?
What you are seeing is is that the observed property items has notified its observer that it has been mutated because it was accessed, and a lazy variable is by definition mutating since it will be set at a later time. Therefore didSet gets called to handle this.
The lazy variable is actually only set once even though it signals that it has mutated and the property myStructPropery is only mutated once when the variable is first set but is the same instance after that.
Here is how we can verify this, first change the lazy var declaration so it's more like how we usually declare such a variable
lazy var items: [Int] = { numbers }()
and then add a print statement
lazy var items: [Int] = {
print("inside lazy")
return numbers
}()
If we now run the test code
var myClass = MyClass()
myClass.myStructProperty.items
myClass.myStructProperty.items
myClass.myStructProperty.items
we see that "inside lazy" only prints once. To verify that the property myStructProperty isn't changed we can make the struct conform to Equatable and perform a simple check inside didSet
didSet {
if oldValue != myStructProperty {
print(myStructProperty)
}
}
Now running the test we see that the print inside didSet is never executed so myStructProperty is never changed.
I have no idea if this behaviour is a bug but personally it feels like it might be complicate for the property observer to stop observing a lazy property once it was accessed or for a lazy var to not be defined as mutating once it is set.
I started debugging this with following set up -
var numbers = [1,2,3]
struct MyStruct {
lazy var items = numbers
}
class MyClass {
var myStructPropery: MyStruct = MyStruct() {
didSet {
// Changed this to make sure we are not invoking getter here
print("myStructPropery setter called")
}
}
}
let myClass = MyClass()
myClass.myStructPropery.items
myClass.myStructPropery.items
myClass.myStructPropery.items
I can reproduce the problem on Xcode 12.5 using Swift 5.4.
Attempt 1 : Turn var numbers into let numbers - Does NOT work.
let numbers = [1,2,3]
Attempt 2 : Assign the value inline without using an extra variable - Does NOT work.
struct MyStruct {
lazy var items = [1,2,3]
}
Attempt 3 : Assign the value inline using the full blown getter syntax - Does NOT work.
struct MyStruct {
lazy var items: [Int] = {
return [1,2,3]
}()
}
At this point, we are out of options to try. Even though we can clearly see that return [1,2,3] in the last attempt is executed exactly once, the MyClass.myStructPropery.modify is called repeatedly on access to items.
Maybe Swift Forums is a better place to discuss this.

How to implement read-only var with mutating get

I have a var
var soketTasksList:Set<SocketTask> {
get { return socketManager.tasksList }
}
I don't need to set, only get,
but I need do something like this
soketTasksList.remove(task)
but compiler says
Cannot use mutating member on immutable value is a get-only property
I tried to add the keyword 'mutating' to the get, but this isn't working. I also
tried to add 'mutating' to the var, but this isn't working either.
UPD
i dont undestand why do I need set?
if i do
func getSoketTasksList() -> Set<CXSocketTask> {
return socketManager.tasksList
}
i can
getSoketTasksList().remove(task)
why not with var?
i don't need to set, only get
Yes, you do need to set.
i need do something like this soketTasksList.remove(task)
That is a mutation. Mutating a value type like Set requires the ability to set. But you have cut off that possibility by making this a read-only computed variable.
UPD i dont undestand why do I need set? if i do
func getSoketTasksList() -> Set<CXSocketTask> {
return socketManager.tasksList
}
i can
getSoketTasksList().remove(task)
No you can't. Try it. Here's a playground test:
class CXSocketTask:NSObject{}
class SocketManager {
var tasksList = Set<CXSocketTask>()
}
let task = CXSocketTask()
let socketManager = SocketManager()
socketManager.tasksList.insert(task)
func getSoketTasksList() -> Set<CXSocketTask> {
return socketManager.tasksList
}
getSoketTasksList().remove(task)
The last line generates an error: "cannot use mutating member on immutable value: 'getSoketTasksList' returns immutable value".
You can use temporary variable for this purpose:
var list = soketTasksList
list.remove(task)
Note that underlying list (socketManager.tasksList in this case) remains untouched.
The only situation in which you can do this is if the actual mutating is done through something which is settable.
For example:
struct Person {
var age: Int = 1
mutating func setAge(a: Int) -> Int {
age = a
return a
}
var computedAge: Int {
mutating get {
setAge(a: 4)
return age
}
}
}
var person = Person()
print(person.computedAge) //Prints 4
This is by design

Swift protocol settable property through a read-only property [duplicate]

This question already has an answer here:
Swift: Failed to assign value to a property of protocol?
(1 answer)
Closed 6 years ago.
Can someone please tell me why Swift has to call the setter of a property when it's only being used to access an object (a protocol) in order to set one of its properties? This first example shows the error I get if I don't declare the indirect object as settable:
protocol AProtocol {
var name: String { get set }
}
class AnImplementation: AProtocol {
var name = ""
}
class AParent {
var test = AnImplementation()
}
class AChild {
var parent: AParent!
var test: AProtocol {
get { return parent.test }
// Note: Not settable
}
}
var parent = AParent()
var child = AChild()
child.parent = parent
child.test.name = "Hello world!" // Error: Cannot assign to property : 'test' is a get-only property
print(child.test.name)
If I give it a setter, it compiles and works but it calls the setter:
protocol AProtocol {
var name: String { get set }
}
class AnImplementation: AProtocol {
var name = ""
}
class AParent {
var test = AnImplementation()
}
class AChild {
var parent: AParent!
var test: AProtocol {
get { return parent.test }
set(newTest) { print("Shouldn't be here!") }
}
}
var parent = AParent()
var child = AChild()
child.parent = parent
child.test.name = "Hello world!"
print(child.test.name)
Output is:
Shouldn't be here!
Hello world!
I'm not sure what I'm not understanding here. I assume I can just give it an empty setter, but I'd like to understand the reason for it.
Any information is much appreciated!
Change your protocol declaration to this:
protocol AProtocol:class {
var name: String { get set }
}
Otherwise, it is taken by default as a value type. Changing a value type's property replaces the value type instance (as shown by the setter observer). And you can't do that if the reference is a let reference.
This is probably caused by the fact that the compiler doesn't know whether AChild.test is a class or a value type. With classes there is no problem but with value types assigning to name would also create an assignment to test (value-copy behavior). Marking APProtocol as class protocol will fix the problem.
To expand, when the compiler is not sure whether test is a value or a class type, it will use the following rewrite of child.test.name = "Hello world!":
var tmp = child.test
tmp.test = "Hello world!"
child.test = tmp
because that will work for both class and value types.

how to create a singleton in swift with init variables

I am trying to create a singleton class in swift but I am getting an error
"cannot create a single-element tuple with an element label"
i am not getting it.
class GroupObject {
// we want the group object to be a singleton
var name: String
var id: Int
var groupJsonObject: JSON
init(groupJsonObject: JSON){
self.groupJsonObject = groupJsonObject
self.id = groupJsonObject["id"].int!
self.name = groupJsonObject["name"].string!
}
class var sharedInstance : GroupObject {
struct Static {
static let instance : GroupObject = GroupObject(groupJsonObject: JSON) // this is the problem line.
}
return Static.instance
}
}
The problem is that you cannot pass a parameter to the singleton. Your singleton implementation doesn't know to what JSON refers.
If you want this to be a singleton, you'd have to initialize the groupJsonObject separately from the initialization of the shared instance. For example:
class GroupObject {
var name: String!
var id: Int!
var groupJsonObject: JSON! {
didSet {
id = groupJsonObject["id"].int!
name = groupJsonObject["name"].string!
}
}
static let sharedInstance = GroupObject() // btw, this is a more concise syntax for declaring a singleton
}
And then, when you want to initialize those properties, you could do:
GroupObject.sharedInstance.groupJsonObject = json
If your "singleton" is supposed to hold some data passed to it on instantiation, how will it get that data? Where/when is it available?
I think you don't actually want a singleton at all; you want an instance created with your JSON data to be accessible from different points in your application. In that case, pick some "master controller", create it there, then pass it along to other controllers as needed.

How to call instance method inside class using Swift

I am having an issue with calling an instance method within the class itself. If someone can provide me some insight it would be greatly appreciated.
My current code looks like this:
class Rect
{
func printthis() -> String {
return "this is working or what"
}
var toPrint:String = self.printthis()
}
The error I am getting in Xcode is: Use of unresolved identifier 'self'.
What am I missing here?
You can't call an instance method without an instance. The class is merely the template for instances. So i don't what you are trying to do here...
But the answer is no, you cannot call an instance method form the class definition because there is no instance yet.
Perhaps you want to delcare a class method and use that to set an instance variable on creation? If so, you might do that like this:
class Rect {
class func printthis() -> String {
return "this is working or what"
}
var toPrint:String
init() {
toPrint = Rect.printthis()
}
}
var r = Rect()
println(r.toPrint) //-> this is working or what
An instance of a class is not initialized and able to be referenced (even as 'self') until all of its variables have been assigned values.
An option that may work for you is to declare your variable as an implicitly-unwrapped optional, which is assigned nil by default. Then in the class's init method, since all of the variables have been assigned values, you are able to start calling methods on your instance.
class Rect {
var toPrint: String!
init() {
toPrint = printthis()
}
printthis() -> String {
return "this will work"
}
}
the problem is that swift is strict about initing all properties.
you may as a workaround
class Rect
{
func printthis() -> String {
return "this is working or what"
}
var toPrint:String = ""
init() {
toPrint = printthis()
}
}