Cedric Cedric - 6 months ago 63
Swift Question

Swift cannot assign value of type '()' to type 'String?'

I'm learning Swift2/iOS app development. I am confused by an error being thrown by Xcode before compiling. Here is the code throwing the error :

let dotpos = display.text!.rangeOfString(".")
if dotpos != nil {
display.text = display.text!.removeRange(dotpos!)
}


The error thrown is (at the line "display.text = display.text!.removeRange(dotpos!)") :


Cannot assign value of type '()' to type 'String?'


Note : display is a
UILabel
object.

Could someone point me toward the error I might have done?

Answer

you need to check documentation for this (Apple swift String link)

let dotpos = display.text!.rangeOfString(".")
if dotpos != nil {
    display.text!.removeRange(dotpos!)
}

This code will work, removeRange function didn't return anything, documentation said

mutating func removeRange(_ subRange: Range)

means text mutate when you call the method on your text label.

The text change directly and you don't need to assign new value for changing it.