【问题标题】:Swift println doesn't print array valueSwift println 不打印数组值
【发布时间】:2014-07-01 01:29:20
【问题描述】:

我是全新的 Swift 学习者,我想知道我在这里做错了什么?我喜欢玩弄代码来获得理解。

var shoppingList = ["pound of catfish", "bottle of fresh water", "bag of tulips", "can of blue paint"]

println("Susie checks her Shopping List to find that a \(shoppingList[2]) is her third item.")

我试图弄清楚为什么输出没有显示“Susie 检查她的购物清单,发现一袋郁金香是她的第三件商品。”与目前所说的相反:正如上面所说,“Susie 检查她的购物清单,发现 (shoppingList[2]) 是她的第三件商品。”

我知道这是一个超基本的概念,但我想确保我 100% 理解所有内容。

谢谢!

【问题讨论】:

    标签: ios xcode swift


    【解决方案1】:

    这里的问题是你只是输出字符串“(shoppingList[2])”。

    要将其替换为您想要的值,您必须首先使用 \ 转义字符串。

    var shoppingList = ["pound of catfish", "bottle of fresh water", "bag of tulips", "can of blue paint"]
    
    "Susie checks her Shopping List to find that a \(shoppingList[2]) is her third item."
    

    这称为字符串插值,您可以找到更多信息here

    【讨论】:

      【解决方案2】:

      您需要在() 前面加上\

      var shoppingList = ["pound of catfish", "bottle of fresh water", "bag of tulips", "can of blue paint"]
      
      "Susie checks her Shopping List to find that a \(shoppingList[2]) is her third item."
      

      String Interpolation

      【讨论】:

        【解决方案3】:

        在 Apple 文档中:

        “Swift 使用字符串插值来包含常量的名称或 变量作为较长字符串中的占位符,并提示 Swift 将其替换为该常量或变量的当前值。裹 括号中的名称并在 左括号。”

        在你的情况下,代码应该是:

        println("Susie checks her Shopping List to find that a \(shoppingList[2]) is her third item.")
        

        【讨论】: