Unable to solve this Null issue in swift 4? - swift

I am trying to check value which I am receiving from the server, if a string is empty I am using the following condition.
var line2Cvar = permanentCAddVarDictionary?["line2"] as! String
if line2Cvar.isEmpty {
line2Cvar = "---"
}
self.permanentCAddDic.setValue(line2Cvar, forKey: "line2Cvar")
if a string is null I am using the following condition.
var line2Cvar = permanentCAddVarDictionary?["line2"]
if line2Cvar is NSNull {
line2Cvar = "----"
}
self.emergencyContactDic.setValue(line2Cvar, forKey: "line2Cvar")
but in my case sometimes I am getting empty and sometimes I am getting a null value. how check string is empty or null directly.

When checking for a string in a dictionary, you have 4 possible states:
the string is present, and non-empty
the string is present, but empty
the key is in the dictionary, but the value isn't a string
the key is absent from the dictionary
You have to check each case individually.
let possibleString = dict[key]
if let string = possibleString as? String {
if string.isEmpty {
// deal with empty case
} else {
// deal with non-empty case
}
} else if possibleString == nil {
// deal with key not-present case
} else {
// deal with value-not-string case
}
You can combine some checks and eliminate others, depending on the particular logic you require. For example, if you want to treat not-present and not-a-string the same way, you can eliminate the nil check, and just fall-through to the final else.

extension String {
var isEmptyNull:Bool {
let string = self.trimmingCharacters(in: CharacterSet.whitespaces)
if string == "" || string.lowercased() == "null" {
return true
}else {
return false
}
}
}
You can check here
let stringvalue = ""
if stringvalue.isEmptyNull {
print("string value is empty or null")
}else {
print(stringvalue)
}
output
string value is empty or null

Related

Getter Setter With Type of Any Swift

Is it possible to do a getter and setter for an attribute that has a type of 'Any'
Here is my thought:
private var _valueObject: Any?
public var valueObject: Any? {
set {
if newValue is String {
self._valueObject = newValue as? String
} else if newValue is BFSignature {
self._valueObject = newValue as? BFSignature
}
}
get {
if self._valueObject is String {
return self._valueObject as? String
} else if self._valueObject is BFSignature {
return self._valueObject as? BFSignature
} else {
return self._valueObject
}
}
}
When I try to use it through out my code though I get errors stating:
Cannot compare String to type Any
Is there a way to use something like this without casting the 'valueObject' to a string whenever I need it. A way to use it and it already knows its a 'String' or 'BFSignature' instead of 'Any'.
Here is an example of the error:
I would rather it just know that cellValue is a 'String.' Instead of casting it each time I use it.
You shouldn't use Any
In my opinion, you should make a common representation of the API call result instead of using Any. You know exactly what the API is going to return, don't you? It's either a String or something that you turn into your custom object BFSignature.
Therefore, you can make an enum to represent your API call result:
enum APIResult {
case signature(BFASignature)
case justString(String)
}
and use it like
private var _valueObject: APIResult?
if let stringValue = newValue as? String {
self._valueObject = .justString(stringValue)
}
if let signatureValue = newValue as? BFSignature {
self._valueObject = .signature(signatureValue)
}
If there are a fixed number of types that you need to use here, you can use an enum:
struct BFSignature {
var a: Int
}
enum Either {
case bfSig(BFSignature)
case string(String)
}
var a: Either
var b: Either
a = .bfSig(BFSignature(a: 7))
b = .string("Stack Overflow")
a = b
Usage:
switch (b) {
case Either.bfSig(let signature):
print(signature.a) // Output integeral value
case Either.string(let str):
print(str) //Output string value
}

Converting a rawValue into a string in Swift

Apple has made changes from Swift 3 to 4. When I run the following code:
let metadata = [ PDFDocumentAttribute.titleAttribute,
PDFDocumentAttribute.authorAttribute,
PDFDocumentAttribute.subjectAttribute,
PDFDocumentAttribute.creatorAttribute,
PDFDocumentAttribute.producerAttribute,
PDFDocumentAttribute.creationDateAttribute,
PDFDocumentAttribute.modificationDateAttribute,
PDFDocumentAttribute.keywordsAttribute ]
if var attributes = pdfDoc.documentAttributes {
for (index, value) in metadata.enumerated() {
if attributes[value] != nil {
print("\(metadata[index])): \(String(describing: attributes[value]!))")
} else {
print("\(metadata[index]): nil")
}
}
I now get: PDFDocumentAttribute(_rawValue: Title) instead of "Title", which I got before as the value of metadata[index].
How do I get rid of the rawValue stuff?
The PDFDocumentAttribute type has a property called rawValue that contains the old string value. So you can say
print("\(metadata[index].rawValue): \(String(describing: attributes[value]!))")
As an aside, instead of force-unwrapping the attribute you can use an if let, as in
if let attr = attributes[value] {
print("\(metadata[index].rawValue): \(attr)")
} else {
print("\(metadata[index].rawValue): nil")
}
If you add this extension:
extension PDFDocumentAttribute: CustomStringConvertible {
public var description: String {
return self.rawValue
}
}
Now you can just do:
// Forcing the downcast has little risk here
// but you may want to use `as?` and test for the optional instead
let attributes = pdfDoc.documentAttributes as! [PDFDocumentAttribute:Any]
for meta in metadata {
print("\(meta): \(attributes[meta] ?? "nil")")
}
Note that you can also do:
for attribute in attributes {
print("\(attribute.key): \(attribute.value)")
}
Which will just print out the attributes that exist on the document.

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 }

