Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am creating String by using String(char) but getting optional value with that, how to remove it?

Tags:

my output is coming like "Optional(\"A\") but I want only string "A". I have to apply filter on my array by using this character.

let char  = selectedSection.characters.last
let str = String(char)
let array = result?.objectForKey("GetClassPeriodList") as! NSArray
let filtered = array.filter {
    return ($0["Section_Code"] as! String) == str
}
print(filtered)
like image 720
sukhmeet Avatar asked Aug 30 '16 05:08

sukhmeet


People also ask

How do you remove something from string?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

How do I remove special characters from a string in Python?

But by using the ord() function, this function returns the Unicode of a character. This can be used to remove a character from a string.

How do you remove a given character from string?

We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.


1 Answers

As @martin-r says, last gives you an optional because you can not be certain that when you ask for the last character of a collection, you actually end out with a character, what if the collection was empty for instance?

What you can do is unwrap it using if let, so you could write:

if let char  = selectedSection.characters.last {
    let str = String(char)
    let array = result?.objectForKey("GetClassPeriodList") as! NSArray
    let filtered = array.filter {
        return ($0["Section_Code"] as! String) == str
    }
    print(filtered)
}

And then you know for certain that your char contains a value which you can continue to work with.

You can read more about optionals here

Hope that helps you.

like image 198
pbodsk Avatar answered Sep 23 '22 16:09

pbodsk