aka ak aka ak - 23 days ago 10
iOS Question

Value of optional type [String] not wrapped

I'm currently a making IOS app using Stripe. When I tried to implement a Stripe card object( the image below), I got a compiler error on the line

var expMonth: NSNumber = Int(expArr[0])!
var expYear: NSNumber = Int(expArr[1])!


saying
"Type of optional type [String] not wrapped. not unwrapped; did you mean to use ! or ??"

func buttonPressed(_: UIButton) {

let creditCard = STPCardParams()
creditCard.number = cardNumberTextField.text
creditCard.cvc = cvvTextField.text

if (expDateTextField.text?.isEmpty == nil){

let expArr = expDateTextField.text?.components(separatedBy: "/")
if (expArr?.count)! > 1 {

var expMonth: NSNumber = Int(expArr[0])!
var expYear: NSNumber = Int(expArr[1])!

creditCard.expMonth = expMonth.uintValue
creditCard.expYear = expYear.uintValue


How can I fix this error? Your help would be appreciated!

Answer

Your expArr is of type [String]?. You can check this by force-clicking on the variable name.

And since it is an optional, you must unwrap it before you access an item in the array here:

var expMonth: NSNumber = Int(expArr[0])!
var expYear: NSNumber = Int(expArr[1])!

You can either do it by force unwrapping it:

var expMonth: NSNumber = Int(expArr![0])!
var expYear: NSNumber = Int(expArr![1])!

Or you can do it through conditional binding, which is safer:

if let expirationDates = expArr {
    var expMonth: NSNumber = Int(expirationDates[0])!
    var expYear: NSNumber = Int(expirationDates[1])!

    creditCard.expMonth = expirationDates.uintValue
    creditCard.expYear = expirationDates.uintValue

    // ...
}
Comments