Swift基础语法(二)

来源:互联网 时间:1970-01-01

操作符

swift中运算符基本基础于c,下面我就给大家白话白话那些被优化过的运算符们

//加号减号的妙用

var a=1

var b= -a//此时b=-1

var c = +b//此时 c=-1

var d= - c//此时 d=1

操作符

//操作符(数字...数字1)表示从数字到数字1之间的数其中包括数字和数字1

for var i in 1...5{

printlin("数字:\(i)进化后:\(i*6)")

}

/*输出

数字:1进化后:6

数字:2进化后:12

数字:3进化后:18

数字:4进化后:24

数字:5进化后:30

*/

字符串

swift里面用到的字符串默认都是utf-16字符编码,无论是标识符还是自定义字符串

字符串拼接用加号(+)

字符串遍历用for...in

//字符串拼接

var a="Hello"

var b="world"

var c=" "

println(a+c+b)//输出Hello World

println(a+b)//输出HelloWorld

//字符串遍历

for i in a{

print("\(i) ")//输出:H e l l o

}

//获取字符串长度countElements

print(countElements(a))//5

//字符串赋值

“let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"

// "Imagination is more important than knowledge" - Einstein

let dollarSign = "\x24" // $, Unicode scalar U+0024

let blackHeart = "\u2665" // ♥, Unicode scalar U+2665

let sparklingHeart = "\U0001F496" // 💖, Unicode scalar U+1F496”

var check1:String = "Swift is good!"

var check2:String = "Swift is good!"

//字符串是否相等

if check1 == check2 {

println("check1 = check2")

} else {

println("check1 != check2")

}

//是否包含前缀

var preCheck = "Swift"

if check1.hasPrefix(preCheck) {

println("包含前缀")

}

//是否包含后缀

var sufCheck = "good!"

if check1.hasSuffix(sufCheck) {

println("包含后缀")

}

//大小写转换

let myString = "Wait a moment, please."

let newString = myString.uppercaseString

// "WAIT A MOMENT, PLEASE."

let myString = "Wait a moment, please."

let newString = myString.lowercaseString

// "wait a moment, please."

//是否包含字符串

var myString = "This is a string test"

if myString.rangeOfString("string") {

println("exists")

}

//截取字符串

/截取字符串的标识位从1开始计数

let myString = "ABCDEFGHI"

//1.从目标标识位后一个字符开始截取余下的字符串

let mySubstring = (myString.substringFromIndex(2))

println(mySubstring) // "CDEFGHI"

//2.从第一个字符截取到目标标识位

let mySubstring2 = (myString.substringToIndex(4))

println(mySubstring2) // "ABCD"

//分割字符串

//单一分隔符:只有一种分割符

var myString = "Berlin, Paris, New York, San Francisco"

//1.隐式定义字符串数组

var myArray = myString.componentsSeparatedByString(",")

//2.显示定义字符串数组

var myArray2 : String[] = myString.componentsSeparatedByString(", ")

for em in myArray2 {

print(em) //Berlin Paris New York San

}

//多重分割符:有2个或两个以上分隔符

var myString2 = "One-Two-Three-1 2 3"

var array2:String[] = myString2.componentsSeparatedByCharactersInSet(NSCharacterSet (charactersInString: "- "))

//["One", "Two", "Three", "1", "2", "3"]

//字符串去空格

var newString = myString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

//字符串转NSData

let string: NSString = myString

let data = string.dataUsingEncoding(NSUTF8StringEncoding)

字符串转编码

let dogString = "Dog!🐶"

for codeUnit in dogString.utf8 {

print("\(codeUnit) ")

}

print("\n")

// 68 111 103 33 240 159 144 182

for codeUnit in dogString.utf16 {

print("\(codeUnit) ")

}

print("\n")

// 68 111 103 33 55357 56374”

 

明天Array dictionary


相关阅读:
Top