How to remove Optional from String Value Swift
Just like @GioR said, the value is Optional(52.523553) because the type of latstring is implicitly: String?. This is due to the fact that
let lat = data.value(forKey: "lat")
will return a String? which implicitly sets the type for lat.
see https://developer.apple.com/documentation/objectivec/nsobject/1412591-value
for the documentation on value(forKey:)
Swift has a number of ways of handling nil. The three that may help you are,
The nil coalescing operator:
??
This operator gives a default value if the optional turns out to be nil:
let lat: String = data.value(forKey: "lat") ?? "the lat in the dictionary was nil!"
the guard statement
guard let lat: String = data.value(forKey: "lat") as? String else {
//Oops, didn't get a string, leave the function!
}
the guard statement lets you turn an optional into it's non-optional equivalent, or you can exit the function if it happens to be nil
the if let
if let lat: String = data.value(forKey: "lat") as? String {
//Do something with the non-optional lat
}
//Carry on with the rest of the function
Hope this helps ^^
Removing Optional in Swift 4
Just unwrap it.
if let temperature = Int(incomeTemp.text!) {
celcjuszScore.text = "\(temperature)"
print(temperature)
}
How to remove optional from a string value in swift?
The problem is in the line
grandtotal = String(describing: grandtotal)
You check for nil
but you don't unwrap the value so it's still an optional.
And you are misusing String(describing
. Never use it for types which can be converted to String
with an init
method.
Use always conditional downcast
if success == false {
if let grandtotal = value["total"] as? Double {
self.lblTotalAmount.text = String(grandtotal)
}
}
Swift How to remove optional String word
//replace your code with this your are not force unwrapping the symbol
public func getCurrencySymbolFromCurrencyCode(currencyCode: String) -> String! {
// let currencyCode: String = "EUR"
let locale: NSLocale = NSLocale(localeIdentifier: currencyCode)
let symbol = locale.displayNameForKey(NSLocaleCurrencySymbol, value: currencyCode)!
let currencySymbol: String = "\(symbol)"
print("Currency Symbol : \(currencySymbol)")
return currencySymbol
}
Unable to remove Optional from String
Your line
(String(location?.latitude), String(location?.longitude))
is the culprit.
When you call String()
it makes a String
of the content, but here your content is an Optional, so your String is "Optional(...)"
(because the Optional type conforms to StringLiteralConvertible, Optional(value)
becomes "Optional(value)"
).
You can't remove it later, because it's now text representing an Optional, not an Optional String.
The solution is to fully unwrap location?.latitude
and location?.longitude
first.
Remove optional keyword while displaying string - Swift
Replace this
releaseDateLabel.text = "\(releaseDateText): \(String(describing: date != "" ? Date.getMMMddyyyyDateFormat(date) : "\(tbaText)" ))"
with
releaseDateLabel.text = "\(releaseDateText): \(date != "" ? Date.getMMMddyyyyDateFormat(date)! : "\(tbaText)" ))
for safty try
if date != "" {
if let str = Date.getMMMddyyyyDateFormat(date) {
releaseDateLabel.text = "\(releaseDateText): \(str)"
}
}
else {
releaseDateLabel.text = "\(releaseDateText): \(tbaText)"
}
how to remove optional from string i have used following code
When you subscript it will already return optional and you are setting dictionary with value String?
means you are getting optional twice also specifying array of AnyObject make it array of [[String:String]]
so no need to cast it letter again. Also initialized the strValue
with empty string.
var strValue = ""
if let dicArray = array as? [[String:String]] {
for dic in dicArray {
if let title = dic["title"], let value = dic["value"] {
strValue += "\n\n \(title) \n\n\(value)"
}
}
}
Remove optional from string getting from NSNotification
For your current code. It should be:
func getAlertMsg(notification: NSNotification) {
if let string = notification.object as? String {
Helper.showAsAlert(strMessage: string, VC: self)
}
}
Also, your notification post should be:
let strMessage = responseVal.value(forKey: "message") as? String
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "RegAlertMsg"),
object: strMessage)
Just pass strMessage
. Don't bang (!) it or you app will crash when responseVal.value(forKey: "message") as? String
fails.
Swift remove optionals and unnecessary characters iOS
First of all struct names are supposed to start with a capital letter
Just remove the exclamation marks in the struct.
Never declare members / properties as IUO if there is an initializer with non-optional values.
struct Item : Codable {
var title : String
var size : String
init(title: String, size: String) {
self.title = title
self.size = size
}
}
Second of all
Never use value(forKey
with UserDefaults
.
In this case there is a dedicated method data(forKey
otherwise use object(forKey
or other dedicated methods for scalars (integer(forKey
, bool(forKey
etc.). However this is not related to the issue.
if let data = UserDefaults.standard.data(forKey:"items") {
Finally catch
always errors when using Codable
and don't misuse the String(describing
initializer
do {
let itemsUser = try PropertyListDecoder().decode(Array<Item>.self, from: data)
print("*************", itemsUser)
} catch { print(error) }
}
To get rid of the app name in a print
statement adopt CustomStringConvertible
and add your own description
struct Item : Codable, CustomStringConvertible {
var title : String
var size : String
init(title: String, size: String) {
self.title = title
self.size = size
}
var description : String {
return "title : \(title), size : \(size)"
}
}
Related Topics
How to Capture Depth Data from Camera in iOS 11 and Swift 4
@Objc Keyword Extension Subclass Behaviour
How to Change Navigation Bar & Back Button Colour iOS 15
Why Should Not Directly Extend Uiview or Uiviewcontroller
What Is a 'Non-Nominal Type' in Swift
Checking If a Double Value Is an Integer - Swift
Difference Between Using Objectidentifier() and '===' Operator
How to Make a Swift Enum with Uicolor Value
How to Drag and Drop a Sprite in Swift 3.0
Checking If Textfields Are Empty Swift
Curl Through Nstask Not Terminating If a Pipe Is Present
How to Test Whether Generic Variable Is of Type Anyobject
Difference Between Force Unwrapping Optionals and Implicitly Unwrapped Optionals
Swift Package Manager - Uikit Dependency