swift参考了OC,Rust,Haskell,Ruby,Python,C#等语言的特性。首先,学习这门语言是速学的,我不想浪费太多时间在笔记这门语言和其他语言的哪里不同,特性你自己亲自实践就知道了。下面是我亲自实践总结的一点点皮毛而已。

废话不多说,直接上代码:

1 声明变量和常量

var str: String = "Look what I can do"
var age: Int = 18

let favoriteNumber: Int = 42

代替上面的简单写法就是:

var str = "Look what I can do"
var age = 18

let favoriteNumber = 42

2 字符串声明和初始化或者说是直接赋值

var favoriteGame: String = "Mario Kart"
favoriteGame = "Super Smash Bros"

3 操作符的使用与if语法

let batmanCoolness = 10
var supermanCoolness = 9
let aduamanCoolness = 1
batmanCoolness < supermanCoolness
batmanCoolness > supermanCoolness
supermanCoolness >= 8
batmanCoolness == (supermanCoolness + aduamanCoolness)
batmanCoolness > aduamanCoolness && batmanCoolness == (aduamanCoolness + supermanCoolness)
batmanCoolness < supermanCoolness || aduamanCoolness < supermanCoolness

var spidermanCoolness = 7
(spidermanCoolness + aduamanCoolness) > supermanCoolness
spidermanCoolness == 7 && aduamanCoolness == 2

if(batmanCoolness > spidermanCoolness){

spidermanCoolness = spidermanCoolness - 1

}else if(batmanCoolness >= spidermanCoolness){

spidermanCoolness = spidermanCoolness - 1

}else{

spidermanCoolness = spidermanCoolness + 1
}

if(supermanCoolness < spidermanCoolness)  {
    supermanCoolness = supermanCoolness - 1
    spidermanCoolness = spidermanCoolness + 1
} else if (supermanCoolness == spidermanCoolness)  {
    supermanCoolness = supermanCoolness + 1
    spidermanCoolness = spidermanCoolness + 1
} else  {
    supermanCoolness = supermanCoolness + 1
    spidermanCoolness = spidermanCoolness - 1
}

4 print 语法的使用
print("Hello,World")
print("Ry is awesome")
print(batmanCoolness)

5 字符串插入的使用

var apples = 5
print("Sally has \(apples)apples")
print("Sally has \(apples - 5) apples")

6 可选optional使用(注意:0或者一个具体值)

var optionalNumber: Int? = 5
optionalNumber = nil

if let number = optionalNumber {

print("It is a number")
}
else{

print("It is not a number")
}

7 类型转换

var languagesLearned: String = "3"
var languagesLearnedNum: Int? = Int(languagesLearned)

如:

var tutorialTeam: String = "55"
var editorialTeam = 23

var tutorialTeamNum: Int? = Int(tutorialTeam)

if let numTutorial = tutorialTeamNum  {
    if(numTutorial > editorialTeam)  {
        print("\(numTutorial) is greater than \(editorialTeam)")
    } else if (numTutorial < editorialTeam) {
        print("\(numTutorial) is less than \(editorialTeam)")
    } else  {
        print("\(numTutorial) is equal to \(editorialTeam)")
    }
} else  {
    print("Invalid entry")
}

8 方法的使用

例子:func randomIntBetween(low:Int, high:Int) -> Int {
    let range = high - (low - 1)
    return (Int(arc4random()) % range) + (low - 1)
}

新建项目PeopleDatabase

main.swift

import Foundation

//var newPerson = Person() //创建对象newPerson类的person,等于一个Person对象初始化。即可调用person类
//
//newPerson.enterInfo()
//newPerson.printInfo()

// 加入循环
var response: String
var people: [Person] = [] //创建数组

repeat{

var newPerson = Person()
    newPerson.enterInfo()
    newPerson.printInfo()
    people.append(newPerson)
    newPerson.printInfo()
    
    print("Do you want to enter another name?(y/n)")
    response = input()
}while(response == "y")

