简体   繁体   English

Swift println不打印数组值

[英]Swift println doesn't print array value

I'm brand new learning Swift and I was wondering what I am doing wrong here? 我是全新学习Swift的人,我想知道我在这里做错了什么吗? I like to play around with code to gain an understanding. 我喜欢尝试使用代码来获得理解。

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.")

I'm trying to figure out why the output doesn't say "Susie checks her Shopping List to find that a bag of tulips is her third item." 我试图弄清楚为什么输出中没有显示“ Susie检查她的购物清单以发现一袋郁金香是她的第三件商品”。 as opposed to what it says currently: exactly as above, "Susie checks her Shopping List to find that a (shoppingList[2]) is her third item." 与目前所说的相反:完全如上所述,“ Susie检查了她的购物清单,发现(shoppingList [2])是她的第三项。”

I know this is an ultra basic concept and all but I want to make sure I understand everything 100%. 我知道这是一个超基本的概念,但我想确保我100%理解所有内容。

Thanks! 谢谢!

The problem here is that you are simply outputting the string "(shoppingList[2])". 这里的问题是您只是输出字符串“(shoppingList [2])”。

To replace this with the value you want, you must first escape the string using a \\ . 要将其替换为所需的值,必须首先使用\\对该字符串进行转义。

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."

This is called String Interpolation and you can find more information here . 这称为字符串插值,您可以在此处找到更多信息。

You need a \\ in front of the () . 您需要在()前面加一个\\

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 字符串插值

As in Apple docs: 如Apple文档中所示:

“Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable. “ Swift使用字符串插值法将常数或变量的名称作为占位符包含在较长的字符串中,并提示Swift将其替换为该常数或变量的当前值。 Wrap the name in parentheses and escape it with a backslash before the opening parenthesis.” 将名称括在括号中,并在左括号前使用反斜杠将其转义。”

In your case, the code should be: 就您而言,代码应为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM