实例方法
/*
1、实例方法
*/
print("1、实例方法")
class MyPoint {
var myX:Double = 0.0
var myY:Double = 0.0
func setPoint(x:Double,y:Double) {
myX = x
myY = y
}
func showPoint(){
print("x=\(myX),y=\(myY)")
}
}
func setPoint(x:Double,_ y:Double) {
}
//默认第一参数作为内部参数,第二个及以后既作为内部有作为外部参数
setPoint(x:10.0,10.0)
var p0 = MyPoint()
p0.setPoint(x: 5.0, y: 5.0)
p0.showPoint()
/*
2、mutating方法
值类型(结构体或者枚举)默认方法是不可以修改属性的,如果要修改要使用mutating关键字
*/
print("\n2、mutating方法")
struct Myperson {
var name:String = ""
var age:Int = 0
mutating func set(name:String,age:Int) {
self.name = name
self.age = age
}
func show() {
print("name=\(name),age=\(age)")
}
}
var person = Myperson()
person.set(name: "ming", age: 20)
person.show()
enum LightSwitch {
case OFF,LOW,HIGH
mutating func next(){
switch self {
case .OFF:
self = .LOW
case .LOW:
self = .HIGH
case .HIGH:
self = .OFF
}
}
}
var light = LightSwitch.LOW
light.next()
print("light=\(light)")
/*
3、类型方法
通过类名来调用的方法,就像类型属性一样
类方法对应的关键字是static(结构体和枚举)class(类)
类方法里面不存在self
*/
//struct TypeMethods {
// var p:Int = 0
// static var sp:Int = 0
// func method() {
// print("p=\(p),sp=\(TypeMethods.sp)")
// }
// static func staticMethod(){
// print("sp=\(TypeMethods.sp)")
// }
//}
print("\n3、类型方法")
class TypeMethods {
var p:Int = 0
class var sp:Int {
return 10
}
func method() {
print("p=\(p),sp=\(TypeMethods.sp)")
}
class func staticMethod(){
print("sp=\(TypeMethods.sp)")
}
}
var type = TypeMethods()
type.method()
TypeMethods.staticMethod()
/*
4、subscript方法 实例对象[索引]调用
*/
print("\n4、subscript方法")
struct Student {
var name:String = ""
var math:Int = 0
var chinese:Int = 0
var english:Int = 0
func sorce(cource:String) -> Int? {
switch cource {
case "math":
return math
case "chinese":
return chinese
case "english":
return english
default:
return nil
}
}
subscript (cource:String) -> Int? {
get{
switch cource {
case "math":
return math
case "chinese":
return chinese
case "english":
return english
default:
return nil
}
}
set{
switch cource {
case "math":
math = newValue!
case "chinese":
chinese = newValue!
case "english":
english = newValue!
default:
print("key is wrong")
}
}
}
}
var student1 = Student(name:"ming",math:98,chinese:97,english:100)
student1["math"] = 96
print(student1["math"]!)
print(student1.sorce(cource:"chinese")!)
/*
5、多索引subscript方法 实例对象[索引]调用
*/
print("\n5、多索引subscript方法")
struct Multiple {
subscript (a:Int,b:Int) -> Int{
return a*b
}
}
var mul = Multiple()
print(mul[3,5])