Check Non Optional value for nil - swift

I'm creating a function in swift to check the if non optional value return nil. My aim is just to handle that exception and avoid app crash for unexpected nil values.
I have two variables in my class:
// My Class variables
var compulsoryValue: Any!
I dont want to check optionalValue as nil. The compiler is returning Optional.none or Optional.some enums instead of nil or some value.
My problem:
I'm facing the problem that I am not able to check if this value is empty or not. As for empty the compiler returning none while for a value it is return some as defined in Swift Optional Enum.
Implicitly Unwrapped Optional is just throwing an error while it has a nil value.
How I can check that the value nil which was supposed as a non-optional value?
Update# 1:
My code:
class myClass {
var compulsoryValue: Any!
init() {
if type(of: compulsoryValue) != Optional<Any>.self {
// Here I want to check if compulsoryValue is nil so I want to throw an exception
print("this is not optional: ", compulsoryValue)
}
}
}
_ = myClass()

class myClass {
var compulsoryValue: Any!
var optionalValue: Any?
init() {
let variabless = [compulsoryValue, optionalValue]
for (_, v) in variabless.enumerated() {
if(v != nil) { //Or v == nil
// Here I want to check if v is nil so I want to throw an exception
print("this is not optional: ", v)
}
}
}
}
_ = myClass()

Related

How can I define insert function for Set when Set is optional in Swift?

