Swift基础语法汇总

前端之家收集整理的这篇文章主要介绍了Swift基础语法汇总前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

// Playground - noun: a place where people can play

import UIKit

var str = "Hello,playground"

var (a,b) = (10,29)
let (c:String,d:Int) = ("10",19)

println(a + b)

a = 1;

var array = [1,2,3,4];
println(array[2]);

var dict: [String: Int] = [
    "a": 1,"b": 2,"c": 3,"d": 4,"e": 5
];
dict["c"]

//可变类型
var dict11 = [
    "a": 1,"b": "2"
]

dict11["a"]
dict11["b"]


var intList: [Int] = []

var dict1 =
[
    "a": 0,"b": 1,"c": 2
];

dict1["a"]
//println("\(dict1["a"])");



//特殊的组合
let lang2: (String,Int,Int) = ("Swift",1);
lang2.0
lang2.1
lang2.2


//可以为特殊组合定义名称
let lang1: (name:String,age:Int) = (name:"a",age:0);
lang1.name


let length = -6

if(length > 0){
    println(1);
}else if(length > 1){
    println(2);
}else if length < 1 {
    println(-1);
}

for i in array{
    println(i)
}

//Null型??
var strValue: String?

println(strValue)

var strValueOptional: Optional<Int>

if strValue != nil {
    println(0)
}else{
    println(1)
}

var myVar = 0;

println(" (myVar) ");



println("Hello,World!")

var array1 = [1,4,5]

for i in array1{
    println(i)
}


var myVar1 = 0;

println("my var is myVar)" + String(myVar1));

println("my var is ¥(myVar)");

var my : Int = 0;

println(my);

var myVar3 : Double = 3.21123123

println(myVar3);


var movieCount = 0
var songCount = 0


println("Media library contains \(movieCount) movies and \(songCount) songs");


println("国")



//基本控制语句
var score = 50;

var scoreArray = [90,100,23,43,67];

for s in scoreArray {
    println("s is \(s)");
}

var maxscore = 0;
var minscore = 0;
var avgscore = 0.0;
var sumscore = 0.0;

var count = scoreArray.count;

for s in scoreArray{
    sumscore += Double(s);
}

println("sumscore is \(sumscore)");

for (var i = 0; i < count; i++){
    println(scoreArray[i]);
}

var index = 0;
while(index < count){
    var s = scoreArray[index];
    index++;
    println(" while is [\(s)]");
}

let type = "IOS"

//Swift不是穿透型,[fallthrough]可以设定穿透
switch type {
case "IOS":
    println("");
case "IOS1":
    println("");
    fallthrough
default:
    break;
}


///方法的使用
func testConcat(v1:String,v2:String) -> String {
    return "\(v1) and \(v2)";
}

func testConcat2(v1:String,p2 v2:String,p3 v3:String) -> String {
    return "\(v1) and \(v2) and \(v3)";
}

func getInfo() -> (String,String,String){
    return ("syu","gen","syou")
}

func testFunctionInFunction() -> Int {
    
    //基本上和JS是一致的
    var y = 10;
    
    func add(){
        y += 5;
    }
    
    add();
    
    return y;
}

func Function() -> String {
    return "OK!";
}

func addFuc(num : Int) -> Int {
    return num ;
}


func Function(v1 : Int) -> (Int -> String) {
    func addFuc(num : Int) -> String {
        var a = num + 1;
        return "result is \(a)";
    }
    return addFuc;
}


func lessThanTen(number: Int) -> Bool {
    return number < 10;
}

func hasAnyMatch(list: [Int],condition: (Int -> Bool)) -> Bool {
    for item in list {
        if condition(item) {
            return true;
        }
        continue;
    }
    
    return false;
}

func testFuction(){
    println("My First Fuc");
    
    let v = testConcat("hello","world");
    println("v is \(v)");
    
    let v2 = testConcat2("syu",p2: "gen",p3: "syou");
    println("v2 is \(v2)");
    
    let (v3,v4,v5) = getInfo();
    println("\(v4)");
    
    
    let v6 = testFunctionInFunction();
    println("\(v6)");
    
    //方法指针
    var myFunc = Function(1);
    let v7 = myFunc(1);
    println("\(v7)");
    
    var arr = [10,20,30,5];
    let v8 = hasAnyMatch(arr,lessThanTen);
    println("\(v8)");
}

testFuction();


//数据结构

var p1 = 100;
let p2 = "value is " + String(p1);
println("p2 is \(p2)");

var p3 = ["IOS","Android","winPhone","Symbian"];

p3[0] = "IOS/Swift";

