外观
ios
493字约2分钟
2020-06-25
Swift
简介
- Swift用于开发iOS、OS X、watchOS。结合了C和Objective-C的优点并且不受
数据类型
- int
- 十进制整型 123
- 十六进制整型 0x1231f1
- float
- 2434.34
- 12.4e6
- double
- 143.4f
- char
- 'a'
- 常量
let name = jinchen
let number : Double = 50 指定类型
let apples = 3
let appleSummary = "I have \(apples) apples"- 变量
var name = "jinchen"- 数组
var arr = ["a", "b", "c"]
var arr = []- 字典
var dict = ["name1" : "value1", "name2" : "value2" ]
var dict = [:]字符串
- 字面量
let some = "some things";- 空字符串
var emptyString = "" var emptyString = String() if emptyString.isEmpty { print("Nothing to see here"); }- 字符串可变性
字面量是常量还是变量确定字符串的可变性 字符串值类型 for character in "Dog" { print(character); }- 字符串数量
let name = "jinchen" print("name has (name.count) character")- 连接字符串和字符
let character1 :Character = "!" var welcome = "good morning" welcome += character1- 字符串插值
let num = 3 let message = "(num) times"- 比较字符串
- 字符串相等
let name1 = "jinchen" let name2 = "jinchen" if name1 == name2 { print("These two strings are considered equal") }- 字符串前缀、后缀比较 hasPrefix、hasSuffix
let romeoAndJuliet = { "Act 1 AAAAA", "Act 1 BBBBB", "Act 1 CCCCC", "Act 2 AAAAA", } var act1count = 0 for scene in romeoAndJuliet { if scene.hasPrefix("Act 1") { ++act1count } } print(act1count); - 字符串大写、小写
let name = “JinChen” let name1 = name.uppercaseString let name2 = name.lowercaseString
流程控制
for循环
- for- in
for index in 1...5 { // ...表示序列 print(index) } for _ in 1...5 { print("HelloWorld") } let interestingNumbers = [ "Frime": [2, 3, 5, 7, 11, 13], "Equarl": [1, 4, 9, 16, 25] ] var largest = 0 for (kind, numbers) in interestingNumbers { for number in numbers { if(number > largest) { largest = number } } } print(largest)- 增量循环 Swift3 已经删除C样式语句
for var index1 = 0; index1 < 3; ++index1 { print(index1) }while循环
- while
var n = 2 while n < 100 { n = n + 30 } print(n)- repeat-while
var m = 2 repeat { m = m + 30 } while m < 100 print(m)if语句
var num2 = "jin"
if(num2 == "jinchen") {
print(1)
} else if(num2 == "jin") {
print(2)
} else {
print(3)
}- switch
let someCharacter : Character = "e"
switch someCharacter {
case "a", "b":
print("AA")
case "e":
print("BB")
default:
print("CC")
}函数
- 单返回值
func sayHello(personName: String) -> String {
let message = "Hello (personName)"
return message
}
print(sayHello(personName: "Jc"))- 多返回值
func count(string: String) -> (vowels: String, others: String) {
var vowels = "A", others = "B"
vowels += string
others += string
return (vowels, others)
}
print(count(string: "Jc"))