How to Remove "Optional" from String

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)
}
}

Removing Optional in Swift 4

Just unwrap it.

if let temperature = Int(incomeTemp.text!) {
celcjuszScore.text = "\(temperature)"
print(temperature)
}

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 ^^

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.

Get rid of Optional [] String?

You can use Optional#orElseGet e.g.

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

class Question {
private String title;

public Question(String title) {
this.title = title;
}

public String getTitle() {
return title;
}
}

public class Main {
public static void main(String[] args) {
// Test
Question q1 = new Question("Hello");
Question q2 = new Question("World");
System.out.println(getShortestTitel(List.of(q1, q2)).orElseGet(() -> ""));
}

public static Optional<String> getShortestTitel(List<Question> list) {
// return the the shortest title
return list.stream().map(Question::getTitle).min(Comparator.comparingInt(String::length));
}
}

Output:

Hello

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)"
}
}
}

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
}

How do I remove Optional() from object in an array

As you designed the database model you exactly know which record attributes always exist. Declaring class properties as implicit unwrapped optional as an alibi not to write an initializer is very bad practice.

Assuming every attribute in a record does have a value declare the properties as non-optional and write an initializer.

At least created and recordID are supposed to have always a value!

import UIKit
import CloudKit

class StartDay {

var recordID: CKRecord.ID
var wakeUp: String
var sleptWell: String
var dNN: String
var created: String

init(record : CKRecord) {
// recordID can be retrieved directly
self.recordID = record.recordID
self.wakeUp = record.object(forKey: "wakeUP") as! String
self.sleptWell = record.object(forKey: "sleptWell") as! String
self.dNN = record.object(forKey: "dNN") as! String
self.created = record.object(forKey: "createdDato") as! String
}
}

and create instances with

operation.recordFetchedBlock = { record in
startDays.append(StartDay(record: record))
}

Now the Optional has gone.

print(startDayList.map{ $0.created })


Related Topics



Leave a reply



Submit