Verify a string as a valid UUID in Swift

Given an supplied String, how can I verify wether the String is a valid UUID in Swift?
A valid UUID (as far as I know) could be:
33041937-05b2-464a-98ad-3910cbe0d09e
3304193705b2464a98ad3910cbe0d09e
You could use UUID
var uuid = UUID(uuidString: yourString)
This will return nil if yourString is not a valid UUID
Note: this only validates the first case you presented, not the second but adding the dashes yourself is trivial.
The following is updated for Swift 4.0 to determine if a string is a valid UUID.
let uuidHyphens = "33041937-05b2-464a-98ad-3910cbe0d09e"
let uuidNoHyphens = "3304193705b2464a98ad3910cbe0d09e"
if UUID(uuidString: uuidHyphens) != nil {
print("UUID string with hypens is valid") // Will be valid
} else {
print("UUID string with hypens is not valid")
}
// In this scenario, the UUID will be nil,
if UUID(uuidString: uuidNoHyphens) != nil {
print("UUID string with no hypens is valid")
} else {
print("UUID string with no hypens is not valid") // Will not be valid
}
The string passed in to the UUID init must contain hyphens, otherwise the check will fail. If you are expecting strings without hypens, then you can utilize an approach such as what is discussed here to add hypens to a string if it satisfies a length of 32.
The relevant section from Apple's documentation:
Create a UUID from a string such as
“E621E1F8-C36C-495A-93FC-0C247A3E6E5F”.
I wrote the extension below to make UUID Strings
extension String {
var uuid: String? {
var string = self
var index = string.index(string.startIndex, offsetBy: 8)
for _ in 0..<4 {
string.insert("-", at: index)
index = string.index(index, offsetBy: 5)
}
// The init below is used to check the validity of the string returned.
return UUID(uuidString: string)?.uuidString
}
}

How to check is a string or number?

