您的位置:首页 > 移动开发 > Swift

demo学习swift 之 swift 初见

2014-07-30 17:53 405 查看
分享一下在学习swift中写成的demo,本章是第一章(顺序按照苹果的官方文档来,学习之后,按照自己的想法写的一下demo和部分来自官网的),以后会陆续补充。

首先创建一个空项目(这个就不说了),之后添加一个基于父类UIViewController的窗体,这个一不说了。这里面没有用playground,感觉没有那种神秘的感觉(虽然写的时候就知道了结果),用断点+println()打印出自己的结果,感觉还是蛮有意思的事情。原来和自己的看法,如何实现都写在代码的注释中。

这个demo设计面挺多,没有深入下去是入门级的(大神可以绕过),让大家大概对swift的知识点有个全面的了解。



上代码:

1.AppDelegate.swift

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var vc:HelloSwiftViewController?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
{
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

self.vc = HelloSwiftViewController(nibName:nil,bundle:nil);

self.window!.rootViewController = self.vc;

self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}

func applicationWillResignActive(application: UIApplication)
{}

func applicationDidEnterBackground(application: UIApplication)
{}

func applicationWillEnterForeground(application: UIApplication)
{}

func applicationDidBecomeActive(application: UIApplication)
{}

func applicationWillTerminate(application: UIApplication)
{}

}


2.HelloSwiftViewController.swift

在xib上面添加2个label 和 7个button

把七个button对应绑定事件

import UIKit

protocol protocolObject
{
mutating func adjust()
}

class HelloSwiftViewController: UIViewController
{

@IBOutlet var ui_oupPutLabel : UILabel

init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

/*
简单值
说明:使用let 来声明常量(只能赋值一次,这个你懂的),使用var来声明变量。
*/
@IBAction func SimpleValuesTapped(sender : UIButton)
{
//begin-------看看如何给变量赋值(常量和变量)------------
let letName = 70
var varName = "hello var"
var declareName:Int

//打开此注释看看会发生什么?
//        println(delareName)

//可以依次打开注释查看区别
//        var testLabel:UILabel? //初始化nil,大家可以自己区找答案的为什么?!。
//        var testLabel:UILabel! //初始化nil
//        var testLabel:UILabel  //使用前初始化,即使用前必须赋值
//        println(testLabel)

/*
1>没有分号,换行、空格,就是代表语句的分割
2>没有类型声明
3>常量和变量会根据赋值情况,动态获取类型
4>如果没有用!和?追加在类型后面,有类型声明的这个变量或者常量必须在使用前初始化 如上述的declareName变量
*/

self.ui_oupPutLabel.text = String(letName)   //值必须显示转换类型,去掉String会报错:类型不对啊!亲
//        self.ui_oupPutLabel.text = "\(letName)"    //"\()"有String()相同的功效

//到此我有一个疑问:如果用var 或者 let 动态获取一个类型(没有变量声明),此时再想获取(比如这个类型是UILabel),这种类型的属性怎么办呢?我的建议,推荐用静态声明数据类型,这样在后面程序逻辑方面也清晰,也知道这个变量是什么类型,如果动态获取,反而给开发带来一些不必要的麻烦。

//end

//==============================================万恶分割线================================================

//begin --------数组、字典的的赋值---------------------
//写过C#和java等语言的人都知道,用这个[]来访问赋值数组是多么的方面,但是oc里面就是没有(C遗留的不算哦),现在有救了,哈哈,这里至告诉一点点,后面你就会知道用下标是多么的强大
var arrayName = ["元素1","元素2","元素3"];

println(arrayName[0]); //结果是 元素1  不在是objectAtIndex,大家都知道索引下标的强大。

//字典
var dictionaryName = ["key1":"value1","key2":"value2"];
println(dictionaryName["key1"])

//上面初始化都是直接初始化,如果我想在后面动态赋值怎么办
var emptyArray = String[]()
var emptyDictionary = Dictionary<String,Float>()

emptyArray = ["元素1","元素2","元素3"]
//        emptyArray = ["元素1","元素2",2]  //看看有什么变化
println(emptyArray)

emptyDictionary = ["key1":20];
//        emptyDictionary = ["key1":"20"];
println(emptyDictionary)

//这样也行的
//        emptyArray = []
//        emptyDictionary = [:]

//end
}

/*
控制流初见
条件:if、switch  程序的中转站
循环:for-in、for、while、do-while 我知道你们都太熟了,来看看他们在swift中怎么用
*/
@IBAction func controlFlowTapped(sender : UIButton)
{
//-------------------begin循环-------------------
//for-in 这个和oc里面是一样的
let forInArray = [20,30,20,90,100,10]
var forInTotalAdd = 0
for tmpDeclareVarName in forInArray
{
forInTotalAdd += tmpDeclareVarName
}
println(forInTotalAdd)

//for
var forTotalAdd = 0
for var i = 0;i < 3;i++
{
forTotalAdd += i
}
println(forTotalAdd)

//for in ..
var forInDotTotalAdd = 0
for i in 1..10
{
forInDotTotalAdd += i
}
println(forInDotTotalAdd)

//while 和 do while
var whileName = 2
while whileName < 100
{
whileName *= 2
}
println(whileName)

var doWhileName = 2
do
{
doWhileName *= 2
}
while doWhileName < 100
println(doWhileName)

//看看swift的强大
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
}
}
}
println(largest)

