Swift编程注释小记1(变量,函数,类)
来源:互联网 发布:js跨域清除cookie 编辑:程序博客网 时间:2024/05/12 09:43
--阅读The Swift Progrmaing Language
--Swift 中的self 参考了Python, 也有函数式编程的影子,
import Foundation//Varibal 变量和定义篇 ===============================================println("Hello, World!")//var 表示变量, let表示常量,所有的数据类型的的首字母是需要大写的var myVariable = 42myVariable = 50let myConstant = 42let explicitDouble: Double = 70let lablel = "The width is "let width = 40let widthLable = lablel + String(width)println(widthLable)let apples = 3let oranges = 5let appleSummary = "I have \(apples) apples."//两个整数相加时,任意一个不能为浮点数let fruitSummary = "I have \(apples + oranges) pieces of fruit."//打印语句println(appleSummary)println(fruitSummary)//array and dictionaryvar shoppingList = ["catfish", "water","tulips","blue paint"]shoppingList[1] = "bottle of water"var occpations = [ "Malcolm":"Captain", "Kaylee":"Mechanic",]occpations["Jayne"] = "Public Relations"println(shoppingList)println(occpations)//create empty array and dictionarylet emptyArray = String[]()let emptyDictionary = Dictionary<String, Float>()//for loop statment must be bool typelet individualScores = [75,43, 103,87,12]var tempScore = 0for score in individualScores{ if score > 50 { tempScore += 3 } else { tempScore += 1 }}println(tempScore)//for and let together usevar optionalString:String? = "Hello"optionalString == nilvar optionalName : String? = "John Appleaseed"var greeting = "Hello"/* if name is nil the code int braces is skipped*/if let name = optionalName{ greeting = "Hello ,\(name)"}//switch...case//must need add default case and is no need to explicitly breaklet vegetable = "red pepper"switch vegetable{case "celery": let vegetableComment = "Add some raisions and make ants on a log"case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich"case let x where x.hasSuffix("pepper"): let vegetable = "It it a spicy \(x)?"default: let vegetableComment = "Everything tasts good is soup"}//for in providing a pair of name to user for key-value pairlet interestingNumbers = [ "Prime" : [2,4,5,7,11,13], "Fibonacci" : [1,1,2,3,5,8], "Squear" : [1,4,5,16,25],]var largest = 0for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest{ largest = number } }}println("largest = \(largest)")//whilevar n = 2while n < 100 { n = n * 2}var m = 2do { m = m * 2} while m < 100println("n = \(n), m = \(m).")//for i in 0..3 I think don't using this statment ,on method resoulation one Problem//Function 篇 ====================================================//func and closures,one return value//“Use -> to separate the parameter names and types from the function’s return type.”func greet(name:String,day:String) -> String{ return "Hello \(name), today is \(day)."}let Return:String = greet("Bob", "Tues")println("Return = \(Return)")//func and closures ,Use a tuple to return multiple values from a function,rember is a tuplefunc getGasPrices() -> (Double, Double, Double){ return (3.58,4.23,45.234)}let MultipleReturn = getGasPrices()println("MultipleReturn = \(MultipleReturn)")// func and closures, functions can nested,就是可以在一个函数中定义多个函数,低层次中的函数可以使用上层次中的变量。func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y}let result : Int = returnFifteen()println("result = \(result)")//func and closures, first-class-type //意思就是一个函数可以当成值返回,so coolfunc makeIncrementer() -> (Int -> Int) { func addOne(number :Int) -> Int { return 1 + number } return addOne}var increment = makeIncrementer()println(increment(7))println("---------------------------------")//func and closures, A function can tak another function as one of ites argument//一个函数可以作为一个参数其它函数使用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, 18,7,12]println(hasAnyMatches(numbers,lessThanTen))// func and closures ,Use in to separate the argumnet and return type from the bodylet mapValue = numbers.map({(number:Int) -> Int in let result = 3 * number return result})let tuple = [1,4,3,45,2]sort(tuple) { $1 > $0}println(tuple)println("---------------------------------")//Object and Classes define and declare =================================//Object and Classes class Shape{ var numberOfSides = 0; func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." }}var shape = Shape()shape.numberOfSides = 7var shapeDescription = shape.simpleDescription()println(shapeDescription)println("---------------------------------")//object and class , important:an initializer to set up the class when an instance create//“Use deinit to create a deinitializer if you need to perform some cleanup before the object is deallocated.class NamedShape { var numberOfSide : Int = 0 var name: String //importmemt: init(name:String) { self.name = name } //deinit(){} func shapeDescription() -> String { return "A simple whith \(numberOfSide) sides" }} //class initializervar namedShape = NamedShape(name:"triganle")namedShape.numberOfSide = 3println(namedShape.shapeDescription())println("---------------------------------")//Object and class override//class Square : NamedShape { var sideLength : Double init(sideLength: Double, name:String) { self.sideLength = sideLength //super 代表父类初始化,也可以重新设置父类的变量值 super.init(name:name) numberOfSide = 4 } func area() -> Double { return sideLength * sideLength } //override shapeDescription method override func shapeDescription() -> String{ return "A spuare whith sides of length \(sideLength)" }}let test = Square(sideLength : 5.2, name :"my test square")println(test.shapeDescription())println(test.area())println("---------------------------------")//object and class , get and set class EquilaterTriangle : NamedShape { var sideLength:Double = 0.0 init(sideLength: Double, name : String) { self.sideLength = sideLength super.init(name:name) numberOfSide = 3 } var perimter: Double { get { return 3.0 * sideLength } //use set newValue and return new Value set { sideLength = newValue / 3.0 } } override func shapeDescription() -> String{ return "An equilater triagle with sides of length \(sideLength)" }}var triangle = EquilaterTriangle(sideLength:10.5,name:"a triangle")println(triangle.perimter)println(triangle.perimter = 11)println(triangle.shapeDescription())
0 0
- Swift编程注释小记1(变量,函数,类)
- 《Swift 函数可以作为变量》
- C#编程(1)实例类成员变量,静态类成员变量,局部函数变量
- swift基础1-变量
- [Swift]Swift的函数式编程
- Eclipse 注释模板 函数注释 类注释 文件注释 Code Template - 1
- Swift的函数式编程( ) -> ( )
- Swift函数式编程API
- Swift函数式编程:Optional
- Swift 的函数式编程
- Swift 的函数式编程
- swift函数式编程-函数基础
- Swift(1):常量与变量
- swift资源库-1-变量&常量
- c++并发编程小记1
- javascript小记——变量和函数的声明提前
- 类内成员变量直接初始化小记
- swift+keystone 部署小记
- Linus Torvalds 先生的 10 个有趣的问答
- freemarker报错之十三
- R语言[]和[[]]操作的区别
- 基于qt5的移动话费详单读取分析程序开发记录
- 编译原理方面:词法语法语义分析器
- Swift编程注释小记1(变量,函数,类)
- 《The programming language Swift》读书笔记
- R语言&与&&操作符的区别
- nginx负载均衡
- 表单操作-复选框
- No matching code signing identity found
- 获取URL参数并跳转
- (异或) 签到
- 拆解字符串并逐个处理 R语言