for i in p3 {
    println("new i is \(i)");
}

p3.append("BlackBerray");



// 字典型的使用
var p4 : Dictionary = [
    "Name": "zyx","Age": 35,"score": "100"
]

for(key,value) in p4{
    println("key value \(key) and \(value)");
}

p4["Course"] = "100";

for(key,value) in p4{
    println("key value \(key) and \(value)");
}

let p5 = p4.keys;

for key in p5{
    println("key is \(key)");
}


//Closure 闭包= 类似于Net的拉姆达表达式 简化代码写法
var arr = [20,9,34,89,39];

func hasClosureMatch(arr: [Int],compareValue: Int,cb:(num: Int,value: Int) -> Bool) -> Bool{
    for item in arr {
        if (cb(num: item,value: compareValue)) {
            return true;
        }
        
    }
    return false;
}

var v1 = hasClosureMatch(arr,400,{
    (num: Int,value: Int) -> Bool in
    return num >= 400;
});

println("v1 is \(v1)");


var v3 = hasClosureMatch(arr,5,{
    //sh Coding经常食用方法
    return $0 < $1
});

println("v3 is \(v3)");


let v4  = hasClosureMatch(arr,{
    return $1 == 9
});

println("v4 is \(v4)");

//闭包函数特性整理
array = [20,39]

func canMatch(arr: [Int],cb: (num: Int,value: Int) -> Bool) -> Bool {
    
    for item in arr {
        if (cb(num: item,value: compareValue)) {
            return true
        }
    }
    
    return false
}

//Fn1
var compareFn1 = {
    (num: Int,value: Int) -> Bool in
    return num == value;
}

var val1 = canMatch(array,compareFn1);

println("\(val1)")

//Fn2
var val2 = canMatch(array,{ return $0 == $1 });

println("\(val2)")


//构造体
struct QFTest {
    var x = 0;
    var y = 0;
    
    //构造函数固定名称
    init(){
        NSLog("init called");
    }
    
    init(x:Int,y:Int){
        self.x = x;
        self.y = y;
        
        NSLog("init with params is called");
    }
    
    //特殊语法,如果再调用构造函数的时候想使用一般语法的参数传递「QFTest(100,200)」 ,必须自己重写下面的代码
    init(_ x: Int,_ y: Int){
        self.x = 0;
        self.y = 0;
    }
    
    //结构体没有析构函数
    
    //可以定义函数
    mutating func add(v1: Int,v2: Int){
        //结构体是一个对象的拷贝,其成员变量的值在定义的时候初始化
        //默认在构造体内是不能改变成员变量的,如果想改变需要在函数加上mutating
        
        x += v1;
        y += v2;
    }
    
}

struct dog {
    var age = 0;
}

func testStructure() {
    
    //构造体初期化
    var s = QFTest(x:100,y:200);
    
    printlnForStructure(s);
    
    var s1 = QFTest();
    s1.x = 100;
    s1.y = 200;
    
    printlnForStructure(s1);
    
    
    var s2 = QFTest(100,200);
    printlnForStructure(s2);
    
    s2.add(300,v2:300);
    printlnForStructure(s2);
    
}

func printlnForStructure(p: QFTest){
    println("x: \(p.x) and y: \(p.y)");
}

testStructure();



//クラス
class Person {
    //Swift 变量类型
    var age :Int = 0;
    var name :String?;
    
    init() {
        self.age = 5;
        self.name = "x man";
    }
    
    init(name:String,age:Int){
        self.age = age;
        self.name = name;
    }
    
    //两种方法类型
    //1、成员方法:通过类的实例化对象调用
    func getAge() -> Int {
        return age;
    }
    
    func getName() -> String {
        //! => nil(Null)可以理解是一种装箱操作
        return name!;
    }
    
    //2、类方法、相当于静态方法
    class func  MaxAge() -> Int {
        return 200;
    }
    
    //3. 不经常使用,返回类型本身
    class func person() -> Person {
        return Person();
    }
    
    //析構函数
    deinit {
        
    }
}

var xiaoming = Person();

println("xiaoming is \(xiaoming.age)");


var maxAge = Person.MaxAge();
println("Max age is \(maxAge)");


//参数标签的区别:
//一般情况下方法的第一个参数的标签,在调用的时候是不需要明确写出来的.但是如果参数带有#符号则必须写
//构造函数的参数标签是必须写的
var xiaoli = Person(name: "王さん",age: 32);

//Setter Getter

struct  Point {
    var x = 0.0,y = 0.0;
};

struct Size {
    var width = 0.0,height = 0.0;
}

