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

初学swift笔记 方法(九)

2015-10-26 23:13 337 查看
import Foundation
/*
方法
*/
//实例方法 一定需要依附于对象

class MyPoint {
var x: Double = 0.0
var y: Double = 0.0
//类中的内部方法 第一个参数默认没有外部参数名,从第二个以后开始,方法名作为外部参数名 既作为内部参数又做为外部参数
//实例方法
func set(_x: Double,_y: Double) {
x = _x
y = _y
}
//实例方法
func show() {
println("x:\(x) y\(y)")
}
}
func set(_x: Double,_y: Double) {

}

var p0 = MyPoint()
p0.set(10, _y: 7)
p0.show()
set(10, 10)

//结构体中的mutating方法
struct MyPoint_1 {
var x : Double = 0
var y : Double = 0
//结构体和枚举 值类型不可以直接修改其内的变量值,如果要修改,需要在方法前加关键字 mutating
mutating func set(x : Double,y : Double) {
self.x = x
self.y = y

}
func show() {
println("x:\(self.x) y:\(self.y) ")
}

}
//枚举中可以写方法,但枚举中不能有存储属性,可以有计算属性
enum LightSwitch {
case OFF,ON,HIGH
mutating func next() {
switch self {
case .OFF:
self = ON
case .ON:
self = OFF
case .HIGH:
self = OFF

}
}

}
var p1 = MyPoint_1()
p1.show()

var light = LightSwitch.OFF
println(light.hashValue)
light.next()
println(light.hashValue)

/*
类型方法 静态方法
通过类名+方法名来调用
与static静态方法相似,该方法为所有对象共用
*/
struct MyPoint_2 {
var p: Int = 0
static var sp: Int = 0
func getvalue() {
println("p:\(p) sp:\(MyPoint_2.sp)")
}
//静态方法不能够访问非静态变量
static func static_getvalue() {
// println("p:\(p) sp:\(MyPoint_2.sp)")
println("sp:\(MyPoint_2.sp)")

}

}
struct MyPoint_3 {
var p: Int = 0
static var sp: Int = 0
func getvalue() {
println("p:\(p) sp:\(MyPoint_3.sp)")
}
//静态方法不能够访问非静态变量
static func static_getvalue() {
// println("p:\(p) sp:\(MyPoint_3.sp)")
println("sp:\(MyPoint_3.sp)")

}

}
var m2 = MyPoint_2()
m2.getvalue()
MyPoint_2.static_getvalue()

var m3 = MyPoint_3()
m3.getvalue()
MyPoint_3.static_getvalue()

/*
subscripts 下标 访问对象中数据的快捷方式
实例[索引值]
*/
let array = [1,2,3,4,5,6,7]
println(array[0]) //实例对象[索引]

struct student {
var name : String = ""
var math : Int
var english : Int
var chinese : Int
func scoreOf(course : String) -> Int? {
switch course {
case "math":
return math
case "chinese":
return chinese
case "english":
return english
default:
return nil
}
}
//制作下标方法
/*
subscript (course : String) -> Int? {
switch course {
case "math":
return math
case "chinese":
return chinese
case "english":
return english
default:
return nil
}
}
*/
//或者这么写
subscript (course : String) -> Int? {
get{
switch course {
case "math":
return math
case "chinese":
return chinese
case "english":
return english
default:
return nil
}
}
set{
switch course {
case "math":
math = newValue!
case "chinese":
chinese = newValue!
case "english":
english = newValue!
default:
println("set error")
}
}
}

}
var li = student(name: "lisi", math: 90, english: 80, chinese: 98)
println(li.scoreOf("math"))
println(li["math"])//下标访问
li["math"] = 100 //下标赋值
println(li["math"])//下标访问

//下标多索引
struct Mul {
subscript (a: Int,b: Int) -> Int {
return a*b
}
}
var mul = Mul()
println(mul[3,6])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: