iOS分享世界MG的Swift空间iOS Developer

Swift_Apprentice_v2.0语法上

2017-07-03  本文已影响81人  Mg明明就是你
76EC2ADC-AA6C-43AD-9A57-2C08844F059C.png


说明是以2进制进行移动,9<<1=92=18,6<<2=62=24,9>>1=9/2=4(取整)
sin(45 * Double.pi / 180)
// 0.7071067811865475
cos(135 * Double.pi / 180)
// -0.7071067811865475
 sqrt(2.0)              //根号
// 1.414213562373095
max(5, 10)             // 两者中取最大值
// 10
min(-5, -10)           // 两者中取最小值
// -10
 max(sqrt(2.0), Double.pi / 2)
// 1.570796326794897

如果一个字符串0的个数太多你很难数出写了几个0的话,你可以这样


5A7DBBB1-1734-4B99-9127-D093FD231018.png
  • Tuples元组

tuple是表示由任何类型的多个值组成的数据的类型。您可以在tuple中拥有任意多的值。
例如,您可以定义一对2D坐标,其中每个轴值都是一个整数,如下所描述的:


var namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]
namesAndScores.isEmpty  //  false
namesAndScores.count    //  4
Array(namesAndScores.keys) // ["Craig", "Anna", "Donna","Brian"]
Array(namesAndScores.values)   // [8, 2, 6, 2]
// 根据key更新值
namesAndScores.updateValue(6, forKey: "Brian") // 
print(namesAndScores["Brian"]) // 6
// There’s even a shorter way to add pairs, using subscripting: 添加键值对
bobData["city"] = "San Francisco"
// Removing pairs:移除键值对
namesAndScores.removeValue(forKey: "Anna")
// 该方法将从字典中删除键状态及其关联值。
// 如您所料,使用下标更短的方法来实现这一点:
namesAndScores["Donna"] = nil
var namesAndScores = ["Anna": 2, "Brian": 2, "Craig": 8, "Donna": 6]
for (player, score) in namesAndScores {
      print("\(player) - \(score)")
}
// > Craig - 8
// > Anna - 2
// > Donna - 6
// > Brian - 2
for player in namesAndScores.keys {
  print("\(player)") 
}
// > Craig, Anna, Donna, Brian
  • Bool:TRUE AND FALSE

let a = 5
let b = 10
let min: Int
if a < b { min = a } else {   min = b }
let max: Int
if a > b { max = a } else {max = b }
let a = 5
let b = 10
let min = a < b ? a : b
let max = a > b ? a : b
while <CONDITION> {
        <LOOP CODE>
 }
var sum = 1
while sum < 1000 {
        sum = sum + (sum + 1)  // 1023
}

解释:

