• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

IOSSwift训练

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
// Playground - noun: a place where people can play

import Cocoa

var str = "Hello, playground"

str+=",Yes I'm Good";

println("hello swift")

var myvar=23

myvar=18
let myConstant=42
var a:Double=10

let label="this width is"
let width=94
let widthlabel=label+String(width)


"I have \(width) apples."
"I have \(String(width)+String(width)) apples"
var shoppingList=["C","B","D","E"]
shoppingList[0]="A"
shoppingList
var dict=["A":"yes","B":"no"]
dict["A"]
dict["C"]="Cancel"
dict
var emptyArray=String[]()
emptyArray.append("A")
emptyArray.append("C")
emptyArray

var emptyDict=Dictionary<String,Float>()
emptyDict.values
emptyDict=["A":1,"B":2,"C":4]

let individualSocres=[1,2,45,6,2,0]
var teamScore=0
for score in individualSocres{
    if(score>8){
        teamScore+=3
    }
    else{
        teamScore+=1
    }
}
teamScore
var optional:String?="Hello"
optional=nil
var t="H"
if optional==nil {
    t="hello \(optional)"
}else{
    t="XX"
}

let vegetable="1cecery"
switch vegetable{
    
//Case 用法
case let x where x.hasSuffix("cery"):
    let v="Is it a spicy \(x)"
    
    case "cecery":
        let v="add some";
    case "cecery","":
        let v="tttt"
    default:
        let v="tastes good"
}


let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest

var n=2
while n<100{
    n=n*2
}

var firstForLoop=0
for i in 0..10{
    firstForLoop+=i
}

//多返回值参数
func greet(name:String,day:String)->(String,Double){
    return ("hello \(name),today is \(day)",99.0)
}

greet("jack","2014-06-09")

//数组参数
func sumOf(numbers:Int...)->Int{
    var sum=0;
    for num in numbers{
        sum+=num
    }
    return sum
}

sumOf()
sumOf(19,0,3)

//嵌套函数
func returnFifteen()->Int{
    var y=10;
    func add(){
        y+=5;
    }
    //调用了才执行
    add()
    return y;
}

returnFifteen();

//函数可以作为另一个函数的返回值
func makIncrementer() -> (Int->Int){
    func addOne(number:Int)->Int{
        return 1+number;
    }
    return addOne;
}

var increment=makIncrementer();
increment(7)

func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, lessThanTen)

//类定义
class Animals{
    var name="";
    //构造函数
    init(name:String){
        self.name=name;
    }
    //方法
    func WhatsName()->String{
        return "my name is \(name)!";
    }
}
//注意构造函数的调用方式
var cat=Animals(name: "dog");
//cat.name="cat";
cat.WhatsName();

//类的继承
class Pig:Animals{
    var age:Int{
        //在设置之前可以执行某段代码,之后执行用didSet
        willSet{
            println("aaaa");
        }
    };
    
    //Getter And Setter
    var Age:Int{
        get{
            return age;
        }
        set{
            age=newValue;
        }
    }
    
    init(age:Int){
        self.age=age;
        super.init(name:"Pig");
    }
    
    func HowOld()->String{
        return "pig is \(age) years old";
    }
    //重写
    override func WhatsName()->String{
        return "pig is a clever animal!";
    }
    
}

let LittlePig=Pig(age:3);
LittlePig.HowOld();
LittlePig.WhatsName();
LittlePig.age;
LittlePig.age=4;
LittlePig.Age=8;



class Counter {
    var count: Int = 0
    //方法参数名,可以在为方法体内部使用单独定义一个别名,例如times
    func incrementBy(amount a: Int, numberOfTimes times: Int) {
        count += a * times
    }
}
var counter = Counter()
counter.incrementBy(amount:2, numberOfTimes: 7)

//?之前如果为nil,则之后的会被忽略,否则执行
var os:String;//?="hello jack";
var ai:String?="BBBBB"

//枚举
enum Rank: Int {
    case Ace = 1,Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,Jack, Queen, King
    func simpleDescription() -> String {
        switch self {
        case .Ace:
            return "ace"
        case .Jack:
            return "jack"
        case .Queen:
            return "queen"
        case .King:
            return "king"
        default:
            return String(self.toRaw())
        }
    }
}
let ace = Rank.Ace
let aceRawValue = ace.toRaw()
ace.simpleDescription();
//struct结构体,值类型,类为引用类型
enum ServerResponse {
    case Result(String, String)
    case Error(String)
}

let success = ServerResponse.Result("36:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")

switch success {
case let .Result(sunrise, sunset):
    let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
    let serverResponse = "Failure...  \(error)"
}

//接口和扩展
protocol IUser{
    var simpleDesc:String{get}
    mutating func addJust()
}

class SimpleClass:IUser{
    var simpleDesc:String="Very well";
    func addJust(){
        simpleDesc+=" Now implement";
    }
}

var test=SimpleClass();
test.addJust()
test.simpleDesc;

//接口是可以用来扩展类型的功能的
extension String: IUser {
    var simpleDesc: String {
        return "The number \(self)";
    }
    mutating func addJust() {
        self += "S";
    }
}
"OK".simpleDesc
let tx:IUser = test;
tx.simpleDesc

//范型
func repeat<T>(item: T, times: Int) -> T[] {
    var result = T[]()
    for i in 0..times {
        result += item
    }
    return result
}
repeat("knock", 4)

func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}

anyCommonElements([1, 2, 3], [4,5])

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
swift--静态变量static发布时间:2022-07-13
下一篇:
Swift---一门智能型的编程语言发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap