Swift cannot assign to immutable value of type 'string'

Discussion in 'iOS Programming' started by njharris97, Jun 5, 2015.

  1. njharris97, Jun 5, 2015
    Last edited by a moderator: Jun 5, 2015

    njharris97 macrumors member


    I have just started to learn a programming language from scratch, and am working with Swift. Can anyone solve this problem.

    func apple123(){
        var apple = "1"
        if apple = "2" {              - here I get the error cannot assign to immutable value of type 'string'
        else {
    Thanks in advance
  2. chown33 macrumors 604

    Aug 9, 2009
    What do you intend this line of code to do:
        if apple = "2" {              - here I get the error cannot assign to immutable value of type 'string'
    Is it to compare a string with another string ("2")? Or is it to assign a string ("2") to a variable?

    If your intent is comparison, then you need to review the comparison operators and look very carefully at what code you wrote.

    If your intent is assignment, then you should rethink the use of if/else.
  3. kage207 macrumors 6502a

    Jul 23, 2008
    Exactly what chown33 said. You need to understand the difference between an Assignment and a Comparison in code. You are using an Assignment in the If Statement. Use == operator to for Comparisons. Read this article: https://developer.apple.com/library....html#//apple_ref/doc/uid/TP40014097-CH6-ID76
  4. KoolStar macrumors demi-god


    Oct 16, 2006

Share This Page