Is there an operator in Swift that stops the evaluation of a multi expression conditional statement, as soon as the answer is clear?
What you described is called short circuiting and Swift does have it. For example:
let a : Int? = nil
if a != nil && a! == 1 {
print("a is 1")
} else {
print("a is nil")
}
You can see a
is never unwrapped. I think in your case, it's more likely that SpriteOwner()
returns nil. the Swifty way to unwrap optional values is to use the let ... where ...
syntax:
if let s = selectedSprite where s.SpriteOwner().type == "Human" {
println("a human selected")
}
How are consecutive if statements evaluated?
for customObject in array {
if customObject.isSimpleBool && customObject.isCostlyBool {
// do some stuff
}
}
This will work, I have used these kinds of statements with nil checks many times.
if (obj != nil && obj!.property == false) {}
and in cases of obj
being nil, obj.property
is never called(otherwise the application would crash)
Debugger displaying some instead of memory address
You've declared that method to return an optional MyObject
. In Swift, optionals are implemented as an enum that has two possible values: .None
, which is usually seen in its literal form, nil
, and .Some
, which holds the value of the optional as an associated value. You're seeing Some
in the debugger because your method successfully returns a value wrapped in an optional.
You can read more about Optionals in the Swift language guide.
Multiple conditions in ternary conditional operator?
For the first question, you can indeed use the ternary operator, but a simpler solution would be to use a String[]
with the month descriptions, and then subscript this array:
String[] months = { "jan", "feb", "mar", ... };
int month = 1; // jan
String monthDescription = months[month - 1]; // arrays are 0-indexed
Now, for your second question, the ternary operator seems more appropriate since you have fewer conditions, although an if
would be much easier to read, imho:
String year = "senior";
if (credits < 30) {
year = "freshman";
} else if (credits <= 59) {
year = "sophomore";
} else if (credits <= 89) {
year = "junior";
}
Contrast this with the ternary operator:
String year = credits < 30 ? "freshman" : credits <= 59 ? "sophomore" : credits <= 89 ? "junior" : "senior";
Reducing the number of brackets in Swift
You can do that :
let x = 10, y = 20;
let max = (x < y) ? y : x ; // So max = 20
And so much interesting things :
let max = (x < y) ? "y is greater than x" : "x is greater than y" // max = "y is greater than x"
let max = (x < y) ? true : false // max = true
let max = (x > y) ? func() : anotherFunc() // max = anotherFunc()
(x < y) ? func() : anotherFunc() // code is running func()
This following stack : http://codereview.stackexchange.com can be better for your question ;)
Edit : ternary operators and compilation
By doing nothing more than replacing the ternary operator with an if else statement, the build time was reduced by 92.9%.
https://medium.com/@RobertGummesson/regarding-swift-build-time-optimizations-fc92cdd91e31#.42uncapwc
Order of execution for an if with multiple conditionals
This type of evaluation is called short-circuiting.
Once the result is 100% clear, it does not continue evaluating.
This is actually a common programming technique.
For example, in C++ you will often see something like:
if (pX!=null && pX->predicate()) { bla bla bla }
If you changed the order of the conditions, you could be invoking a method on a null pointer and crashing. A similar example in C would use the field of a struct when you have a pointer to that struct.
You could do something similar with or:
if(px==null || pX->isEmpty()} { bla bla bla }
This is also one of the reasons that it is generally a good idea to avoid side effects in an if condition.
For example suppose you have:
if(x==4 && (++y>7) && z==9)
If x
is 4
, then y
will be incremented regardless of the value of z
or y
, but if x
is not 4
, it will not be incremented at all.
Replacing nested if statements
Well, not directly an answer to your question since you specifically ask about switch/case statements, but here is a similar question.
Invert “if” statement to reduce nesting
This talks about replacing nested if's with guard-statements, that return early, instead of progressively checking more and more things before settling on a return value.
Dependency Injection - I don't get it!
Dependency injection lets you decouple specific implementations of objects from their interfaces. It is difficult to justify in most of the small examples out there, but for larger systems it can be a life-saver. It can also help you to isolate your objects in unit tests.
For example, if you wanted to write tests for your CustomerService class, you could easily inject a MockRepository instead of CustomerRepository. This would let you test CustomerService without also testing CustomerRepository.
Outside of unit testing, I think the easiest example to visualize might be if you were writing a data access module for your application. You might want to support SQL Server and MySQL. You would then create Interfaces for your data access objects and create specific implementations of them for both database systems. Those implementations could be injected at runtime, thusly:
Function Setup(ByVal dbType As String) As IKernel
Dim dbModule As NinjectModule
If dbType = "SQL Server" Then
dbModule = New SQLServerModule
Else If dbType = "MySQL" Then
dbModule = New MySQLModule
End If
Return New StandardKernel(dbModule)
End Function
This also enables you to add support for other databases in the future, isolating the implementation details from the rest of the application.
Related Topics
Get The Start Point and End Point of The UIpangesturerecognizer in Swift
Create an Array of Protocols with Constrained Associated Types
Access Id Does Not Work When Testing a Textfield with 'Issecuretextentry = True'
iOS 10 App Crashes When Accessing Camera
How to Get Textfields from Static Cells in UItableviewcontroller? Swift
Swift Codable: Decode Dictionary with Unknown Keys
Why Do I Have to Explicitly Unwrap My String in This Case
Swift - Boundingbox Cause Exc_Bad_Access (Code=1)
Uicolor Code in a Variable in Swift
Dictionary of a Protocol Swift 4
How to Convert Custom Object to Data Swift
Filter Array of Objects with Multiple Criteria and Types in Swift
Firebase Connection State Always Returning False on First Run
What Is The Default Value of The Padding Modifier in Swift
How to Create a Circle with Calayer
How to Know If a Swiftui Button Is Enabled/Disabled
How to Change Orientation for Avcapturemoviefileoutput in Swift