Read-only and non-computed variable properties in Swift

后端 未结 4 1419
感情败类
感情败类 2020-12-23 08:54

I\'m trying to figure out something with the new Apple Swift language. Let\'s say I used to do something like the following in Objective-C. I have readonly prop

4条回答
  •  抹茶落季
    2020-12-23 09:29

    There are two basic ways of doing what you want. First way is by having a private property and and a public computed property which returns that property:

    public class Clock {
    
      private var _hours = 0
    
      public var hours: UInt {
        return _hours
      }
    
    }
    

    But this can be achieved in a different, shorter way, as stated in the section "Access Control" of the "The Swift Programming Language" book:

    public class Clock {
    
        public private(set) var hours = 0
    
    }
    

    As a side note, you MUST provide a public initialiser when declaring a public type. Even if you provide default values to all properties, init() must be defined explicitly public:

    public class Clock {
    
        public private(set) var hours = 0
    
        public init() {
          hours = 0
        }
        // or simply `public init() {}`
    
    }
    

    This is also explained in the same section of the book, when talking about default initialisers.

提交回复
热议问题