码迷,mamicode.com
首页 > 其他好文 > 详细

Swift语法快速索引

时间:2014-07-17 22:03:11      阅读:471      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   使用   

在WWDC的演示中就可以看出来Swift这个更接近于脚本的语言可以用更少的代码量完成和OC同样的功能。但是对于像我一样在战争中学习战争的同学们来说,天天抱着笨Swift Programming Language Reference之类的大部头看不实际。毕竟还是要养家糊口的。而且,那么1000+页内容讲的东西不是什么都要全部在平时工作中用到的。咱们就把平时用到的全部都放在一起,忘记了立马翻开看看,不知不觉的就学会了之后变成习惯。这样多省事。

变量

1 // Variable
2 var int_variable = 1    // 类型推断
3 var message : String
4 var x = 0.0, y = 0.0, z = 0.0

 

常量

// Constant
let const_int = 1
//const_int = 10  ERROR: can not assign to let value

 

字符串

// String
// 1. 定义
var empty_string = ""
var another_empty_string = String()
// 2. 拼接
var hello_string = "hello"
var world_string = " world"
hello_string += world_string    // hello world
 
let multiplier = 3
//let multiplier_message = "\(mulitplier) times 2.5 is \(Double(multiplier) * 2.5)"

// 3. 比较
var hello_world_string = "hello world"

hello_string == hello_world_string  // all are "hello world", result is true

if hello_string == hello_world_string {
    println("These two are equal")
}

 

Tuple

 

// Tuple
// 1. Unnamed tuple
let http_not_found = (404, "Not Found")
println("tuple item 1 \(http_not_found.0), tuple item 2 \(http_not_found.1)")
// 2. Named tuple
let (statusCode, statusMessage) = (404, "Not Found")
statusCode      // 404
statusMessage   // "Not Found"

let http_not_found2 = (statusCode:404, statusMessage:"Not Found")
http_not_found2.statusCode      // 404
http_not_found2.statusMessage   // "Not Found"
// 3. return tuple
func getHttpStatus() -> (statusCode : Int, statusMessage : String){
    // request http
    return (404, "Not Found")
}

 

 

数组

 

// Array

// 1. 定义
//var empty_array = []  // 在swift里没事不要这样定义数组。这是NSArray类型的,一般是Array<T>类型的
var empty_array : [Int]
var empty_array2 = [Int]()
var fire_works = [String]()
var colors = ["red", "yellow"]
var fires : [String] = ["small fire", "big fire"]; // Xcode6 beta3里数组的类型是放在方括号里的

var red = colors[0]

// 2. append & insert
colors.append("black")
colors += "blue"
colors += fires
colors.insert("no color", atIndex: 0)

// 3. update
colors[2] = "light blue"
//colors[5...9] = ["pink", "orange", "gray", "limon"]

// 4. remove
colors.removeAtIndex(5)
//colors[0] = nil ERROR!

// other
colors.isEmpty
colors.count

 

 

字典

 

 

// Dictionary
// 1. 定义
var airports : Dictionary<String, String> = ["TYP":"Tokyo", "DUB":"Boublin"]
var airports2 = ["TYP":"Tokyo", "DUB":"Boublin"]
var empty_dic = Dictionary<String, String>()
var empty_dic2 = [:]

// 2. update
airports.updateValue("Dublin International", forKey: "DUB")
airports["DUB"] = "Dublin International"

// 3. insert
airports["CHN"] = "China International"

// 4. check exists
if let airportName = airports["DUB"] {
    println("The name of the airport is \(airportName).")
}
else{
    println("That airport is not in the airports dictionary.")
}

// 5. iterate
for (airportCode, airportName) in airports{
    println("\(airportCode):\(airportName)")
}

// 6. remove
airports.removeValueForKey("TYP")
airports["DUB"] = nil

 

 

枚举

 

// Enum
// 1. defination & usage
enum PowerStatus: Int{
    case On = 1
    case Off = 2
}

enum PowerStatus2: Int{
    case On = 1, Off, Unknown
}

var status = PowerStatus.On

enum Barcode {
    case UPCA(Int, Int, Int)
    case QRCode(String)
}

var product_barcode = Barcode.UPCA(8, 8679_5449, 9)
product_barcode = .QRCode("ABCDEFGHIJKLMN")

switch product_barcode{
case .UPCA(let numberSystem, let identifier, let check):
    println("UPC-A with value of \(numberSystem), \(identifier), \(check)")
case .QRCode(let productCode):
    println("QR code with value of \(productCode)")
}

 

 

方法

 

 

// Function
// 1. 定义
func yourFuncName(){

}

// 2. 返回值
func yourFuncNameWithReturnType()->String{
    return ""
}

// 3. 参数
func funcWithParameter(parameter1:String, parameter2:String)->String{
    return parameter1 + parameter2
}

funcWithParameter("1", "2")

// 4. 外部参数名
func funcWithExternalParameter(externalParameter p1:String) -> String{
    return p1 + " " + p1
}

funcWithExternalParameter(externalParameter: "hello world")

func joinString(string s1: String, toString s2: String, withJoiner joiner: String)
    -> String {
        return s1 + joiner + s2
}

joinString(string: "hello", toString: "world", withJoiner: "&")

// 外部内部参数同名
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
    for character in string {
        if character == characterToFind {
            return true
        }
    }
    return false
}

containsCharacter(string: "aardvark", characterToFind: "v")

// 默认参数值
func joinStringWithDefaultValue(string s1: String, toString s2: String, withJoiner joiner: String = " ")
    -> String {
        return s1 + joiner + s2
}

joinStringWithDefaultValue(string: "hello", toString: "world") //joiner的值默认为“ ”

// inout参数
func swapTwoInts(inout a: Int, inout b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3

 

 

 

 

// Class
// 1. 定义
class NamedShape {
    var numberOfSides: Int = 0
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

// 2. 继承 & 函数重载 & 属性getter setter
class Square: NamedShape {
    var sideLength: Double
    
    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 4
    }
    
    func area() ->  Double {
        return sideLength * sideLength
    }
    
    // 函数重载
    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."
    }
}

class EquilateralTriangle: NamedShape {
    var sideLength: Double = 0.0
    
    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 3
    }
    
    // 属性的getter setter
    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
            sideLength = newValue / 3.0
        }
    }

    override func simpleDescription() -> String {
        return "An equilateral triagle with sides of length \(sideLength)."
    }
}

// 3. 使用
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength

 

 

其他稍后补充

Swift语法快速索引,布布扣,bubuko.com

Swift语法快速索引

标签:des   style   blog   http   color   使用   

原文地址:http://www.cnblogs.com/sunshine-anycall/p/3851717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!