喜欢的小伙伴,可以关注我.
class Student{
//实例方法
func study(){
print("学生学习")
}
//类方法
class func run(){
print("学生跑步")
}
}
实例方法要写在它所属的类型的前后大括号({})之间。
实例方法能够隐式访问它所属类型的所有的其他实例方法和属性。
实例方法只能被它所属的类的某个特定实例调用。
实例方法不能脱离于现存的实例而被调用。
//实例方法调用
var s = Student()
s.study()
//类方法
Student.run()
//在外部调用方法的时候,可以用下划线(_)来忽略参数的外部名称
//这里类拓展
extension Student{
//下划线的用法
//food:内部参数
func eat(_ food:String,time:Int){
print("学生吃\(food),吃了\(time)分钟")
}
}
s.eat("火鸡", time: 5)
//类型的每一个实例都有一个隐含属性叫做self,self 完全等同于该实例本身。
//这个地方就要说到OC的方法,底层实现就是C函数,
CMethodImp(id self, SEL _cmd,id arg)
默认底层都有两个参数,self 当前对象或者类, _cmd当前方法的方法编号 @selector(CMethodImp:):对比类似self
现在swift在方法中也能拿到self,还有#function 我们也可以猜测底层实现
extension Student{
//实例方法的测试
func testSelfCmd(){
print(self,#function)
}
//类方法的测试
class func testClassSelfCmd(){
print(self,#function)
}
}
s.testSelfCmd()
Student.testClassSelfCmd()
打印效果
Swift-day1---HelloWord
Swift-day2---基本数据类型
Swift-day3---字符串
Swift-day4---闭包(Closures)
Swift-day5---集合类型--数组,集合,字典
Swift-day6---函数
Swift-day7---类
Swift-day8---结构体,枚举
Swift-day9---属性
持续更新!!!如有什么不足,还请不吝指出!谢谢!








网友评论