码迷,mamicode.com
首页 > 编程语言 > 详细

Swift之关键字使用(I)

时间:2018-05-27 12:02:34      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:func   class   var   类型   closed   toc   spl   err   地方   

static和class的使用

static 使用

在非class的类型(包括enum和struct)中,一般使用static来描述类型作用域。在这个类型中,我们可以在类型范围中声明并使用存储属性,计算属性和方法。

技术分享图片
 1 //other
 2 struct Point {  
 3     let x: Double  
 4     let y: Double  
 5     // 存储属性  
 6     static let zero = Point(x: 0, y: 0)  
 7     // 计算属性  
 8     static var ones: [Point] {  
 9         return [Point(x: 1, y: 1),  
10                 Point(x: -1, y: 1),  
11                 Point(x: 1, y: -1),  
12                 Point(x: -1, y: -1)]  
13     }  
14     // 类方法  
15     static func add(p1: Point, p2: Point) -> Point {  
16         return Point(x: p1.x + p2.x, y: p1.y + p2.y)  
17     }  
18 } ```
19 > 注意: class修饰的类中不能使用class来存储属性的
View Code

 

class 使用

1  // other
2  class MyClass {
3  class var bar: Bar?
4  }

但是在使用protocol时,要注意会报一种错误,如:"class variables not yet supported"

//other
有一个比较特殊的是protocol,在Swift中class、struct和enum都是可以实现protocol的,那么如果我们想在protocol里定义一个类型域上的方法或者计算属性的话,应该用哪个关键字呢?答案是使用class进行定义,但是在实现时还是按照上面的规则:在class里使用class关键字,而在struct或enum中仍然使用static——虽然在protocol中定义时使用的是class.
技术分享图片
 1 //other
 2 protocol MyProtocol {
 3     static func foo() -> String
 4 }
 5 struct MyStruct: MyProtocol {
 6     static func foo() -> String {
 7         return "MyStruct"
 8     }
 9 }
10 enum MyEnum: MyProtocol {
11     static func foo() -> String {
12         return "MyEnum"
13     }
14 }
15 class MyClass: MyProtocol {
16     class func foo() -> String {
17         return "MyClass"
18     }
19 }
View Code

 

Private、FilePrivate、Public、open

四大属性的使用范围图:

技术分享图片

 

private 修饰符

  • 只允许在当前类中调用,不包括 Extension 
  • private 现在变为了真正的私有访问控制 
  • 用 private 修饰的方法不可以被代码域之外的地方访问

 

fileprivate 修饰符

  • fileprivate 其实就是过去的 private。 
  • 其修饰的属性或者方法只能在当前的 Swift 源文件里可以访问。 
  • 即在同一个文件中,所有的 fileprivate 方法属性都是可以访问到的。
 1 class A {
 2     fileprivate func test(){
 3         print("this is fileprivate func!")
 4     }
 5 }
 6 
 7 class B:A {
 8     func show(){
 9         test()
10     }
11 }

public 修饰符

  • 修饰的属性或者方法可以在其他作用域被访问  
  • 但不能在重载 override 中被访问  
  • 也不能在继承方法中的 Extension 中被访问

 

open 修饰符

  open 其实就是过去的 public,过去 public 有两个作用:

  • 修饰的属性或者方法可以在其他作用域被访问  
  • 修饰的属性或者方法可以在其他作用域被继承或重载 override

 

Swift之关键字使用(I)

标签:func   class   var   类型   closed   toc   spl   err   地方   

原文地址:https://www.cnblogs.com/EchoHG/p/9095216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!