print("Number of people in the database: \(people.count)")

for onePerson in people  {
    onePerson.printInfo()
}

新建一个Person类

Person.swift

import Foundation
class Person  {//创建了一个person的类,类不仅有属性,还可以包含方法

var firstName = ""
    var lastName = ""
    var age = 0
    
    func input() -> String {
        let keyboard = NSFileHandle.fileHandleWithStandardInput()
        let inputData = keyboard.availableData
        let rawString = NSString(data: inputData, encoding:NSUTF8StringEncoding)
        if let string = rawString {
            return string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        } else {
            return "Invalid input"
        }
    }
    
    func changeFirstName(newFirstName:String) { //1创建方法
        firstName = newFirstName
    }
    
    func enterInfo()  {//2创建方法
        print("What is the first name?")
        firstName = input()
        
        print("What is \(firstName)'s last name?")
        lastName = input()
        print("How old is \(firstName) \(lastName)")
        let userInput = Int(input())
        if let number = userInput {
            age = number
        }
    }
    
    func printInfo()  {//3创建方法
//        print("First Name: \(firstName)")
        print("\(firstName) \(lastName) is \(age) years old")
    }

}

记得导入文件helpers.swift的辅助文件

helpers.swif

import Foundation

func input() -> String {
  let keyboard = NSFileHandle.fileHandleWithStandardInput()
  let inputData = keyboard.availableData
  let rawString = NSString(data: inputData, encoding:NSUTF8StringEncoding)
  if let string = rawString {
    return string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
  } else {
    return "Invalid input"
  }
}

func randomIntBetween(low:Int, high:Int) -> Int {
  let range = high - (low - 1)
  return (Int(arc4random()) % range) + (low - 1)
}

9 swift的导入类的时候,不需要导入类的头文件,直接创建类直接就可以调用了,这是和OC特殊的不同点,主要是方便。节省很多开发时间和提高开发效率

10

//常量的声明
let swiftTeam = 13
let iOSTeam = 54
let otherTeams = 48
//变量 的声明和值的改变
var totalTeam = swiftTeam + iOSTeam + otherTeams
totalTeam += 1

let priceInferred = 19.99
let priceExplict: Double = 19.99
let onSaleInferred = true
let onSaleExplicit: Bool = false
let nameInferred = "Whoopie Cushion"
let nameExplicit: String = "Whoopie Cushion"
if onSaleInferred {
  print("\(nameInferred) on sale for \(priceInferred)!")
}else{
 print("\(nameInferred) at regular price: \(priceInferred)!")
}

//类的定义和调用
class TipCalculator{
    let total: Double
    let taxPct: Double
    let subtotal: Double
    
    init(total:Double,taxPct: Double){ //初始化方法
    
      self.total = total
        self.taxPct = taxPct
        subtotal = total/(taxPct + 1)
      
    }
    func cailcTipWithTipPct(tipPct: Double) -> Double {
        
        return subtotal * tipPct
    }
   
    func printPossibleTips(){
        
        print("15%:\(cailcTipWithTipPct(0.15))")
        print("18%:\(cailcTipWithTipPct(0.18))")
        print("20%:\(cailcTipWithTipPct(0.20))")
    }
    
    func returnPossibleTips() -> [Int: Double] {
        
        let possibleTipsInferred = [0.15,0.18,0.20]
        var retval = [Int: Double]()
        for possibleTip in possibleTipsInferred {
            let intPct = Int(possibleTip * 100)
            retval[intPct] = cailcTipWithTipPct(possibleTip)
        }
        return retval
    }

}
let tipCalc = TipCalculator(total: 33.25,taxPct: 0.06)
tipCalc.printPossibleTips()

11 //Unnamed Tuples元组的使用---无命名

//let tipAndTotal = (4.00,25.19)或者
let tipAndTotal:(Double,Double) = (4.00,25.19)
//元组点语法的访问index(第几个元素)
tipAndTotal.0
tipAndTotal.1
//另外设置一个元组赋值第一个元组,然后访问里面的元素
let(theTipAmt,theTotal) = tipAndTotal
theTipAmt
theTotal

