Will Jamieson
Will Jamieson

Reputation: 926

Convert Int to String in Swift and remove optional wrapping?

I am attempting to convert Int? to a String and assign it to a label without including the optional text. I currently have:

struct Choice: Mappable{

    var id: String?
    var choice: String?
    var questionId: String?
    var correct: Bool?
    var responses: Int?


    init?(map: Map) {

    }


    mutating func mapping(map: Map) {
        id  <- map["id"]
        questionId  <- map["questionId"]
        choice <- map["choice"]
        correct <- map["correct"]
        responses <- map["responses"]

    }


}

In the class accessing it

var a:String? = String(describing: self.currentResult.choices?[0].responses)
        print("\(a!)")

and the output is: Optional(1)

How would I make it just output 1 and remove the optional text?

Upvotes: 1

Views: 2810

Answers (2)

dfrib
dfrib

Reputation: 73186

a is an Optional, so you need to unwrap it prior to applying a String by Int initializer to it. Also, b needn't really be an Optional in case you e.g. want to supply a default value for it for cases where a is nil.

let a: Int? = 1
let b = a.map(String.init) ?? "" // "" defaultvalue in case 'a' is nil

Or, in case the purpose is to assign the possibly existing and possibly String-convertable value of a onto the text property of an UILabel, you could assign a successful conversion to the label using optional binding:

let a: Int? = 1
if let newLabelText = a.map(String.init) {
    self.label.text = newLabelText
}

Upvotes: 5

loretoparisi
loretoparisi

Reputation: 16271

Why don't?

let a : Int = 1
var b = "\(a)"
print(b)

so

$ swift
[ 9> let a : Int = 1
a: Int = 1
[ 10> var b = "\(a)"
b: String = "1"
[ 11> print(b)
1

By the way there are other options like this one

12> var c = a.description
c: String = "1"
 13> print(c)
1

Upvotes: 0

Related Questions