当前位置: 移动技术网 > 移动技术>移动开发>IOS > Swift之关键字使用(I)

Swift之关键字使用(I)

2018年05月29日  | 移动技术网移动技术  | 我要评论
static和class的使用 static 使用 在非class的类型(包括enum和struct)中,一般使用static来描述类型作用域。在这个类型中,我们可以在类型范围中声明并使用存储属性,计算属性和方法。 1 //other 2 struct Point { 3 let x: Double ...

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

 

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网