struct  Rect {
    //在定义类和构造体的时候可以想下面这行这样用一种懒加载的方式定义变量,可以使变量只有在被使用的时候才加载
    //@lazy var aysnObj = Point();
    
    var origin = Point();
    
    var size = Size();
    
    //Center相当于C#的属性成员
    var center : Point {
        get {
            let x = origin.x + (size.width / 2);
            let y = origin.y + (size.height / 2);
            return Point(x :x,y :y);
        }
        
        set(newCenter) {
            origin.x = newCenter.x - size.width/2;
            origin.y = newCenter.y - size.height/2;
            
        }
    }
    
    
    func getCenter() -> (Double,Double) {
        let x = origin.x + (size.width / 2);
        let y = origin.y + (size.height / 2);
        
        return (x,y);
    }
}

var rect = Rect(origin :Point(x:100,y:200),size :Size(width: 400,height: 50));

var (x,y) = rect.getCenter();

println("x y =(\(x),\(y) )")

var p11 :Point = rect.center;

println("x y =(\(p11.x),\(p11.y) )")

var p13 = Point(x:200,y:400);
rect.center = p13;
println("x y =(\(p13.x),\(p13.y) )")

var rect1 = Rect(origin: Point(x:200,y:500),size: Size(width: 300,height: 100));

class Human {
    
    var x = 0
    var y = 0
    var w = 0
    var h = 0
    
    init() {
        
    }
    
    init(x: Int,y: Int,w: Int,h: Int){
        self.x = x
        self.y = y
        self.w = w
        self.h = h
    }
    
    var position: (x: Int,y: Int){
        
        //返回值必须和「(x: Int,y: Int)」属性定义一致
        get {
            return (x,y)
        }
        
        //set的参数也必须和 「(x: Int,y: Int)」属性定义一致
        set(pos) {
            self.x = pos.x
            self.y = pos.y
        }
    }
    
    class func Summay() -> String {
        return "human"
    }
}

var person = Human()
person.position
person.position = (9,9)
Human.Summay()


/* 属性的各种情况 */
class HumanNew {
    
    var fristName: String = ""
    
    var milldeName: String?
    
    var lastName: String = ""
    
    //属性的参数列表带nil值的情况
    var Name: (frist: String,millde: String?,last: String) {
        
        get {
            return (fristName,milldeName,lastName)
        }
        
        set(fullName) {
            self.fristName = fullName.frist
            self.milldeName = fullName.millde
            self.lastName = fullName.last
        }
        
    }
    
    func toString() -> String {
        return lastName + " " + (milldeName ?? "XX") + fristName
    }
    
    //nil属性
    var _company = ""
    //只有一个属性的时候
    var company: (String?) {
        get {
            return _company + "株式会社"
        }
        
        set (companyName) {
            self._company = companyName!
        }
    }
}


var xiaowang = HumanNew()
xiaowang.Name = ("xiao",nil,"wang")
println(xiaowang.toString())


//Interface
//多継承可能
@objc protocol SortProtocol : NSObjectProtocol {
    
    //必须实现的方法
    func compare (value:Int) -> Bool;
    
    
    //如果有用了optional的方法,则Class的前面必须追加@objc。这个方法是可选的。可以不实现
    optional func beginCompare() -> Bool;
    
}

protocol SortProtocol1 : NSObjectProtocol {
    
    func findMaxValue (v1:Int,v2:Int) -> Bool;
    
    
}

class ClassA : NSObject,SortProtocol,SortProtocol1 {
    var age = 0;
    init(age:Int) {
        self.age = age;
    }
    
    func compare(value: Int) -> Bool {
        return true;
    }
    
    func findMaxValue(v1: Int,v2: Int) -> Bool {
        if(v1 > v2){
            return true;
        }else{
            return false;
        }
    }
    
}

let classA = ClassA(age:100);

let ret = classA.compare(200);

let result = classA.findMaxValue(200,v2: 300);

println(result);
//強制类型转换
let newClassA = classA as SortProtocol1;

println(newClassA.findMaxValue(500,v2: 300));

let newClassB = classA as SortProtocol;

//这是在调用一个没有被实现的的方法。该方法没有被实现的时候,可以返回nil
println(newClassB.beginCompare?());


//可简化的循环写法
for i in 1...11 {
    println(i)
}

func add(heigth: Int,#width: Int) -> Int {
    return heigth + width
}

add(100,width: 200)



let number = 10
switch number {
    case 2,6,7,10:
        println("2")
        //可穿透
        fallthrough
    case 10:
        println("10")
    case 1,7:
        println("3")
    default:
        println()
}





猜你在找的Swift相关文章