func demo() {
let oName:
String? =
"张三"
let oAge:
Int? =
10
if oName != nil && oAge != nil {
print(oName! +
String(oAge!))
}
}
// if let /
var 连用 判断对象的值是否为nil
if let name = oName,
age = oAge {
//进入分支后 一定有值,不需要解包
print(name + String(age))
}
// guard
let 守护一定有值,如果没有直接返回 刚好与
if let 相反
func demo2() {
let oName: String? =
"张三"
let oAge: Int? =
10
guard
let name = oName,
age = oAge
else {
print(
"姓名或者年龄为nil")
return
}
}
// 小技巧
func demo3(
name: String?,
age: Int?) {
//guard
let &
if let
guard
let name = name, age = age
else {
print(
"姓名火年龄为nil")
return
}
}
func demo4(num: String) {
swith: num {
case "10",
"9":
print(
"我")
break
case "11":
print(
"你")
break
default:
print(
"其他")
break
}
}
func demo() {
for var i =
0; i <
10; i +=
1 {
}
}
func demo() {
let str: String =
"我要飞得更高"
for c in
str.characters {
print(c)
}
}
func demo() {
let str:
"hello world你好"
print(
str.lengthOfBytes(using: .utf8))
print(
str.characters.count)
let ocStr =
str as NSString
print(ocStr.length)
}
func demo() {
let name =
"小王"
let age =
10
let title: String =
"BOSS"
let point = CGPoint(x:
100, y:
100)
let str =
"\(name) \(age) \(title ?? "") \(point)"
print(
str)
}
func demo() {
let h =
8
let m =
9
let s =
6
let dataStr =
String(format:
"d:d:d", h, m, s)
print(dataStr)
}
func demo() {
let
array = [
"张三",
"李四",
"小杨"]
print(
array)
}
func demo() {
let
array = [
"张三",
"李四",
"小杨"]
for i in
0..<
array.count {
print(
array[i])
}
for s in
array {
print(s)
}
for e in
array.enumerated() {
print(e)
print(
"\(e.offset) \(e.element)")
}
for (n, s) in
array.enumerated() {
print(
"\(n) \(s)")
}
for s in
array.reversed() {
print(s)
}
for (n, s) in
array.enumerated().reversed() {
print(
"\(n) \(s)")
}
}
func demo() {
var array = [
"张三",
"李四",
"小杨"]
array.append(
"老王")
print(
array)
array[
0] =
"小张三"
print(
array)
array[
5] =
"xxx"
array.remove(at:
3)
array.removeAll(keepingCapacity:
try)
}
func demo() {
var array = [
"张三",
"李四",
"小杨"]
var array2 = [
"王五",
"小宋"]
array += array2
print(
array)
}
func demo2() {
var array1: [NSObject] = [
"张三",
"李四",
"小杨"]
var array2 = [
"10",
"20",
100]
array += array2
print(
array)
}
//字典
func demo() {
// [KEY: VALUE] -> [String : NSObject]
let dict = [
"name":
"张",
"age":
18]
print(dict)
let array:
[[String: AnyObject]] = [
[
"name":
"张",
"age":
18],
[
"name":
"李",
"age":
20]
]
}
func demo() {
let dict = [
"name":
"张",
"age":
18]
dict[
"title"] =
"大哥"
dict[
"name"] =
"大西瓜"
dict.removeValue(forKey:
"age")
print(dict)
}
//字典遍历
func demo() {
let dict = [
"name":
"张",
"age":
18,
"title":
"老板"]
for e
in dict {
print(
"\(e.key) \(e.value)")
}
for (k, v)
in dict {
print(
"\(k) \(v)")
}
}
func demo() {
let dict1 = [
"name":
"张",
"age":
18,
"title":
"老板"]
let dict2 = [
"name":
"李",
"age":
18,
"title":
"员工"]
for e
in dict2 {
dict1[e.key] = dict2[e.key]
}
}