I have an array ["abc", "94761178","790"]
I want to iterate each and check is a String or an Int?
How to check it?
How to convert "123" to integer 123?
Here is a small Swift version using String extension :
Swift 3/Swift 4 :
extension String {
var isNumber: Bool {
return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
}
Swift 2 :
extension String {
var isNumber : Bool {
get{
return !self.isEmpty && self.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) == nil
}
}
}
Edit Swift 2.2:
In swift 2.2 use Int(yourArray[1])
var yourArray = ["abc", "94761178","790"]
var num = Int(yourArray[1])
if num != nil {
println("Valid Integer")
}
else {
println("Not Valid Integer")
}
It will show you that string is valid integer and num contains valid Int.You can do your calculation with num.
From docs:
If the string represents an integer that fits into an Int, returns the
corresponding integer.This accepts strings that match the regular
expression "[-+]?[0-9]+" only.
Be aware that checking a string/number using the Int initializer has limits. Specifically, a max value of 2^32-1 or 4294967295. This can lead to problems, as a phone number of 8005551234 will fail the Int(8005551234) check despite being a valid number.
A much safer approach is to use NSCharacterSet to check for any characters matching the decimal set in the range of the string.
let number = "8005551234"
let numberCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
if !number.isEmpty && number.rangeOfCharacterFromSet(numberCharacters) == nil {
// string is a valid number
} else {
// string contained non-digit characters
}
Additionally, it could be useful to add this to a String extension.
public extension String {
func isNumber() -> Bool {
let numberCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
return !self.isEmpty && self.rangeOfCharacterFromSet(numberCharacters) == nil
}
}
I think the nicest solution is:
extension String {
var isNumeric : Bool {
return Double(self) != nil
}
}
Starting from Swift 2, String.toInt() was removed.
A new Int Initializer was being introduced: Int(str: String)
for target in ["abc", "94761178","790"]
{
if let number = Int(target)
{
print("value: \(target) is a valid number. add one to get :\(number+1)!")
}
else
{
print("value: \(target) is not a valid number.")
}
}
Swift 3, 4
extension String {
var isNumber: Bool {
let characters = CharacterSet.decimalDigits.inverted
return !self.isEmpty && rangeOfCharacter(from: characters) == nil
}
}
Simple solution like this:
extension String {
public var isNumber: Bool {
return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
}
I think using NumberFormatter is an easy way:
(Swift 5)
import Foundation
extension String {
private static let numberFormatter = NumberFormatter()
var isNumeric : Bool {
Self.numberFormatter.number(from: self) != nil
}
}
The correct way is to use the toInt() method of String, and an optional binding to determine whether the conversion succeeded or not. So your loop would look like:
let myArray = ["abc", "94761178","790"]
for val in myArray {
if let intValue = val.toInt() {
// It's an int
println(intValue)
} else {
// It's not an int
println(val)
}
}
The toInt() method returns an Int?, so an optional Int, which is nil if the string cannot be converted ton an integer, or an Int value (wrapped in the optional) if the conversion succeeds.
The method documentation (shown using CMD+click on toInt in Xcode) says:
If the string represents an integer that fits into an Int, returns the corresponding integer. This accepts strings that match the regular expression "[-+]?[0-9]+" only.
This way works also with strings with mixed numbers:
public extension String {
func isNumber() -> Bool {
return !self.isEmpty && self.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil && self.rangeOfCharacter(from: CharacterSet.letters) == nil
}}
So u get something like this:
Swift 3.0 version
func isNumber(stringToTest : String) -> Bool {
let numberCharacters = CharacterSet.decimalDigits.inverted
return !s.isEmpty && s.rangeOfCharacter(from:numberCharacters) == nil
}
If you want to accept a more fine-grained approach (i.e. accept a number like 4.5 or 3e10), you proceed like this:
func isNumber(val: String) -> Bool
{
var result: Bool = false
let parseDotComNumberCharacterSet = NSMutableCharacterSet.decimalDigitCharacterSet()
parseDotComNumberCharacterSet.formUnionWithCharacterSet(NSCharacterSet(charactersInString: ".e"))
let noNumberCharacters = parseDotComNumberCharacterSet.invertedSet
if let v = val
{
result = !v.isEmpty && v.rangeOfCharacterFromSet(noNumberCharacters) == nil
}
return result
}
For even better resolution, you might draw on regular expression..
Xcode 8 and Swift 3.0
We can also check :
//MARK: - NUMERIC DIGITS
class func isString10Digits(ten_digits: String) -> Bool{
if !ten_digits.isEmpty {
let numberCharacters = NSCharacterSet.decimalDigits.inverted
return !ten_digits.isEmpty && ten_digits.rangeOfCharacter(from: numberCharacters) == nil
}
return false
}
This code works for me for Swift 3/4
func isNumber(textField: UITextField) -> Bool {
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: textField.text!)
return allowedCharacters.isSuperset(of: characterSet)
// return true
}
You can use this for integers of any length.
func getIntegerStrings(from givenStrings: [String]) -> [String]
{
var integerStrings = [String]()
for string in givenStrings
{
let isValidInteger = isInteger(givenString: string)
if isValidInteger { integerStrings.append(string) }
}
return integerStrings
}
func isInteger(givenString: String) -> Bool
{
var answer = true
givenString.forEach { answer = ("0"..."9").contains($0) && answer }
return answer
}
func getIntegers(from integerStrings: [String]) -> [Int]
{
let integers = integerStrings.compactMap { Int($0) }
return integers
}
let strings = ["abc", "94761178", "790", "18446744073709551615000000"]
let integerStrings = getIntegerStrings(from: strings)
let integers = getIntegers(from: integerStrings)
print(integerStrings) // ["94761178", "790", "18446744073709551615000000"]
print(integers) // [94761178, 790]
However, as pointed out by #Can, you can get the integer value for the number only up to 2^31 - 1 (signed integer limit on 32-bit arch). For the larger value, however, you will still get the string representation.
This code will return an array of converted integers:
["abc", "94761178","790"].map(Int.init) // returns [ nil, 94761178, 790 ]
OR
["abc", "94761178","790"].map { Int($0) ?? 0 } // returns [ 0, 94761178, 790 ]
Get the following isInteger() function from the below stackoverflow post posted by corsiKa:
Determine if a String is an Integer in Java
And I think this is what you want to do (where nameOfArray is the array you want to pass)
void convertStrArrayToIntArray( int[] integerArray ) {
for (int i = 0; i < nameOfArray.length(); i++) {
if (!isInteger(nameOfArray[i])) {
integerArray[i] = nameOfArray[i].toString();
}
}
}