Swift的一些基础内容

时间:2023-03-09 00:37:14
Swift的一些基础内容

//①判断字符串是否为空的方法 isEmpty

var str:String = "www.baidu.com"

if str.isEmpty {

print("空字符串")

}else

{

print("str的值是:\(str)")

}

//② 计算字符串的长度

str.characters.count

//③ 查询字符串是否以str字符串为开头或者结尾

if str.hasPrefix("www.") {

print("嘿嘿")   //说明if else if 只要满足了if 后面就不会执行了

}else if str.hasSuffix(".com"){

print("呵呵")

}

//④ 字符串全部大写 全部小写 首字母大写方法

var uppercase = str.uppercaseString

var lowercase = uppercase.lowercaseString

var capitalized = lowercase.capitalizedString  //首字母大写

//⑤ 元祖

let myProject = (one:"wocao",two:1234)

print(myProject.two)

// ⑥ swift随机数

var temp:Int = Int(arc4random()%100) + 1

var  temp1:Int = Int(arc4random_uniform(100)) + 1

// ⑦  闭与开

for iCount in 0...5{

print(iCount)

}

var fruits = ["apple","orange","banana"]

let iC = fruits.count

for i in 0..<iC{

print("第\(i+1)个水果是\(fruits[i])")

}

// ⑧ 截取字符串

let index = str.startIndex.advancedBy(4)

let index2 = str.startIndex.advancedBy(6)

//let range1 = Range<String.Index>(start: index, end: index2)

let range1 = Range(start: index, end: index2)

let rangeStr = str.substringWithRange(range1)

let range2 = str.startIndex.advancedBy(4)..<str.startIndex.advancedBy(6)

let range2Str = str.substringWithRange(range2)

// ⑨ 检查字符数里是否都是合法的(如全部都是小写)

let index = str.startIndex.advancedBy(4)

let index2 = str.startIndex.advancedBy(6)

//let range1 = Range<String.Index>(start: index, end: index2)

let range1 = Range(start: index, end: index2)

let rangeStr = str.substringWithRange(range1)

let range2 = str.startIndex.advancedBy(4)..<str.startIndex.advancedBy(6)

let range2Str = str.substringWithRange(range2)