【Swift 60秒】05 - String interpolation

0x00 Lesson

You’ve seen how you can type values for strings directly into your code, but Swift also has a feature called string interpolation - the ability to place variables inside your strings to make them more useful.

You can place any type of variable inside your string - all you have to do is write a backslash, \, followed by your variable name in parentheses.

For example:

var score = 85
var str = "Your score was \(score)"

As you can see in the playground output, that sets the str variable to be “Your score was 85”.

You can do this as many times as you need, making strings out of strings if you want:

var results = "The test results are here: \(str)"

As you’ll see later on, string interpolation isn’t just limited to placing variables - you can actually run code inside there.


0x01 Test

Which of these lines use string interpolation?

01

var message = "Installation failed: \{reason}."

02

var formattedHheight = "You are (size)cm"

03

var str = "Hello, playground!"

04

var result = "\(daysRemaining) days to go"

05

var versionString = "You're using v(version)"

Answer:
01 - String interpolation is written as \(reason)

02 - String interpolation is written as \(size)

03 - This is just a plain string.

04 - true

05 - String interpolation is written as \(version)


0x02 我的小作品

欢迎体验我的作品之一:小五笔 86 版
五笔学习好帮手
App Store 搜索即可~


猜你喜欢

转载自blog.csdn.net/xjh093/article/details/126700450