Count Annotations on MapView in Swift - ios

After completing a loop that places annotations on a map from an array, I want to count the number of annotations.
My code as follows:
let anCount = self.mapView.annotations?.count
if (anCount > 1) {
//do something
}
gives error:
Value of optional type 'Int?' must be unwrapped to a value of type
'Int'
The fixit suggestions yield other errors. What is the correct way to count the number of annotations for the map.
Thanks for any suggestions.

You have to unwrap the optional, e.g. with if let, which you can then combine with the > 1 test in a single if statement:
if let anCount = mapView.annotations?.count, anCount > 1 {
//do something
}
But annotations isn't an optional (at least in current iOS versions), so you'd probably just do:
let anCount = mapView.annotations.count
if anCount > 1 {
//do something
}

Related

Iterating over a for loop X amount of times from textfield input

I am trying to query my textfield.text input (Let's say the user types 5 in the keypad).
Then convert the string to an integer.
Then make a for loop and run the for loop X amount of times. (X being the integer converted from the string).
I have tried the below however I can't work out the syntax/format for the for loop.
var shotCountInt = Int(numberOfShots.text!)
for item in 0..<shotCountInt {
//do something
}
The error I am getting is on the for loop which is:
Type 'Int?' does not conform to protocol 'Sequence'
I think the problem is in 0..<shotCountInt of optional Int , so
if let shotCountInt = Int(numberOfShots.text!) {
for item in 0..<shotCountInt {
// proceed here
}
}

Cannot assign value of type 'String?' to type 'Int'

I am getting the error message Cannot assign value of type 'String?' to type 'Int'
I have browsed through other questions like this but it still shows the error.
if sunscreenName.text != nil && reapplyTime.text != nil {
sunscreen = sunscreenName.text!
reApplyTime = reapplyTime.text
//Some sort of message such as Progress hud
}
Thanks in advance!
I got your problem, actually what happens here Swift is is type safe langauge
So what you are doing is is to store a String value in Int which will not happen automatically you need to convert it to Int
like this
Int(sunscreenName.text)
But there is a catch there not all string are convertible to Int type, fo e.g.
let name = "roshan"
if you try to convert it to Int it will give you a nil
let a = Int(name)
So its better you do a optional Binding here provided by Swift
if let sunValue = Int(sunscreenName.text),let reApplyValue = Int(reapplyTime.text) {
sunscreen = sunValue
reApplyTime = reApplyValue
}
I recommend reading through The Swift Programming Language to get a better understanding of Swift and its fundamental concepts, since this question is fairly basic.
You make several mistakes:
if sunscreenName.text != nil && reapplyTime.text != nil {
This is wrong. In Swift, if you plan to use the value later, you should use if let rather than comparing to nil. Comparing to nil leaves the values optional, but if let unwraps them. So, do this instead:
if let sunscreenText = sunscreenName.text, let reapplyText = reapplyTime.text {
Now you have the sunscreenText and reapplyText variables, which are typed String, not String? (i.e. they are not optional).
Now, there's these two lines.
sunscreen = sunscreenName.text!
reApplyTime = reapplyTime.text
You don't say which one is giving the error, but the issue is the same in either case. First, use our unwrapped sunscreenText and reapplyText variables instead of sunscreenName.text! and reapplyTime.text. Next, if one of these is meant to be an Int instead of a String, cast it. Swift is not like JavaScript, in that it won't automatically convert values from one type to another, so if something is a string and we need an integer, we have to convert it ourselves.
(assuming reapplyTime was the line that was giving the error:)
if let reapplyInt = Int(reapplyText) {
reapplyTime = reapplyInt
}
The reason we have to unwrap is because Int(String) can return nil if the string is something that can't be converted to an integer. Alternately, we could just provide a default value:
reapplyTime = Int(reapplyText) ?? 0 // sets to 0 if it can't parse the string as an integer

Swift - optional dates comparison

I'm trying to implement code in swift which will give me the closest date from current date.
The thing is I want users to choose in maximum 3 dates, and every time he chooses the date is added to the array named "reminders"
Then I check how many items (max 3) are in this array (named: reminders), and store the particular date/ dates from the array using CoreData:
if addObjectView.reminders.count == 1 {
newobject.firstReminder = addObjectView.reminders[0]
}
if addObjecteView.reminders.count == 2 {
newobject.firstReminder = addObjectView.reminders[0]
newobject.secondReminder = addObjectView.reminders[1]
}
if addObjectView.reminders.count == 3 {
newobject.firstReminder = addObjectView.reminders[0]
newobject.secondReminder = addObjectView.reminders[1]
newobject.thirdReminder = addObjectView.reminders[2]
}
Then I want to implement code to check first if the first/second/thirdReminder from CoreData is nil, and if it's not then compare it to current date. If it is 'larger' then set String from this date as label. But I want also to compare date from first/second/thirdReminder between themselves or somehow make sure that the firstReminder will always be earlier than second and so on.
I don't know if it is that hard, but I'm trying to figure it out and I'm stuck.
You should use the nil coalescing operator for this purpose.
The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.
Source - developer.apple.com
You could get the reminder's date, stored in myOptionalDate, and check if it is nil. If it is, then we will do
0 > NSDate().timeIntervalSince1970
which will always be false. If it isn't nil, we can do the equivalent of
myOptionalDate!.timeIntervalSince1970 > NSDate().timeIntervalSince1970
which will tell you if you if the label should be added
if((myOptionalDate?.timeIntervalSince1970 ?? 0) > NSDate().timeIntervalSince1970){
//add the label
}
Which is shorthand for
var myInterval = 0
if(myOptionalDate != nil){
myInterval = myOptionalDate!.timeIntervalSince1970
}
if(myInterval > NSDate().timeIntervalSince1970)
Also, although this doesn't have to do with the question, depending on how your code is formatted, you shouldn't have to use if statements to check how many reminders there are
By default, newobject.firstReminder, newobject.secondReminder, and newobject.thirdReminder will (I'm assuming) be nil. So, you could just change all of your example code to
let originalReminders = addObjectView.reminders
newobject.firstReminder = originalReminders.count > 0 ? originalReminders[0] : nil
newobject.secondReminder = originalReminders.count > 1 ? originalReminders[1] : nil
newobject.thirdReminder = originalReminders.count > 2 ? originalReminders[2] : nil
if the default value isn't nil, you could simply replace nil in the above code with your default value

How to use optional binding in Swift 2

I'm new to learning Swift so I decided I might as well learn Swift 2 instead. Everything has made sense to me so far except for the following code snippet. Hopefully someone can shed some light on this for me.
//: Playground - noun: a place where people can play
import UIKit
//Works
let possibleNumber="2"
if let actualNumber = Int(possibleNumber) {
print("\'\(possibleNumber)\' has an integer value of \(actualNumber)")
}
else {
print("could not be converted to integer")
}
//Doesn't Work and I'm not sure why
let testTextField = UITextField()
testTextField.text = "2"
let numberString = testTextField.text //I know this is redundant
if let num = Int(numberString) {
print("The number is: \(num)")
}
else {
print("Could not be converted to integer")
}
The top section of the code is straight from Apple's Swift 2 ebook and it makes sense to me how it uses optional binding to convert the string to an int. The second piece of code is basically the same except that the string comes from the text property of a UITextField. The bottom part of the code gives the following error:
Playground execution failed: /var/folders/nl/5dr8btl543j51jkqypj4252mpcnq11/T/./lldb/843/playground21.swift:18:18: error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
if let num = Int(numberString) {
I fixed the problem by using this line:
if let num = Int(numberString!) {
I just want to know why the second example needs the ! and the first doesn't. I'm sure the problem has to do with the fact that I'm getting the string from a textfield. Thanks!
The difference is that in the first case possibleNumber is not an optional variable. It is definitely a string. It cannot be nil.
In the second case textField.text returns an optional string and so numberString is an optional variable. It could be nil.
Now... The conversion Int("") returns an optional int. if the string is "abc" then it cannot return a number so returns nil. This is what you are unwrapping with the if let... statement.
However, in the second case your string is also optional and the Int() will not accept an optional. So you are force unwrapping it. This is dangerous as it could crash the app if the string is nil.
What you could do instead is this...
if let numberString = textFeidl.text,
number = Int(numberString) {
// use the number
}
This will unwrap the text first and if it's available then use it to. Get the number. If that is not nil then you enter the block.
In Swift 2 you could use the guard let function here also.
Just seen that you are using Swift 2.
You can do it this way also...
func getNumber() -> Int {
guard let numberString = textField.text,
number = Int(numberString)
else {
return 0
}
return number
}

Swift: Testing optionals for nil

I'm using Xcode 6 Beta 4. I have this weird situation where I cannot figure out how to appropriately test for optionals.
If I have an optional xyz, is the correct way to test:
if (xyz) // Do something
or
if (xyz != nil) // Do something
The documents say to do it the first way, but I've found that sometimes, the second way is required, and doesn't generate a compiler error, but other times, the second way generates a compiler error.
My specific example is using the GData XML parser bridged to swift:
let xml = GDataXMLDocument(
XMLString: responseBody,
options: 0,
error: &xmlError);
if (xmlError != nil)
Here, if I just did:
if xmlError
it would always return true. However, if I do:
if (xmlError != nil)
then it works (as how it works in Objective-C).
Is there something with the GData XML and the way it treats optionals that I am missing?
In Xcode Beta 5, they no longer let you do:
var xyz : NSString?
if xyz {
// Do something using `xyz`.
}
This produces an error:
does not conform to protocol 'BooleanType.Protocol'
You have to use one of these forms:
if xyz != nil {
// Do something using `xyz`.
}
if let xy = xyz {
// Do something using `xy`.
}
To add to the other answers, instead of assigning to a differently named variable inside of an if condition:
var a: Int? = 5
if let b = a {
// do something
}
you can reuse the same variable name like this:
var a: Int? = 5
if let a = a {
// do something
}
This might help you avoid running out of creative variable names...
This takes advantage of variable shadowing that is supported in Swift.
Swift 3.0, 4.0
There are mainly two ways of checking optional for nil. Here are examples with comparison between them
1. if let
if let is the most basic way to check optional for nil. Other conditions can be appended to this nil check, separated by comma. The variable must not be nil to move for the next condition. If only nil check is required, remove extra conditions in the following code.
Other than that, if x is not nil, the if closure will be executed and x_val will be available inside. Otherwise the else closure is triggered.
if let x_val = x, x_val > 5 {
//x_val available on this scope
} else {
}
2. guard let
guard let can do similar things. It's main purpose is to make it logically more reasonable. It's like saying Make sure the variable is not nil, otherwise stop the function. guard let can also do extra condition checking as if let.
The differences are that the unwrapped value will be available on same scope as guard let, as shown in the comment below. This also leads to the point that in else closure, the program has to exit the current scope, by return, break, etc.
guard let x_val = x, x_val > 5 else {
return
}
//x_val available on this scope
One of the most direct ways to use optionals is the following:
Assuming xyz is of optional type, like Int? for example.
if let possXYZ = xyz {
// do something with possXYZ (the unwrapped value of xyz)
} else {
// do something now that we know xyz is .None
}
This way you can both test if xyz contains a value and if so, immediately work with that value.
With regards to your compiler error, the type UInt8 is not optional (note no '?') and therefore cannot be converted to nil. Make sure the variable you're working with is an optional before you treat it like one.
From swift programming guide
If Statements and Forced Unwrapping
You can use an if statement to find out whether an optional contains a
value. If an optional does have a value, it evaluates to true; if it
has no value at all, it evaluates to false.
So the best way to do this is
// swift > 3
if xyz != nil {}
and if you are using the xyz in if statement.Than you can unwrap xyz in if statement in constant variable .So you do not need to unwrap every place in if statement where xyz is used.
if let yourConstant = xyz {
//use youtConstant you do not need to unwrap `xyz`
}
This convention is suggested by apple and it will be followed by devlopers.
Although you must still either explicitly compare an optional with nil or use optional binding to additionally extract its value (i.e. optionals are not implicitly converted into Boolean values), it's worth noting that Swift 2 has added the guard statement to help avoid the pyramid of doom when working with multiple optional values.
In other words, your options now include explicitly checking for nil:
if xyz != nil {
// Do something with xyz
}
Optional binding:
if let xyz = xyz {
// Do something with xyz
// (Note that we can reuse the same variable name)
}
And guard statements:
guard let xyz = xyz else {
// Handle failure and then exit this code block
// e.g. by calling return, break, continue, or throw
return
}
// Do something with xyz, which is now guaranteed to be non-nil
Note how ordinary optional binding can lead to greater indentation when there is more than one optional value:
if let abc = abc {
if let xyz = xyz {
// Do something with abc and xyz
}
}
You can avoid this nesting with guard statements:
guard let abc = abc else {
// Handle failure and then exit this code block
return
}
guard let xyz = xyz else {
// Handle failure and then exit this code block
return
}
// Do something with abc and xyz
Swift 5 Protocol Extension
Here is an approach using protocol extension so that you can easily inline an optional nil check:
import Foundation
public extension Optional {
var isNil: Bool {
guard case Optional.none = self else {
return false
}
return true
}
var isSome: Bool {
return !self.isNil
}
}
Usage
var myValue: String?
if myValue.isNil {
// do something
}
if myValue.isSome {
// do something
}
One option that hasn't specifically been covered is using Swift's ignored value syntax:
if let _ = xyz {
// something that should only happen if xyz is not nil
}
I like this since checking for nil feels out of place in a modern language like Swift. I think the reason it feels out of place is that nil is basically a sentinel value. We've done away with sentinels pretty much everywhere else in modern programming so nil feels like it should go too.
Instead of if, ternary operator might come handy when you want to get a value based on whether something is nil:
func f(x: String?) -> String {
return x == nil ? "empty" : "non-empty"
}
Another approach besides using if or guard statements to do the optional binding is to extend Optional with:
extension Optional {
func ifValue(_ valueHandler: (Wrapped) -> Void) {
switch self {
case .some(let wrapped): valueHandler(wrapped)
default: break
}
}
}
ifValue receives a closure and calls it with the value as an argument when the optional is not nil. It is used this way:
var helloString: String? = "Hello, World!"
helloString.ifValue {
print($0) // prints "Hello, World!"
}
helloString = nil
helloString.ifValue {
print($0) // This code never runs
}
You should probably use an if or guard however as those are the most conventional (thus familiar) approaches used by Swift programmers.
Optional
Also you can use Nil-Coalescing Operator
The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.
let value = optionalValue ?? defaultValue
If optionalValue is nil, it automatically assigns value to defaultValue
Now you can do in swift the following thing which allows you to regain a little bit of the objective-c if nil else
if textfieldDate.text?.isEmpty ?? true {
}
var xyz : NSDictionary?
// case 1:
xyz = ["1":"one"]
// case 2: (empty dictionary)
xyz = NSDictionary()
// case 3: do nothing
if xyz { NSLog("xyz is not nil.") }
else { NSLog("xyz is nil.") }
This test worked as expected in all cases.
BTW, you do not need the brackets ().
If you have conditional and would like to unwrap and compare, how about taking advantage of the short-circuit evaluation of compound boolean expression as in
if xyz != nil && xyz! == "some non-nil value" {
}
Granted, this is not as readable as some of the other suggested posts, but gets the job done and somewhat succinct than the other suggested solutions.
If someone is also try to find to work with dictionaries and try to work with Optional(nil).
let example : [Int:Double?] = [2: 0.5]
let test = example[0]
You will end up with the type Double??.
To continue on your code, just use coalescing to get around it.
let example : [Int:Double?] = [2: 0.5]
let test = example[0] ?? nil
Now you just have Double?
This is totally logical, but I searched the wrong thing, maybe it helps someone else.
Since Swift 5.7:
if let xyz {
// Do something using `xyz` (`xyz` is not optional here)
} else {
// `xyz` was nil
}

Resources