//#####元组的使用 有命名
//let tipAndTotalNamed:(tipAmt:Double, total:Double) = (4.00, 25.19)也可以这样
let tipAndTotalNamed = (tipAmt:4.00,total:25.19)
tipAndTotalNamed.tipAmt
tipAndTotalNamed.total

//#####元组的使用 Returning Tuples
let total = 21.19
let taxPct = 0.06
let subtotal = total/(taxPct + 1)
func calcTipWithTipPct(tipPct:Double) -> (tipAmt:Double,total:Double) {
    
    let tipAmt = subtotal * tipPct
    let finalTotal = total + tipAmt
    return(tipAmt,finalTotal)
}
calcTipWithTipPct(0.20)

12 //A Full Prototype 完整的原型
class TipCalculatorModel {
    
    var total: Double
    var taxPct: Double
    var subtotal: Double {
        get {
            return total / (taxPct + 1)
        }
    }
    
    init(total: Double, taxPct: Double) {
        self.total = total
        self.taxPct = taxPct
    }
    
    func calcTipWithTipPct(tipPct:Double) -> (tipAmt:Double, total:Double) {
        let tipAmt = subtotal * tipPct
        let finalTotal = total + tipAmt
        return (tipAmt, finalTotal)
    }
    
    func returnPossibleTips() -> [Int: (tipAmt:Double, total:Double)] {
        
        let possibleTipsInferred = [0.15, 0.18, 0.20]
        
        var retval = [Int: (tipAmt:Double, total:Double)]()
        for possibleTip in possibleTipsInferred {
            let intPct = Int(possibleTip*100)
            retval[intPct] = calcTipWithTipPct(possibleTip)
        }
        return retval
        
    }
    
}

13 //Protocols
protocol Speaker{
  func Speak()
}
class Vicki: Speaker {
    func Speak() {
        print("Hello, I am Vicki!")
    }
}

class Ray: Speaker {
    func Speak() {
        print("Yo, I am Ray!")
    }
}
class Animal {
}
class Dog : Animal, Speaker {
    func Speak() {
        print("Woof!")
    }
}

14//Optional Protocols
@objc protocol Speak{
  func Speak()
    optional func TellJoke()
}
//If you get an error, make sure to add this line to the top of your playground:import Foundation
//protocol的使用调用
var speaker:Speaker
speaker = Ray()
speaker.Speak()
speaker = Vicki()
speaker.Speak()

15//Delegates

protocol DateSimulatorDelegate {
    func dateSimulatorDidStart(sim:DateSimulator, a:Speaker, b:Speaker)
    func dateSimulatorDidEnd(sim:DateSimulator, a: Speaker, b:Speaker)
}

class DateSimulator {
    
    let a:Speaker
    let b:Speaker
    var delegate:DateSimulatorDelegate?
    
    init(a:Speaker, b:Speaker) {
        self.a = a
        self.b = b
    }
    
    func simulate() {
        delegate?.dateSimulatorDidStart(self, a:a, b: b)
        print("Off to dinner...")
        a.Speak()
        b.Speak()
        print("Walking back home...")
//        a.TellJoke?()
//        b.TellJoke?()
        delegate?.dateSimulatorDidEnd(self, a:a, b:b)
    }
}