• Afteriteration2:sum=7,loopcondition=true•
• Afteriteration3:sum=15,loopcondition=true • •Afteriteration4:sum=31,loopcondition=true • •Afteriteration5:sum=63,loopcondition=true • •Afteriteration6:sum=127,loopcondition=true•
• Afteriteration7:sum=255,loopcondition=true•
• Afteriteration8:sum=511,loopcondition=true•
• Afteriteration9:sum=1023,loopcondition=false•
repeat {
        <LOOP CODE>
} while <CONDITION>
var sum = 1
repeat {
        sum = sum + (sum + 1)  // 1023
} while sum < 1000
var sum = 1
while true {
      sum = sum + (sum + 1)
      if sum >= 1000 {
          break  // 当sum >= 1000调出循环
      } 
}
for <CONSTANT> in <RANGE> {
      <LOOP CODE> 
}
var sum = 0
for row in 0..<8 {
          if row % 2 == 0 {
            continue
        }
        for column in 0..<8 {
            sum += row * column
        }
}
var sum = 0
rowLoop: for row in 0..<8 {  // 给行循环起一个名字rowLoop
        columnLoop: for column in 0..<8 {  // 给列循环起一个名字columnLoop
            if row == column {  // 如果行数等于列数
              continue rowLoop // 不执行此次行的循环
            }
            sum += row * column
         }
}
for index in stride(from: 10, to: 22, by: 4) {
          print(index)
}
// prints 10, 14, 18
for index in stride(from: 10, through: 22, by: 4) {
          print(index)
}
// prints 10, 14, 18, and 22
let number = 10
switch number {
      case 0:
        print("Zero")
      default:
        print("Non-zero")
}
let hourOfDay = 12
let timeOfDay: String
switch hourOfDay {
        case 0, 1, 2, 3, 4, 5:
           timeOfDay = "Early morning"
        case 6, 7, 8, 9, 10, 11:
           timeOfDay = "Morning"
        case 12, 13, 14, 15, 16:
          timeOfDay = "Afternoon"
        case 17, 18, 19:
          timeOfDay = "Evening"
        case 20, 21, 22, 23:
          timeOfDay = "Late evening"
        default:
          timeOfDay = "INVALID HOUR!"
}
// 优化写法
switch hourOfDay {
        case 0...5:
           timeOfDay = "Early morning"
        case 6...11:
           timeOfDay = "Morning"
        case 12...16:
           timeOfDay = "Afternoon"
        case 17...19:
           timeOfDay = "Evening"
        case 20..<24:
           timeOfDay = "Late evening"
        default:
           timeOfDay = "INVALID HOUR!"
}
let coordinates = (x: 3, y: 2, z: 5)
switch coordinates {
       case (0, 0, 0): // 1
           print("Origin")
       case (_, 0, 0): // 2
           print("On the x-axis.")
       case (0, _, 0): // 3
           print("On the y-axis.")
       case (0, 0, _): // 4
           print("On the z-axis.")
       default:        // 5
           print("Somewhere in space")
}
// 更进一步
let coordinates1 = (x: 3, y: 6, z: 4)
switch coordinates1 {
       case (0, 0, 0):
          print("Origin")
       case (let x, 0, 0):
          print("On the x-axis at x = \(x)")
       case (0, let y, 0):
          print("On the y-axis at y = \(y)")
       case (0, 0, let z):
          print("On the z-axis at z = \(z)")
       case let (x, y, z):
          print("Somewhere in space at x = \(x), y = \(y), z = \(z)")
}
// Somewhere in space at x = 3, y = 6, z = 4
// let coordinates1 = (x: 3, y: 0, z: 0)  On the x-axis at x = 3
// let coordinates1 = (x: 0, y: 6, z: 0)  On the y-axis at y = 6
// let coordinates1 = (x: 0, y: 0, z: 4)  On the z-axis at z = 4
  • Function parameters(带参函数)

func printMultipleOf(multiplier: Int, andValue: Int) {
          print("\(multiplier) * \(andValue) = \(multiplier * andValue)")
}
printMultipleOf(multiplier: 4, andValue: 2) // 4 * 2 = 8
func printMultipleOf(_ multiplier: Int, _ value: Int = 1) {
          print("\(multiplier) * \(value) = \(multiplier * value)")
}
printMultipleOf(4)// 4 * 1 = 4
func multiply(_ number: Int, by multiplier: Int) -> Int {
          return number * multiplier
}
let result = multiply(4, by: 2) // 8
// 错误示范
 func incrementAndPrint(_ value: Int) {
            value += 1
            print(value)
}
var value = 5
incrementAndPrint(value)  // 报错了,如下
This results in an error:
Left side of mutating operator isn't mutable: 'value' is a 'let' constant
func incrementAndPrint(_ value: inout Int) {
            value += 1
            print(value)
}
var value = 5
incrementAndPrint(&value)
print(value)  // 6
func printMultipleOf(multiplier: Int, andValue: Int){}
func printMultipleOf(multiplier: Int, and value: Int){}
func printMultipleOf(_ multiplier: Int, and value: Int){}
func printMultipleOf(_ multiplier: Int, _ value: Int){}
func getValue() -> Int {
          return 31; 
}
func getValue() -> String {
          return "Matt Galloway"
}
let value = getValue()
// 报错
error: ambiguous use of 'getValue()'
// 需明确类型
let valueInt: Int = getValue() // 31
let valueString: String = getValue() // "Matt Galloway"
func add(_ a: Int, _ b: Int) -> Int {
          return a + b 
}
var function = add
function(4, 2) // 6
func subtract(_ a: Int, _ b: Int) -> Int {
          return a - b 
}
function = subtract
function(4, 2) // 2
func printResult(_ function: (Int, Int) -> Int, _ a: Int, _ b: Int) {
          let result = function(a, b)  // 6
          print(result)
}
printResult(add, 4, 2) // 6


  • 轻轻点击,关注我简书

轻轻点击,关注我简书

轻轻点击,关注我微博

浏览我的GitHub


  • 扫一扫,关注我

扫一扫,关注我.jpg
上一篇下一篇

猜你喜欢

热点阅读