Is it possible to use optionals for members in structures or classes in Swift? - swift

I'm having a difficulty reconciling my admittedly incomplete understanding of optionals and this from the Swift 2.1 documentation:
Classes and structures must set all of their stored properties to an
appropriate initial value by the time an instance of that class or
structure is created. Stored properties cannot be left in an
indeterminate state.
I'd like to be able to do something like:
struct Name {
var firstName = "Flintstone First"
var middleName: String?
var lastName = "Flintstone"
}
var wilmaHusband: Name
wilmaHusband.firstName = "Fred"
where middleName may be nil. However, quite understandably according to that part of the Swift documentation, I encounter the error Struct wilmaHusband must be completely initialized before a member is stored...
Is what I'm trying to do--make a member potentially nil in a structure (or class) impossible in Swift? If so, it seems one seeming advantage of optionals--that they may hold the kind of data that may or may not be present in a structured object (such as a middle name in a name construct)--is lost.
I feel like I'm missing something fundamental here in my understanding of optionals, and I apologize in advance for my naïveté.

Since all members of the struct have an initial value
(including var middleName: String? which – as an optional – is
implicitly initialized to nil), you can create a variable of that
type simply with
var wilmaHusband = Name()

Related

Why does this Swift struct require "mutating"? [duplicate]

This question already has answers here:
Mutating function inside class
(4 answers)
Closed 3 years ago.
I am missing something about the mutability concept in Swift. I normally use objects, not structs, to get observability, so the value semantics are still new to me.
struct Game {
var map: [[Int]]
So here I have declared map as mutable. So why in a method like this...
mutating func createPlayer() {
// emptyLocation -> (Int, Int)
let (X,Y) = emptyLocation()
map[X][Y] = .player
}
...do I have to use the mutating? Yes, the function is mutating, but the original struct is declared as such. It seems that practically every func will be mutatingin practice, which seems to defeat the purpose of the markup.
Is there some other way I should be doing this? Is the common use of mutating indicating a performance/memory issue I should be avoiding?
Update: I was rather upset at the way the internal state of the struct "leaked out" to the surrounding code; if you declare a member var inside the struct then it has to be outside as well, even if you never changed. This violates every concept of encapsulation I can think of. So I changed struct to class, removed all the mutating, and was done with it. I get the idea, but I'm not sure I fully understand the implementation. It seems, to this Swift-noob, that the mutating is something the compiler can determine without me telling it - is the member declared var?, does the func actually mutate it? etc.
Yes it is the default behaviour for a struct or enum that instance methods can not modify a property since they are value type. So you need to use mutating to override this behaviour.
The way you define your property, var or let, is still relevant for if you can change it from a mutable instance method or directly or not.
Since your property is not private you can still do
var g = Game(map: [[1]])
g.map.append([2])
In Swift structs have value semantics, ie they behave as if they are values even though some of them like String and Array are implemented as references for performance reasons. When you mutate such a struct the compiler may actually have to make a copy if you are not the only owner of the struct; this is known as copy on write and it is the possible performance issue that mutating indicates.

Advantage of Key-Value Coding in Swift 4

I just want to know the benefits of Key-Value Coding in Swift 4. As I am well aware of key-value coding (hold reference to properties without actually accessing the underlying data held by the property).
For Example:
struct Student {
var name: String?
var rollNo: String?
}
let student = Student(name: "aman", rollNo: "12121")
let nameKey = \Student.name
let name = student[keyPath: nameKey]
Here we created the the instance of Student and access the value by subscript (keyPath) but I can easily access the value by simply writing the code student.name.
In Objective-C, we use string as a key like given below and we could take some benefits from it
[object valueForKey:#"name"]
My question is that is there any benefits related to coding level or memory level?
Two key advantages are:
Keys are validated: Xcode will warn you, at compile time, if you try to use a key that is not valid.
Results are strongly typed: With the following, the compiler will know that the resulting name is a String:
let name = student[keyPath: nameKey]
This eliminates the need to do any casting.
The result is that it's much easier to write safe code.

Swift. When should you define an Object / Value with specific data type

As I started developing with Swift and searching through different tutorials and documentations about the language, I'm not sure about one thing.
You can declare an object / value with a specific data type like this:
var aString:String = "Test"
var anObject:SKScene = ASceneClass()
Or you can just do it like this:
var aString = "Test"
var anObject = ASceneClass()
The result will be exactly the same (ASceneClass inherits from SKScene of course)
As everyone is doing it different I wonder if there's a logical reason behind it or you do it for readability ?
Declaring type right after variable name is called Type Annotation
When you don't do that, you have to provide initial value
var aString = "Test"
Often value is not known at that moment, or you are not even sure if it's going to be not nil value, then you can declare it as optional
var aString:String?
If you would like to declare variable without any initiaization but you are sure it's not going to evaluate to nil, you force unwrap it
var aString:String!
This is the definition. In practice, it's always better to use type annotations even when you initialize variable with value, because later in your program you will notice anytime you mess something with the type of the variable.
Also, When you declare an array or dictionary, usually nested ones, Xcode might expect them to have type annotations since it might have some issues with writing values when the type is not known in advance.
To recap
You will want to use type annotations whenever you can, which means whenever you are sure about the variable's type in advance
Recommended/Documented way to declare a variable in swift is as follow:
var <variable name>: <type> = <initial value/expression>
Note: Given form declares a stored variable or stored variable property. Its used when you are clear about type annotation of it.
Though its valid to declare variable without its Type.
var variableName = <initial value>
Note: When you don't know type annotation its mandatory to assign 'Initial value' to that variable.
Refer Swift Documentation on Declaration for more details.

Prefer optional or non-optional when designing domain?

While defining model for my application what properties should I declare as optional and what as non-optional? What aspects I need to consider?
E.g I want to create entity Car. What type engine should be?
struct Car {
let engine: Engine?
}
or
struct Car {
let engine: Engine
init(engine: Engine) {
self.engine = engine
}
}
or
struct Car {
let engine: Engine = Engine()
}
Introduction
Many of us (me included) were not familiar with this problem.
Infact Objective-C (and many other languages like C, Java 1...7, etc...) forced a variable with a primitive type (Int, Double, ...) to always be populated.
And they also always forced a reference/pointer variable to always be potentially nil.
Se over the years we just adapted to these constraints.
Initially many Swift developers used implicitly unwrapped optionals
var something: Something!
This is the closest thing to declaring a reference variable in a way that behave similarly to the programming languages mentioned above but this way we don't really use the power of Optionals.
When should I declare a property of my model as optional?
The question you have to ask yourself is
In my data domain, can this entity exist and have no value for this specific property?
If the answer is no, then the property should be declared as non optional.
Example
A User struct representing the user of an app will always have a username and password populated.
struct User {
let username: String
let password: String
let profileImageURL: NSURL?
}
On the other hand it could have a nil value for profileImageURL maybe because the user didn't upload a profile picture.
In this case a User value without a username just doesn't make sense, it can't happen and when dealing with a User value we should always have the guarantee (provided by the compiler) that there is username value in it.
So we make username non optional
It really depends on the domain
The "optionality" of the property of an Entity can differ from data domain to data domain.
E.g. this entity for a mailing list system
struct Person {
let name: String?
let email: String
}
makes sense because we could not know the name but we know for sure its email address.
On the other hand the same entity in another context like an Address Book could become
struct Person {
let name: String?
let email: String?
}
because maybe we created/saved an empty card.
Thumb of rule
As personal advice I suggest you to avoid optional values when you have doubts about it. If you declared a non optional property something that should actually be optional the problem will come up very soon.
On the other hand if you declared optional something that should be non optional you could never find out.
Important
And of course NEVER use a value of the domain of the property/variable to represent the absence of value
let birthyear = -1 // 😨
let name = "" // 😰
let username = "NOT_PROVIDED" // 😱

Swift: confused about nullable/optional types

I'm new to Swift and iOS coding and have been working on writing my first app. While my programming background is pretty significant, I come from a Python and C# background where pretty much anything can be None or null and it's up to the user to check at runtime for a null. I'm finding this whole concept of "nullable vs. non-nullable types" or "optional types" in Swift to be confusing.
I understand that the core concept is that a variable declared as a type like myObject cannot be set to nil. However, if I define it as type myObject? then the value can be set to nil.
The problem is that, when I look at my code designs, it feels like everything will have to be "nullable" in my code. It feels like this either means I'm not thinking correctly with how my code should run, or that I'm missing some crucial piece of understanding.
Let's take the simplest example of something I am confused about. Suppose I have two classes - one that stores and manages some sort of data, and another that provides access to that data. (An example of this might be something like a database connection, or a file handle, or something similar.) Let's call the class containing data myData and the class that works with that data myObject.
myObject will need a class-level reference to myData because many of its methods depend on a local reference to the class. So, the first thing the constructor does is to generate a data connection and then store it in the local variable dataConnection. The variable needs to be defined at the class level so other methods can access it, but it will be assigned to in the constructor. Failure to obtain the connection will result in some sort of exception that will interfere with the very creation of the class.
I know that Swift has two ways to define a variable: var and let, with let being analogous to some languages' const directive. Since the data connection will persist throughout the entire life of the class, let seems an obvious choice. However, I do not know how to define a class-level variable via let which will be assigned at runtime. Therefore, I use something like
var dataConnection: myData?
in the class outside any functions.
But now I have to deal with the nullable data type, and do explicit unwrapping every time I use it anywhere. It is frustrating to say the least and quite confusing.
func dealWithData() {
self.dataConnection.someFunctionToGetData() <- results in an unwrapping error.
self.dataConnection!.someFunctionToGetData() <- works.
let someOtherObjectUsingData: otherObject = self.getOtherObject() <- may result in error unless type includes ?
someOtherObjectUsingData.someMethod(self.dataConnection) <- unwrap error if type included ?
var myData = self.dataConnection!
someOtherObjectUsingData.someMethod(myData) <- works
}
func somethingNeedingDataObject(dataObject: myData?) {
// now have to explicitly unwrap
let myDataUnwrapped = myData!
...
}
This just seems to be an extremely verbose way to deal with the issue. If an object is nil, won't the explicit unwrap in and of itself cause a runtime error (which could be caught and handled)? This tends to be a nightmare when stringing things together. I've had to do something like:
self.dataConnection!.somethingReturningAnObject!.thatObjectsVariable!.someMethod()
var myData? = self.dataConnection
var anotherObject? = myData!.somethingReturningAnObject
...
The way I'm used to doing this is that you simply define a variable, and if it is set to null and you try to do something with it, an exception (that you can catch and handle) is thrown. Is this simply not the way things work anymore in Swift? This has confused me sufficiently that just about every time I try to compile an app, I get tons of errors about this (and I just let Xcode fix them). But this can't be the best way to deal with it.
Do I have to consistently deal with wrapping and unwrapping variables - even those which are expected to never be null in the first place but simply can't be assigned at compile time?
However, I do not know how to define a class-level variable via let which will be assigned at runtime.
This part is easy. Just use let instead of var. With Swift 1.2 and later, you can delay the actual assignment of a let. The compiler is smart enough to do flow analysis and make sure it's assigned once, and only once, in all paths. So in the case of a class-wide let, the assignment can also happen in the constructor.
But now I have to deal with the nullable data type, and do explicit unwrapping every time I use it anywhere.
But this is what implicitly unwrapped Optionals are for. For example, StoryBoard defines all #IBOutlets as implicitly unwrapped, because the semantics are very clear: upon entrance to viewDidLoad() and everywhere after, unwrapping is safe. If you can prove clear semantics to yourself, you can do the same.
So you have roughly 4 choices:
A) declare at class level as implicitly unwrapped:
let dataConnection: MyData!
And be forced to initialize it in the constructor:
init() {
let whateverObj = someInitialCalculation()
dataConnection = whateverObj.someWayOfGettingTheConnection()
}
And from then on you don't need the '!'; it should be clear that implicit unwrap is always safe.
B) Initialize it right in its declaration if its initialization is reliable and sensible at that point, allowing you to forgo the entire concept of Optionals:
let dataConnection = SomeClass.someStaticMethod()
C) Declare at class level as a var, as implicit optional:
var dataConnection: MyData!
You won't have to init it in the constructor; let it be nil until its value can/should be computed. You still need some flow analysis to prove after a certain point, as in the case of #IBOutlets, accessing it will always be valid
D) The most 'unpredictable' case. Declare it as an explicit optional, because throughout the lifecycle of the class, the data connection will come and go:
var dataConnection: MyData?
func someMethodThatHandlesData() {
if let dC = dataConnection {
dc.handleSomeData()
}
else {
alert("Sorry, no data connection at the moment. Try again later.")
}
}
I think you're imagining that Swift always forces you down path D).
As far as your spaghetti-string code, you want to look into Optional Chaining, and only need to check the end result for nil.