swift语言的学习笔记的更多相关文章

  1. 初探swift语言的学习笔记四(类对象,函数)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/29606137 转载请注明出处 假设认为文章对你有所帮助,请通过留言 ...

  2. 初探swift语言的学习笔记七(swift 的关健词)

    每一种语言都有相应的关键词,每个关键词都有他独特的作用,来看看swfit中的关键词: 关键词: 用来声明的: “ class, deinit, enum, extension, func, impor ...

  3. 初探swift语言的学习笔记三(闭包-匿名函数)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/29353019 转载请注明出处 假设认为文章对你有所帮助,请通过留言 ...

  4. 初探swift语言的学习笔记十(block)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/35783341 转载请注明出处 假设觉得文章对你有所帮助,请通过留言 ...

  5. 初探swift语言的学习笔记(闭包 - 匿名函数或block块代码)

    很多高级语言都支持匿名函数操作,在OC中的block也为大家所熟悉,然面在swift里好像是被重新作了一个定义,不叫匿名函数,或 block了,而叫闭包(closure).下面配合代码来理解一下swi ...

  6. 初探swift语言的学习笔记五(线程)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/30354127 转载请注明出处 假设认为文章对你有所帮助,请通过留言 ...

  7. 初探swift语言的学习笔记十一(performSelector)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/35842441 转载请注明出处 假设认为文章对你有所帮助,请通过留言 ...

  8. 初探swift语言的学习笔记(闭包-匿名函数或block块代码)

    使用Block的地方很多,其中传值只是其中的一小部分,下面介绍Block在两个界面之间的传值: 先说一下思想: 首先,创建两个视图控制器,在第一个视图控制器中创建一个UILabel和一个UIButto ...

  9. 初探swift语言的学习笔记四-2(对上一节有些遗留进行处理)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/30314359 转载请注明出处 假设认为文章对你有所帮助,请通过留言 ...

随机推荐

  1. 用mciSendString做音乐播放器

    音乐操作类 public class clsMCI { public clsMCI() { // // TODO: 在此处添加构造函数逻辑 // } //定义API函数使用的字符串变量 [Marsha ...

  2. wordpress安装记录

    wordpress 已经完全部署到Linux后,进行开始安装的时候,数据库信息都填入好了(前提是:链接信息输入都正确) 然后点击会报错,说是链接数据库失败(数据库是建在阿里云服务器上的),但是具体不知 ...

  3. 第一篇 UEditor入门部署和体验

    UEditor 是由百度「FEX前端研发团队」开发的所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码. UEditor富文本编辑器,轻量, ...

  4. git一些常用设置

    用法:git config [选项] 配置文件位置    --global              使用全局配置文件    --system              使用系统级配置文件    -- ...

  5. VMware + OpenStack: 从 Plugin 到 VIO (VMware Integrated OpenStack)的演进

    VMware 做为实际上的企业虚拟化领导者,对 OpenStack 的态度一直在变化.一开始,VMware 表达出与 OpenStack 的竞争态度.随着 OpenStack 的逐步壮大并且一步一步进 ...

  6. 使用Ajax与服务器端通信

    Ajax这个词,不代表任何东西,它仅仅是称呼一系列促进客户端与服务器通信的技术时所用的一个术语.服务器通信时Ajax技术的核心内容,其目标就是从客户端向服务器发送信息,并接受后者的回传,以求在此过程中 ...

  7. 1644 免费馅饼 题解(c++)(S.B.S.)

    1644 免费馅饼(巴蜀oj上的编号) 题面:          SERKOI最新推出了一种叫做“免费馅饼”的游戏.         游戏在一个舞台上进行.舞台的宽度为W格,天幕的高度为H格,游戏者占 ...

  8. codeforces 442B B. Andrey and Problem(贪心)

    题目链接: B. Andrey and Problem time limit per test 2 seconds memory limit per test 256 megabytes input ...

  9. HDU 5057 Argestes and Sequence --树状数组(卡内存)

    题意:给n个数字,每次两种操作: 1.修改第x个数字为y. 2.查询[L,R]区间内第D位为P的数有多少个. 解法:这题当时被卡内存了,后来看了下别人代码发现可以用unsigned short神奇卡过 ...

  10. 搜索服务Solr集群搭建 使用ZooKeeper作为代理层

    上篇文章搭建了zookeeper集群 那好,今天就可以搭建solr搜服服务的集群了,这个和redis 集群不同,是需要zk管理的,作为一个代理层 安装四个tomcat,修改其端口号不能冲突.8080~ ...