
6

用 10 个简单的代码片段介绍 Swift
source link: https://www.fly63.com/article/detial/12605
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1.变量的声明和初始化
var myVariable = 42
2. 常量的声明和初始化
let mynumber = 5
3. 连接字符串
var mytext = "My name is "
var name = "John"
var sentence = mytext + name
4. 在字符串内执行操作
let age = 44
let mytext = "My name is John and I am \(age) years old"
5.声明一个Int类型的可选变量
var mynumber: Int?
6. 解包同名的可选值
var count = 0
var mynumber: Int? = 5
if let mynumber {
count = count + mynumber
}
print("count is \(count)")
7. 声明隐式解包选项
var mynumber: Int!
mynumber = 42
mynumber = mynumber + 1
8. 使用逻辑运算符检查多个条件
var mynumber = 42
if mynumber > 0 && mynumber < 100 {
print("The number is between 0 and 100")
}
9. 用开关检查条件
var age = 19
var mssage = ""
switch age {
case 0...2:
message = "Infant"
case 3...12:
message = "Child"
case 13...19:
message = "Teenager"
case 20...39:
message = "Adult"
default:
message = "Elderly"
}
10. 使用 while 创建循环
var counter = 0
while counter < 5 {
print ( "counter is \(counter) " )
counter = counter + 1
}
这些只是 Swift 的基础知识。还有很多东西需要探索和学习。快乐编码!
</section
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK