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)
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With