//end

//-------------begin条件表达式------------
//if
var ifName = 20
if ifName%2 == 0
{
println(ifName)
}

//switch 看不懂不要紧,这里只是让你知道有这回事 看这里没有break了。
let switchName = "case pepper"
switch switchName
{
case "celery":
let vegetableComment = "celery"

case "cucumber", "watercress":
let vegetableComment = "cucumber,watercress"

case let x where x.hasSuffix("pepper"):
let vegetableComment = "\(x)"
println(vegetableComment)

default://看看把这个语句删掉,会出现什么?
let vegetableComment = "Everything tastes good in soup."
}
//end
}

/*
函数和闭包
函数的声明:func 函数名字 (参数名字1:类型1,参数名字2:类型2)-> 函数放回
使用func来声明一个函数,使用名字和参数来调用函数。使用->来指定函数返回值。
使用{}来创建一个匿名闭包。
函数就是一个特殊的闭包。
*/
@IBAction func funcTapped(sender : UIButton)
{
//通过此,告诉函数是可以嵌套
//返回单个值
func hello(name:String,day:String) -> String
{
return "hello \(name),today is \(day)"
}
println(hello("swift","wen"))

//返回多个值
func hello2(name:String,day:String,another:String) -> (String,String,String)
{
return (name,day,another)
}
println(hello2("swift","wen","haha"))

//返回是一个函数
func hello3() -> (Int->Int)
{
func hello3Inner(number:Int) -> Int
{
return number
}

return hello3Inner
}

var hello3ResultMethod = hello3()
println(hello3ResultMethod(100))

//可变参数
func hello4(numbers: Int...) -> Int
{
var sum = 0
for number in numbers
{
sum += number
}
return sum
}
println(hello4())
println(hello4(42, 597, 12))

//函数作为参数
func paramFunc(num:Int) -> Int
{
return num
}

func hello5(method:Int->Int)->String
{
if method(10) > 10
{
return "大于10"
}
else
{
return "小于10"
}
}

println(hello5(paramFunc))

//闭包
//        { (parameters) -> returnType in
//            statements
//        }

var numbers = [20, 19, 7, 12]
println(numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
}))

//如果一个闭包的类型已知,比如作为一个回调函数,你可以忽略参数的类型和返回值。单个语句闭包会把它语句的值当做结果返回。
println(numbers.map({
number in number*3
}))

//排序
let nums = ["123", "2324", "343", "2123", "12344"]

var afterSortNums = sort(nums,{$0>$1});

//当一个闭包作为最后一个参数传给一个函数的时候,它可以直接跟在括号后面。
//        var afterSortNums = sort(nums){$0>$1};

println(afterSortNums)
}