My goal is to be able insert new item to an optional set which this set has nil value before. For that reason i created this extension, but it does not work, and still I cannot insert a new item to a nil set.
extension Optional where Wrapped == Set<String> {
func myInsert(_ value: String) -> Self {
if let unwrappedSet: Set<String> = self {
var newSet: Set<String> = unwrappedSet
newSet.insert(value)
return newSet
}
else {
let set: Set<String>? = [value]
return set
}
}
}
use case:
func myTest() -> Set<String>? {
var set: Set<String>? = nil
set.myInsert("Hello")
return set
}
if let set: Set<String> = myTest() {
print(set)
}
I refuse to believe there is issue with my extension, and i think the issue is from xcode itself, look the function below it is same function but outside of extension, it does works!
func myInsert(set: Set<String>?, value: String) -> Set<String>? {
if let unwrappedSet: Set<String> = set {
var newSet: Set<String> = unwrappedSet
newSet.insert(value)
return newSet
}
else {
let set: Set<String>? = [value]
return set
}
}
use case:
let set: Set<String>? = nil
let newSet = myInsert(set: set, value: "Hello")
let newSet2 = myInsert(set: newSet, value: "World")
print(newSet2)
result:
Optional(Set(["Hello", "World"]))
From your test case code:
var set: Set<String>? = nil
set.myInsert("Hello")
you expect the variable set to change from nil to a wrapped Set<String> containing the String "Hello". In order for the value to modify itself, the func must be mutating.
Make myInsert a mutating func and assign the new set to self. Since myInsert is mutating, it doesn't need to return a value which your test is ignoring anyway:
extension Optional where Wrapped == Set<String> {
mutating func myInsert(_ value: String) {
if self == nil {
self = [value]
} else {
self?.insert(value)
}
}
}
Test
func myTest() -> Set<String>? {
var set: Set<String>? = nil
set.myInsert("Hello")
set.myInsert("Goodbye")
return set
}
if let set = myTest() {
print(set)
}
["Hello", "Goodbye"]
Making insert more usable
(Thanks to #LeoDabus for his suggestions)
We can make this work with a Set of any type and make it more like the original insert on Set by having it return a #discardableResult containing a tuple with a Bool indicating if a the value was inserted and the memberAfterInsert:
extension Optional where Wrapped: SetAlgebra {
#discardableResult
mutating func insert(_ newMember: Wrapped.Element) -> (inserted: Bool, memberAfterInsert: Wrapped.Element) {
if self == nil {
self = .init()
}
return self!.insert(newMember)
}
}
vacawama and Leo's answer is correct but you want to understand why your code doesn't work. I'll try to explain why does not work as you expected. The function you created "myInsert" defines a Set object, inserts the parameter value and returns the newly created Set object. The problem is you are not actually assigning the created Set object to actual Set variable (which is "self") that you are working on.
if let unwrappedSet: Set<String> = self {
var newSet: Set<String> = unwrappedSet // assigning nil valued "self" to a variable doesn't assign the original variable. Assigning nil to another variable makes that variable again nil. Both are equal (they are nil) but not same variables.
newSet.insert(value) // inserts value to second Set object not to "self". So still, your actual Set doesn't contains the given value.
return newSet // returns the value inserted Set object, not "self".
}
else {
let set: Set<String>? = [value]
return set
}
If we look at myTest() function you can see that your adding operation doesn't work on actual variable.
var set: Set<String>? = nil
set.myInsert("Hello") // at this point, myInsert function returns a new Set object with inserted given value. But this operation does not effect the original variable above. That means set variable is still nil
return set // returns nil variable.
I hope this helps.

How to check if nested optional is nil in generic class?

I have simple class:
class Values<T> {
let new: T
let old: T?
init(new: T, old: T? = nil) {
self.new = new
self.old = old
}
func changed<TProp: AnyObject>(_ getter: (T) -> TProp) -> Bool {
return old == nil || !(getter(old!) === getter(new))
}
func changed<TProp: Equatable>(_ getter: (T) -> TProp) -> Bool {
return old == nil || !(getter(old!) == getter(new))
}
}
When using it as Values<ChartViewModelData?> where ChartViewModelData is a class i got problems when old is nested optional - it is both nil and not equal to nil:
So changing function like this doesn't help:
return old == nil || old! == nil || !(getter(old!) === getter(new))
nil shouldn't be passed to the getter function, and i don't know how to achieve it.
Reproduce:
class PropClass {}
class TestClass {
var someProp = PropClass()
}
let values = Values<TestClass?>(new: TestClass(), old: Optional<Optional<TestClass>>(nil))
values.changed({ $0!.someProp }) /* Fatal error: Unexpectedly found nil while unwrapping an Optional value */
values.changed({ $0?.someProp }) /* error: cannot convert value of type '(TestClass?) -> PropClass?' to expected argument type '(TestClass?) -> _' */
Second error appears because it can't use === on two Optional.
Just spent couple of hours looking for a solution to the similar problem and I think I have finally found one. To check if nested value is nil for generic type you can use this:
if (newValue as AnyObject) is NSNull {
//value is nil
}

Unable to return an optional as an optional

Why can't I get Swift to return a value as an optional.
I have a funtion that checks if an optional contains a value and return it as an optional if it isn't:
var someOptional: String?
func checkIfOptional<T>(value: T?) -> (String, T) {
if let _value = value {
return (("Your optional contains a value. It is: \(_value)"), (_value))
} else {
return (("Your optional did not contain a value"), (value?)) //ERROR: Value of optional type 'T?' not unwrapped; did you mean to use '!' or '?'?
}
}
When the optional is nil. Ist should return the same optional the was given to the function.
If there is a value. It should return the unwrapped value.
If you want to return an optional you have to declare the return type as optional
func checkIfOptional<T>(value: T?) -> (String, T?) {
if let _value = value {
return ("Your optional contains a value. It is: \(_value)", value)
} else {
return ("Your optional did not contain a value", value)
// or even return ("Your optional did not contain a value", nil)
}
I removed all unnecessary parentheses.
You may want to declare an enum like this:
enum Value<T> {
case full(String, T)
case empty(String, T?)
}
func checkIfOptional<T>(_ value: T?) -> Value<T> {
if let _value = value {
return .full("Your optional contains a value. It is: \(_value)", _value)
} else {
return .empty("Your optional did not contain a value.", value)
}
}
var toto: String?
print(checkIfOptional(toto)) // empty("Your optional did not contain a value", nil)
print(checkIfOptional("Blah")) // full("Your optional contains a value. It is: Blah", "Blah")
To treat a Value you should use switch this way:
var toto: String?
let empty = checkIfOptional(toto)
let full = checkIfOptional("Blah")
func treatValue<T>(_ value: Value<T>) {
switch(value) {
case .full(let msg, let val):
print(msg)
print(val)
case .empty(let msg, _):
print(msg)
}
}
treatValue(empty) // Your optional did not contain a value.
treatValue(full) // Your optional contains a value. It is: Blah\nBlah
But all of this seems to me to only add needless complexity to the straightforward type that is Optional. So you might want to expand on what you are trying to achieve here.

Simplest way to convert an optional String to an optional Int in Swift

It seems to me there ought to be a simple way to do an optional conversion from a String to an Int in Swift but I can't figure it out.
value is a String? and I need to return an Int?.
Basically I want to do this, but without the boilerplate:
return value != nil ? Int(value) : nil
I tried this, which seems to fit with Swift's conventions and would be nice and concise, but it doesn't recognize the syntax:
return Int?(value)
You can use the nil coalescing operator ?? to unwrap the String? and use a default value "" that you know will produce nil:
return Int(value ?? "")
Another approach: Int initializer that takes String?
From the comments:
It's very odd to me that the initializer would not accept an optional and would just return nil if any nil were passed in.
You can create your own initializer for Int that does just that:
extension Int {
init?(_ value: String?) {
guard let value = value else { return nil }
self.init(value)
}
}
and now you can just do:
var value: String?
return Int(value)
You can use the flatMap() method of Optional:
func foo(_ value: String?) -> Int? {
return value.flatMap { Int($0) }
}
If value == nil then flatMap returns nil. Otherwise it
evaluates Int($0) where $0 is the unwrapped value,
and returns the result (which can be nil if the conversion fails):
print(foo(nil) as Any) // nil
print(foo("123") as Any) // Optional(123)
print(foo("xyz") as Any) // nil
With String extension you shouldn't worry about string == nil
extension String {
func toInt() -> Int? {
return Int(self)
}
}
Usage:
var nilString: String?
print("".toInt()) // nil
print(nilString?.toInt()) // nil
print("123".toInt()) // Optional(123)

Check string for nil & empty

Is there a way to check strings for nil and "" in Swift? In Rails, I can use blank() to check.
I currently have this, but it seems overkill:
if stringA? != nil {
if !stringA!.isEmpty {
...blah blah
}
}
If you're dealing with optional Strings, this works:
(string ?? "").isEmpty
The ?? nil coalescing operator returns the left side if it's non-nil, otherwise it returns the right side.
You can also use it like this to return a default value:
(string ?? "").isEmpty ? "Default" : string!
You could perhaps use the if-let-where clause:
Swift 3:
if let string = string, !string.isEmpty {
/* string is not blank */
}
Swift 2:
if let string = string where !string.isEmpty {
/* string is not blank */
}
With Swift 5, you can implement an Optional extension for String type with a boolean property that returns if an optional string is empty or has no value:
extension Optional where Wrapped == String {
var isEmptyOrNil: Bool {
return self?.isEmpty ?? true
}
}
However, String implements isEmpty property by conforming to protocol Collection. Therefore we can replace the previous code's generic constraint (Wrapped == String) with a broader one (Wrapped: Collection) so that Array, Dictionary and Set also benefit our new isEmptyOrNil property:
extension Optional where Wrapped: Collection {
var isEmptyOrNil: Bool {
return self?.isEmpty ?? true
}
}
Usage with Strings:
let optionalString: String? = nil
print(optionalString.isEmptyOrNil) // prints: true
let optionalString: String? = ""
print(optionalString.isEmptyOrNil) // prints: true
let optionalString: String? = "Hello"
print(optionalString.isEmptyOrNil) // prints: false
Usage with Arrays:
let optionalArray: Array<Int>? = nil
print(optionalArray.isEmptyOrNil) // prints: true
let optionalArray: Array<Int>? = []
print(optionalArray.isEmptyOrNil) // prints: true
let optionalArray: Array<Int>? = [10, 22, 3]
print(optionalArray.isEmptyOrNil) // prints: false
Sources:
swiftbysundell.com - Extending optionals in Swift
objc.io - Swift Tip: Non-Empty Collections
Using the guard statement
I was using Swift for a while before I learned about the guard statement. Now I am a big fan. It is used similarly to the if statement, but it allows for early return and just makes for much cleaner code in general.
To use guard when checking to make sure that a string is neither nil nor empty, you can do the following:
let myOptionalString: String? = nil
guard let myString = myOptionalString, !myString.isEmpty else {
print("String is nil or empty.")
return // or break, continue, throw
}
/// myString is neither nil nor empty (if this point is reached)
print(myString)
This unwraps the optional string and checks that it isn't empty all at once. If it is nil (or empty), then you return from your function (or loop) immediately and everything after it is ignored. But if the guard statement passes, then you can safely use your unwrapped string.
See Also
Statements documentation
The Guard Statement in Swift 2
If you are using Swift 2, here is an example my colleague came up with, which adds isNilOrEmpty property on optional Strings:
protocol OptionalString {}
extension String: OptionalString {}
extension Optional where Wrapped: OptionalString {
var isNilOrEmpty: Bool {
return ((self as? String) ?? "").isEmpty
}
}
You can then use isNilOrEmpty on the optional string itself
func testNilOrEmpty() {
let nilString:String? = nil
XCTAssertTrue(nilString.isNilOrEmpty)
let emptyString:String? = ""
XCTAssertTrue(emptyString.isNilOrEmpty)
let someText:String? = "lorem"
XCTAssertFalse(someText.isNilOrEmpty)
}
var str: String? = nil
if str?.isEmpty ?? true {
print("str is nil or empty")
}
str = ""
if str?.isEmpty ?? true {
print("str is nil or empty")
}
I know there are a lot of answers to this question, but none of them seems to be as convenient as this (in my opinion) to validate UITextField data, which is one of the most common cases for using it:
extension Optional where Wrapped == String {
var isNilOrEmpty: Bool {
return self?.trimmingCharacters(in: .whitespaces).isEmpty ?? true
}
}
You can just use
textField.text.isNilOrEmpty
You can also skip the .trimmingCharacters(in:.whitespaces) if you don't consider whitespaces as an empty string or use it for more complex input tests like
var isValidInput: Bool {
return !isNilOrEmpty && self!.trimmingCharacters(in: .whitespaces).characters.count >= MIN_CHARS
}
If you want to access the string as a non-optional, you should use Ryan's Answer, but if you only care about the non-emptiness of the string, my preferred shorthand for this is
if stringA?.isEmpty == false {
...blah blah
}
Since == works fine with optional booleans, I think this leaves the code readable without obscuring the original intention.
If you want to check the opposite: if the string is nil or "", I prefer to check both cases explicitly to show the correct intention:
if stringA == nil || stringA?.isEmpty == true {
...blah blah
}
I would recommend.
if stringA.map(isEmpty) == false {
println("blah blah")
}
map applies the function argument if the optional is .Some.
The playground capture also shows another possibility with the new Swift 1.2 if let optional binding.
SWIFT 3
extension Optional where Wrapped == String {
/// Checks to see whether the optional string is nil or empty ("")
public var isNilOrEmpty: Bool {
if let text = self, !text.isEmpty { return false }
return true
}
}
Use like this on optional string:
if myString.isNilOrEmpty { print("Crap, how'd this happen?") }
Swift 3
For check Empty String best way
if !string.isEmpty{
// do stuff
}
Swift 3 solution
Use the optional unwrapped value and check against the boolean.
if (string?.isempty == true) {
// Perform action
}
You should do something like this:
if !(string?.isEmpty ?? true) { //Not nil nor empty }
Nil coalescing operator checks if the optional is not nil, in case it is not nil it then checks its property, in this case isEmpty. Because this optional can be nil you provide a default value which will be used when your optional is nil.
Based on this Medium post, with a little tweak for Swift 5, I got to this code that worked.
if let stringA, !stringA.isEmpty {
...blah blah
}
Although I understand the benefits of creating an extension, I thought it might help someone needing just for a small component / package.
You can create your own custom function, if that is something you expect to do a lot.
func isBlank (optionalString :String?) -> Bool {
if let string = optionalString {
return string.isEmpty
} else {
return true
}
}
var optionalString :String? = nil
if isBlank(optionalString) {
println("here")
}
else {
println("there")
}
Create a String class extension:
extension String
{ // returns false if passed string is nil or empty
static func isNilOrEmpty(_ string:String?) -> Bool
{ if string == nil { return true }
return string!.isEmpty
}
}// extension: String
Notice this will return TRUE if the string contains one or more blanks. To treat blank string as "empty", use...
return string!.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty
... instead. This requires Foundation.
Use it thus...
if String.isNilOrEmpty("hello world") == true
{ print("it's a string!")
}
Swift 3
This works well to check if the string is really empty. Because isEmpty returns true when there's a whitespace.
extension String {
func isEmptyAndContainsNoWhitespace() -> Bool {
guard self.isEmpty, self.trimmingCharacters(in: .whitespaces).isEmpty
else {
return false
}
return true
}
}
Examples:
let myString = "My String"
myString.isEmptyAndContainsNoWhitespace() // returns false
let myString = ""
myString.isEmptyAndContainsNoWhitespace() // returns true
let myString = " "
myString.isEmptyAndContainsNoWhitespace() // returns false
Using isEmpty
"Hello".isEmpty // false
"".isEmpty // true
Using allSatisfy
extension String {
var isBlank: Bool {
return allSatisfy({ $0.isWhitespace })
}
}
"Hello".isBlank // false
"".isBlank // true
Using optional String
extension Optional where Wrapped == String {
var isBlank: Bool {
return self?.isBlank ?? true
}
}
var title: String? = nil
title.isBlank // true
title = ""
title.isBlank // true
Reference : https://useyourloaf.com/blog/empty-strings-in-swift/
This is a general solution for all types that conform to the Collection protocol, which includes String:
extension Optional where Wrapped: Collection {
var isNilOrEmpty: Bool {
self?.isEmpty ?? true
}
}
When dealing with passing values from local db to server and vice versa, I was having too much trouble with ?'s and !'s and what not.
So I made a Swift3.0 utility to handle null cases and i can almost totally avoid ?'s and !'s in the code.
func str(_ string: String?) -> String {
return (string != nil ? string! : "")
}
Ex:-
Before :
let myDictionary: [String: String] =
["title": (dbObject?.title != nil ? dbObject?.title! : "")]
After :
let myDictionary: [String: String] =
["title": str(dbObject.title)]
and when its required to check for a valid string,
if !str(dbObject.title).isEmpty {
//do stuff
}
This saved me having to go through the trouble of adding and removing numerous ?'s and !'s after writing code that reasonably make sense.
Use the ternary operator (also known as the conditional operator, C++ forever!):
if stringA != nil ? stringA!.isEmpty == false : false { /* ... */ }
The stringA! force-unwrapping happens only when stringA != nil, so it is safe. The == false verbosity is somewhat more readable than yet another exclamation mark in !(stringA!.isEmpty).
I personally prefer a slightly different form:
if stringA == nil ? false : stringA!.isEmpty == false { /* ... */ }
In the statement above, it is immediately very clear that the entire if block does not execute when a variable is nil.
helpful when getting value from UITextField and checking for nil & empty string
#IBOutlet weak var myTextField: UITextField!
Heres your function (when you tap on a button) that gets string from UITextField and does some other stuff
#IBAction func getStringFrom_myTextField(_ sender: Any) {
guard let string = myTextField.text, !(myTextField.text?.isEmpty)! else { return }
//use "string" to do your stuff.
}
This will take care of nil value as well as empty string.
It worked perfectly well for me.
Swift 5.6 - Xcode 13
extension Optional where Wrapped: Collection {
var isEmptyOrNil: Bool {
guard let self = self else { return true }
return self.isEmpty
}
}
Usage:
var name: String?
if name.isEmptyOrNil {
///true
}
name = "John Peter"
guard !name.isEmptyOrNil else { return }
/// Name is not empty
you can use this func
class func stringIsNilOrEmpty(aString: String) -> Bool { return (aString).isEmpty }