swift2.0 - study

前端之家收集整理的这篇文章主要介绍了swift2.0 - study前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

//

// main.swift

// mycmd

// Created by zhaoxuhui on 15/10/27.

// Copyright © 2015 zhaoxuhui. All rights reserved.

//


import Foundation


var str = "Hello,playground"

//swift初见

let shoppinglist = ["aaa","bbb"];

var shopdic = [1:"aaa",3:"ccc",2:"bbb"];

shopdic[1] = "aA";


for s in shopdic {

print(s);

}



var optionalstring:String? = "hello";

print(optionalstring == nil);

if let name = optionalstring{

print("optionalstring != nil")

}else{

print("optionalstring == nil")

}


let vetetable = "red paper"

var comment:String;

switch vetetable{

case "celery":

comment = "celery a";

case let x where x.hasPrefix("re"):

comment = "prefix re:\(x)";

case "red paper"://这行不会走了

comment = "red paper";

default:

comment = "no comment";

}

print(comment);


let nameNumbers = [

"zhao":[1,2,3,4],

"xu":[2,4,6,8],

"hui":[3,9],

"zxh":[1,0,1,0]];

for (name,nums) in nameNumbers{

for num in nums{

//print(num);

}

print(name,nums);

}

print(nameNumbers.dynamicType);

var n = 2 ;

while n<10{

n*=2;

}

print("n=\(n)");

var m = 20;

repeat{

m*=2;

}while m < 10;

print("m=\(m)")

m = 1;

for i in 0..<4{

print(i);

}

func sumof(numbers:Int...)->Int{

var sum = 0;

for num in numbers{

sum+=num;

}

print("numbers type is \(numbers.dynamicType)");

return sum;

}


var sum = sumof(1,5);

print("sum=\(sum)");


func return15()->Int{

var y = 10;

func add(){

y+=5;

}

add()

return y;

}

var v = return15();

print("v=\(v)");


func makeIncrementer()->(Int->Int){

func addone(number:Int)->Int{

return 1+number;

}

return addone;

}

var incrementer = makeIncrementer();

print(incrementer(5))


//闭包

var numbers = [20,19,7,12];

print("numbers:\(numbers)")

let mappednumbers = numbers.map { (number:Int) -> Int in

let result = 3*number;

return result;

}

print("mapped:\(mappednumbers)");

let unevenNum = numbers.map { (uneven:Int) -> Int in //返回所有奇数

if uneven % 2 == 1{

return uneven;

}

return 0;

}

print("unevenNum\(unevenNum)");


let num3 = numbers.map({num in 3 * num}); //更简洁的闭包

print("num3=\(num3)");


let sortedNumbers = numbers.sort { $0 < $1 } //通过位置而不是参数名字来引用参数

print("sortedNumbers:\(sortedNumbers)")


class NamedShape {

var numberofside:Int = 0;

var name:String;

init(name:String){

self.name = name;

print("\(self) init");

}

deinit{

print("\(self) deinit");

}

func hello(){print("NamedShape")}

}

var namedshape = NamedShape(name: "zxh")


class Square:NamedShape{

override func hello(){ //重写父类函数

print("Square");

}

override init(name:String){

super.init(name:name);

}

var width:Double = 1.0;

var area:Double{ //getter setter

get{

return width*width;

}

set{

width = sqrt(newValue);

}

}

}

var squ = Square(name:"aaa");

squ.hello();

squ.area = 9;

var v2=1;

//?问号的处理:

//处理变量的可选值时,你可以在操作(比如方法属性和子脚本)之前加?。如果?之前的值是nil?后面的东西都会被忽略,并且整个表达式返回nil。否则,?之后的东西都会被运行。在这两种情况下,整个表达式的值也是一个可选值。

//let optionalValue:Square?=123;


//enum枚举

enum Rank:Int{

case Ace = 1

case Two,Three,For,Five

case Jack,Queen,King

func simpleDescription()->String{

switch self{

case .Ace:

return "ace"

case .Jack:

return "jack"

case .Three:

return "three"

default:

return String(self.rawValue)

}

}

}

var vrank = Rank.Three

print(vrank);

print(vrank.rawValue);

print(vrank.simpleDescription())

let convertedRank = Rank(rawValue: 7); //使用init?(rawValue:)构造

print(convertedRank)


//结构体是传值,类是传引用

struct Card{

var rank:Rank

var suit:Int

}


//protocol

protocol ExampleProtocol{

var simpleDescription:String{get}

mutating func adjust() //函数

}

class SimpleClass: ExampleProtocol {

var simpleDescription:String = "a very simple class"

var anotherProperty:Int = 1995

func adjust() { //类的重写虚函数不需要加mustating,因为类中的方法经常会修改

simpleDescription += " now 100% adjusted"

}

}

var a = SimpleClass()

print(a.simpleDescription)

a.adjust()

let aDescription = a.simpleDescription;

print(aDescription);


struct SimpleStructure:ExampleProtocol {

var simpleDescription:String = "a simple structure"

mutating func adjust() { //结构体的重写虚函数需要加mustating

simpleDescription += " (adjusted)"

}

}

var b = SimpleStructure()

b.adjust()

let bDescription = b.simpleDescription

print(bDescription);


extension Int:ExampleProtocol{ //extension来为现有的类添加功能,比如方法和参数

var simpleDescription:String{

return "The number is \(self)"

}

mutating func adjust(){

self += 42

}

}

print(7.simpleDescription)


//泛型

func repeatItem<Item>(item:Item,times:Int)->[Item]{

var result = [Item]()

for _ in 0 ..< times {

result.append(item)

}

return result

}

var items = repeatItem("kick",times: 4);

print(items);


//swift 教程

let cat = "I am a cat";print(cat) //这样必须加分号;

var n8:Int8; //有符号int8

var un8:UInt8 //无符号int8

var n16:Int16

var n32:Int32

var n64:Int64

//swift提供了8163264位的整形

print(Int64.max); //Int64的最大值

//Int的长度与平台相应,64位平台为6432位平台为32

/*十进制,无前缀

二进制,0b

八进制,0o

十六进制,0x


十进制浮点数,1.25e2

十六进制浮点数,0xFp2,代表15*2^2等于60

*/


//类型转换

let three = 3

let pi = Double(three)


//类型别名

typealias AudioSample = UInt16

let http404error = (404,"not found")

print(http404error.dynamicType) //(Int,String)

let(statusCode,statusMessage) = http404error //分解

let(statusCode1,_) = http404error //如果你只需要一个元素,分解的时候忽略的部分使用_标记

print("the status code is \(http404error.0)") //访问元组中的一个元素

let http200status = (statusCode:200,description:"OK") //给元组命名

print("the status code is \(http200status.statusCode)")


//可选类型

let possibleNumber = "123"

let convertedNumber = Int(possibleNumber)

print(convertedNumber.dynamicType,"\r\n",convertedNumber)

//如果声明一个可选常量或者变量没有赋值,那么自动nil

//可选值的强制解析,前面有一个叹号!表示要强制解析,我知道这个可选有值

let notpossibleNumber = "aaa"

if let actualNumber = Int(notpossibleNumber) { //可选绑定

print("is num")

print("is not num")

//print(actualNumber) //不可打印,swift的自由语法限制

}

let possibleint:Int? = 123;

print(possibleint.dynamicType)

let realint = possibleint!; //可选变为不可选

print(realint.dynamicType)

let assumedint:Int! = nil;

print(assumedint.dynamicType) //ImplicitlyUnwrappedOptional<Int>//隐式可算类型//当第一次赋值之后以后总会有值//有的书也成为绝对有有值,强制解析此值

//print(assumedint)//打印这个会崩溃


//异常处理//讲的不完整

func canThrowAnError() throws{

}


do{//一个do的声明创建了一个新的包含作用域,使得错误能被传播到一个或更多catch从句

try canThrowAnError()

//没有错误消息

}catch{

//有一个错误消息

}

//断言

let age = -3

//assert(age>=0,"a person's age cannot be less than zero") //这个将打印在下方调试All Output,debug中断运行

//在软件发布之前使用断言可以快速发现问题


//基本运算符

//对浮点数进行取余运算%

let (x,y) = (1,2)

print(x,y)

//swift 赋值操作不返回任何值

var ifa=1,ifb=2

//if ifa = ifb {}//编不过


//溢出

//swift不支持溢出运算

x &+ y//使用&+来实现溢出运算

//%取余对负数和浮点数有效-9%4-9 = 4*-2+ -1余数是-1

//b的符号会被忽略a%ba&-b结果是一样的

//使用===!==来判断两个对象是否为引用同一对象实例

//空合运算符

//a ?? b//a进行空判断,如果a包含一个值那么解封,否则返回b

//a必须是Optional类型

//相当于a != nil ? a! : b


//区间运算符

//a...b//[a,b]

//a..<b//[a,b)


//p77字符串

原文链接:https://www.f2er.com/swift/325489.html

猜你在找的Swift相关文章