/*对象和类
使用class和类名来创建一个类。
*/
@IBAction func objectClassTapped(sender : UIButton)
{
class objectClass
{
//?默认值是nil或者是0
var stringType:NSString?
var intType:Int?

//返回类型放后面如意忘 亲赞同不?
func helloClass(helloString:String)->String
{
return "helle class " + helloString
}

//构造
init()
{
//变量初始化
}

//析构
deinit
{
//资源的是否和清理
self.stringType = nil
self.intType = 0
}
}

var tmpObj:objectClass = objectClass();
tmpObj.stringType = "haha"
tmpObj.intType = 10

println(tmpObj.stringType)
println(tmpObj.intType)
println(tmpObj.helloClass("hello"));

//面向对象的三大特性 封装、多态、继承
//1.子类的定义方法是在它们的类名后面加上父类的名字,用冒号分割。创建类的时候并不需要一个标准的根类,所以你可以忽略父类。
//2.子类如果要重写父类的方法的话,需要用override标记——如果没有添加override就重写父类方法的话编译器会报错。

//类中的setter getter
class setGetClass
{

var setGetIntName:Int
{
set
{
//do something
}
get
{
return 100
}
}

init(){}
deinit{}
}

var tmpSetObj = setGetClass()
tmpSetObj.setGetIntName = 10
println(tmpSetObj.setGetIntName)

}

/*
枚举和结构体
使用enum来创建一个枚举。就像类和其他所有命名类型一样,枚举可以包含方法。
使用struct来创建一个结构体。结构体和类有很多相同的地方,比如方法和构造器。它们之间最大的一个区别就是 结构体是传值,类是传引用。
*/
@IBAction func emueTapped(sender: UIButton)
{
//扑克牌 枚举里面出现了方法
enum Rank: Int
{
case Ace = 1 //后面依次增加 2,3,4,5,6
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case 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 aceDescription = ace.simpleDescription()
println(aceDescription)

//原始值 如 1、2、3
let aceRawValue = ace.toRaw()
println(aceRawValue)

//枚举值 就是 枚举值(Enum Value)
let aceFromValue = Rank.fromRaw(1)
println(aceFromValue)

if let convertedRank = Rank.fromRaw(12)
{
let threeDescription = convertedRank.simpleDescription()
println(threeDescription)

println(convertedRank.toRaw());
}

//花色 方片、红桃、梅花、黑桃
enum Suit:Int
{
case Spades = 1, Hearts, Diamonds, Clubs
func simpleDescription() -> String
{
switch self
{
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}

//着色
func colorDes() -> String
{
switch self
{
case .Spades,.Clubs:
return "black"
default:
return "red"

}
}
}

let blackColorString = Suit.Clubs.colorDes()
println(blackColorString)

let redColorString = Suit.Diamonds.colorDes();
println(redColorString)

//结构体
struct Card
{
var rank:Rank
var suit:Suit

func simpleDescription() -> String
{
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}

//输出所有扑克对应的花色
func putOutCardAndSuit()
{
for var i = Rank.Ace.toRaw();i <= Rank.King.toRaw();i++
{

var tmpString = "\(i)  "
for var j = Suit.Spades.toRaw();j <= Suit.Clubs.toRaw();j++
{
tmpString += "\(j) 、"
}
println(tmpString)
}
}
}

let carObj = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = carObj.simpleDescription()
println(threeOfSpadesDescription)

println(carObj.putOutCardAndSuit())
}

/*
协议和扩展
也就是oc中的delegate,但swift的中协议更好用,同时类、枚举和结构体都可以实现协议。
*/
@IBAction func protocolTapped(sender:UIButton)
{
//在本页第11行声明了一个协议
//类实现
class simpleDescription:protocolObject
{
var simpleDescription: String
func adjust()
{
println(simpleDescription)
}

init(simpleString:String)
{
simpleDescription = simpleString
}
}

let tmpSimpClassObj = simpleDescription(simpleString: "hello class Protocol")
tmpSimpClassObj.adjust()

//结构体实现
struct simpleStructure: protocolObject
{
var simpleDescription: String = "hello struct Protocol"
func adjust()
{
println(simpleDescription)
}
}

let tmpStructObj = simpleStructure()
tmpStructObj.adjust();

//枚举实现
enum simpleEnum:Int,protocolObject
{
case On=1 ,Off = 0
func adjust()
{
switch self {
case Off:
println("is Off")
case On:
println("is On")
}
}
}

let tmpEnum = simpleEnum.On
println(tmpEnum.adjust())
}

/*
范型
你也可以创建泛型类、枚举和结构体。
*/
@IBAction func typeTapped(sender:UIButton)
{
//方法中的应用
func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[]
{
var result = ItemType[]()
for i in 0..times
{
result += item
}
return result
}

//默认获取是String类型
println(repeat("knock", 4))

//枚举中应用
enum OptionalValue<T>
{
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)

println(possibleInteger);

//范型复杂应用

}
}


点击下载源文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: