Swift 4.0 学习笔记整理

2018-01-16  本文已影响8人  自律者得自由

整理自己学习Swift4.0笔记
一、基础
1、字符串
2、数组

字符串

import UIKit

var str = "Hello, playground"
//字符个数
let count = str.count    //17
//字符串是否为空
str.isEmpty                  //false
//去掉最后一个字符
str.dropLast()             //"Hello, playgroun"
//去掉第一个字符
str.dropFirst()            //"ello, playground"
//去掉最后三个字符
str.dropLast(3)         // "Hello, playgro"
//倒序
String(str.reversed()) //"dnuorgyalp ,olleH"

//全部大写
str.localizedUppercase  //"HELLO, PLAYGROUND"
//全部小写
str.localizedLowercase  //"hello, playground"
//str.insert(contentsOf: "Collection", at: index1!)
//遍历
var lcounts = 0
for c in str {
    if c == "l" {
        lcounts+=1
    }
}
print(lcounts)  //"3\n"


//获取子字符串
let name = "Marie Curie"
name.count  //11
let firstSpace = name.index(of: " ") ?? name.endIndex
let firstName = name[..<firstSpace]
print(firstName)   //"Marie\n"


var index = str.startIndex
var index1 = str.index(of: "u")
let range = str.index(index, offsetBy: 5)
str.suffix(from: index1!)  //"und"
str.prefix(upTo: index1!) //"Hello, playgro"

//增
str.append("123")  //"Hello, playground123"

//删
let range2 = str.startIndex...str.index(str.endIndex, offsetBy: -4)
str.removeSubrange(range2)  //"123"
//改
str.insert(contentsOf: "Collection", at: str.endIndex) //"123Collection"
str.replaceSubrange(name.startIndex...name.endIndex ,with: " ")//" n"

swift中字符串下标已经不是我们熟悉的int类型了,现在使用了String.Index类型,至于更换类型的原因推荐参考这篇文章:http://swift.gg/2016/01/25/friday-qa-2015-11-06-why-is-swifts-string-api-so-hard/

数组

import UIKit

var someArray = ["1","2","3","4","5","6","7","8","9","10","11","12"]
var someArray1 = ["4","5","6"]
someArray.count     //12
someArray1[1]         //"5"
//倒序
someArray.reverse() //["12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1"]
// 是否为空
someArray.isEmpty //false



//增
someArray.append("4")//拼接字符串 ["12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1", "4"]
someArray+someArray1//拼接数组 ["12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1", "4", "4", "5", "6"]

//删
someArray.remove(at: 3) // ["12", "11", "10",  "8", "7", "6", "5", "4", "3", "2", "1", "4"]
someArray.removeLast() // ["12", "11", "10", "8", "7", "6", "5", "4", "3", "2", "1"]
someArray.removeFirst() // ["11", "10", "8", "7", "6", "5", "4", "3", "2", "1"]
someArray.removeSubrange(0...1)  // ["8", "7", "6", "5", "4", "3", "2", "1"]
someArray.removeAll()  //[]

//改
//替换单个
someArray1[0]="7"  //["7", "5", "6"]
//替换连续的几个
someArray1 .replaceSubrange(0...1, with: ["10","11"]) //["10", "11", "6"]

//遍历
for c in someArray1{
    print(c)
}


//排序
var SM = [0,5,3,1,2,4,111,165,888,]
//SM.sort()
SM.sort { (x, y) -> Bool in
    return x>y    //如果x>y那最终结果就是降序的,如果x<y最终结果是升序的,x,y可以任意更改
}

上一篇下一篇

猜你喜欢

热点阅读