您的位置:首页 > 移动开发 > Swift

swift 3官方文档(读后感)

2016-07-05 17:06 489 查看
//:1. The sign of b is ignored for negative values of b. This means that a % b and a % -b always give the same answer.

let a = -9

let b = 4

let c = a % b

let d: Int? = 9

//:2. The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise.

//: The e get the value from d, e equals to 9

let e = (d != nil ? d! : b)

print(e)

//:3. 总结 ??运算符

let defaultColorName = “red”

// defaults to nil

var userDefinedColorName: String?

// defaults to “bule”

var myColor: String? = “blue”

// userDefinedColorName is nil, so colorNameToUse is set to the default of “red”

// myColor is “blue”, so colorNameToUse is set to the default of “blue”

var colorNameToUse = userDefinedColorName ?? defaultColorName

var useMyColor = myColor ?? defaultColorName

//4.The function in String type

let greeting = “Guten Tag!”

//: 注意:字符串的subscript type 不能用int ,只能用Index

//greeting[0],会报错

//startIndex == G

greeting[greeting.startIndex]

//endIndex != “!”, after “!”

greeting[greeting.index(before: greeting.endIndex)]

// !

greeting[greeting.index(after: greeting.startIndex)]

// u

//这个方法是向后移动7个字符

let index = greeting.index(greeting.startIndex, offsetBy: 7)

//打印的字符是:a

greeting[index]

//下面两种取值方法是错误的

//greeting[greeting.endIndex] // error

//greeting.index(after: endIndex) // error

//可以通过使用character的indices属性获得字符串的每一个字符

for index in greeting.characters.indices {

print(“(greeting[index]) “, terminator: “”)

}

// Prints “G u t e n T a g ! “

//5.字符串的insert方法可以在字符串中插入字符或者字符串

var welcome = “hello”

welcome.insert(“!”, at: welcome.endIndex)

// welcome now equals “hello!”

welcome.insert(contentsOf:” there”.characters, at: welcome.index(before: welcome.endIndex))

// welcome now equals “hello there!”

//6.字符串的remove方法可以在字符串中删除字符或者字符串

welcome.remove(at: welcome.index(before: welcome.endIndex))

// welcome now equals “hello there”

let range = welcome.index(welcome.endIndex, offsetBy: -6)..
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: