public OptionSet with private constructor - swift

I have a sample code:
public struct MyOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let one = MyOptions(rawValue: 1 << 0)
public static let two = MyOptions(rawValue: 1 << 1)
}
In other module I can do:
print(MyOptions.one)
print(MyOptions(rawValue: 10))
How can I do public struct with private constructor and public static properties(like a one, two) to limit manual creation?

You can't. When you conform a type to a protocol, all the required stubs' protection levels must be at least equal to the type's protection level. I'll try to explain why.
Let's say I have a type Foo that I conform to Hashable. I then assign an instance as a Hashable type:
let foo: Hashable = Foo()
Because the instance is of type Hashable, I am guaranteed to have access to the hash(into:) method. But what if I make the method private? At that point you end up with unexpected behavior. Either for some reason I can't access a method that I was guaranteed access to, or I have access to a method that I shouldn't be able to reach. It's a conflict of access levels.
So yeah, what you want to do isn't possible.

Related

swift access modifiers correct usage

Suppose I have the following struct inside a StorageService framework :
struct Post {
public let author: String
public let description: String
public let image: String
public let likes: Int
public let views: Int
}
So to access its fields from another module I mark all fields with public keyword - it's clear. But should I mark the name Post itself to be public :
public struct Post ...
I tried both ways but I see no differences (with public struct Post and struct Post).
What is the right way to follow here?
The access modifier of the type itself will control the accessibility of the type and hence making any properties more accessible than the type itself is useless, since you cannot access properties of a type that you don't know about.
In order to be able to use the Post type from outside your framework, you need to declare Post as public.
This makes the type itself and all of its properties accessible from outside your framework:
public struct Post {
public let author: String
public let description: String
public let image: String
public let likes: Int
public let views: Int
}
On the other hand, if you don't want to expose some specific properties/methods publicly, you can always use an accessibility modifier that is stricter than the type's modifier.
public struct Post {
public let author: String
public let image: String
public let likes: Int
let description: String // can only be accessed from inside the module
private let views: Int // can only be accessed from the Post type itself
}

Why does accessing a String parameter of a subclassed NSManagedObject with a parent relationship crash?

I have generated classes for two core data entities. The first is called Address and is an abstract entity. The second is called Person, and it inherits from Address. I've added a few example managed attributes for the purpose of this test. And i've added a non-managed String property to the Person class. Accessing the string property of the Person class will crash. Why does this crash?
The Address and Person classes are automatically generated by Xcode, with the exception of the extra parameter: let foo = "Foo"
If i modify the code to make Person inherit from NSManagedObject directly instead of Address, then the code works and doesn't crash.
Automatically generated Address class:
#objc(Address)
public class Address: NSManagedObject {
}
extension Address {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Address> {
return NSFetchRequest<Address>(entityName: "Address")
}
#NSManaged public var street: String?
#NSManaged public var city: String?
}
Automatically generated person class with the exception of the "foo" parameter:
#objc(Person)
public class Person: Address {
public let foo = "Foo" //added this parameter
}
extension Person {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Person> {
return NSFetchRequest<Person>(entityName: "Person")
}
#NSManaged public var name: String?
}
problem code
let person = Person(context: context)
print(person.foo) //doesn't crash, but prints empty line instead of value
print("VALUE:\(person.foo):") //crashes with Thread 1: EXC_BAD_ACCESS (code=1, address=0x18)
UPDATE:
if foo is defined as
public let foo: String? = "Foo"
then the print statements don't crash, instead they interpret the value as 'nil' and print that.
So my question becomes: Why is this value which is assigned as a constant being reset to nil under the covers?
I have two hand-waving explanations why you are getting nil:
Managed objects don't function very well until they are inserted.
Your foo is a what I would call a constant stored property. I made up the name because, red flag, I cannot find any examples of it in the Swift book chapter on Properties
Put these two together and you get an edge case that doesn't work.
That being said, I'm kind of surprised that your foo setting does not work, because foo is not a managed property (that is, it is not in the data model). If I make such a constant stored property in a regular, non-managed object…
public class Animal {
public let foo: String! = "Foo"
}
it reads back later as expected.
So, if you can accept that this edge case just doesn't work in Core Data, you can move on to several more normal ways that do work.
One way is to declare foo as a var and assign a value to in awakeFromInsert() which is, as I alluded to earlier, after insertion. In Core Data, awakeFromInsert() is one of your friends…
#objc(Person)
public class Person: Address {
public var foo: String!
override public func awakeFromInsert() {
foo = "Foo"
}
}
Another way that works is as a computed property…
#objc(Person)
public class Person: Address {
public var foo : String { return "Foo" }
}
And, finally, the most logical way, since foo is constant for all instances, is to make it a type property…
#objc(Person)
public class Person: Address {
static var foo: String = "Foo"
}
but of course if you do this you must reference it as Person.foo instead of person.foo.

Codable : does not conform to protocol 'Decodable'

Not able to figure why my class does not conform to Codable
Please not that in my case I do not need to implement the methods encode and decode.
public class LCLAdvantagePlusJackpotCache: Codable {
public let token: String
public let amount: NSNumber
public let member: Bool
public init(token: String, amount: NSNumber, member: Bool) {
self.token = token
self.amount = amount
self.member = member
}
enum CodingKeys: String, CodingKey {
case token, amount, member
}
}
It's because NSNumber is not Codable. Do not use Objective-C types; use Swift types. (That's a general rule; it isn't confined to the Codable situation. But this is a good example of why the rule is a good one!)
Change NSNumber to Int or Double (in both places where it occurs in your code) and all will be well.

Require associatedtype to be representable in a #convention(c) block

I want to have a generic way of doing something like in Swift 3:
public protocol Callable {
associatedtype In : CVarArg
associatedtype Out : CVarArg
}
public struct IntCallable : Callable {
public typealias In = Int
public typealias Out = Double
public typealias FunctionalBlock = #convention(c) (In) -> Out
public func call(_ block: FunctionalBlock) { /* do stuff */ }
}
So I'd like it to look more like this:
public protocol Callable {
associatedtype In : CVarArg
associatedtype Out : CVarArg
typealias FunctionalBlock = #convention(c) (In) -> Out
}
public struct IntCallable : Callable {
public typealias In = Int
public typealias Out = Double
}
public extension Callable {
public func call(_ block: FunctionalBlock) { /* do stuff */ }
}
However, I get the error:
'(Self.In) -> Self.Out' is not representable in Objective-C, so it cannot be used with '#convention(c)'
Is there any constraint I can place on the In/Out associatedtypes that will allow my to declare the generic form of the FunctionalBlock? It works fine without #convention(c), but I need it in order to form a C function call.
This is not currently possible in Swift, due to the how Swift manages values passed as protocols, and CVarArg is a protocol.
What happens behind the scenes is that when passing a value under the umbrella of a protocol, the Swift compiler creates an existential container that wraps the value, a value which is transparently unwrapped at the callee site.
So basically your block actually looks something like this:
typealias FunctionalBlock = #convention(c) (Container<In>) -> Container<Out>
Due to this behind-the-scenes transform, you're not passing values that can be represented in C, thus the error you get.
This is very similar to other protocol related issues, like the famous Protocol doesn't conform to itself?.
Your best bet would be to add overloads for all types that conform to CVarArg, since this is a finite and unchangeable list.

Swift: conforming to properties in protocol?

How to confirm to protocols that declares properties of other protocols in Swift?
There is a protocol GKGameModel in which its implementers need to have a properties conforming to a protocol
public protocol GKGameModel {
// ...
public var players: [GKGameModelPlayer]? { get }
public var activePlayer: GKGameModelPlayer? { get }
// ...
}
public protocol GKGameModelPlayer {
// ...
}
Now, suppose I have a class Player and GameModel that conforms to the above protocols
class Player : NSObject, GKGameModelPlayer {
//...
}
class GameModel : NSObject, GKGameModel {
//...
public var players: [Player]?
public var activePlayer: Player?
}
Now the above code doesn't compile and the error messages (among others) were:
protocol requires property 'activePlayer' with type 'GKGameModelPlayer?'; do you want to add a stub?
candidate has non-matching type 'Player?'
However the Player class conforms to protocol GKGameModelPlayer, hence it should confirm just fine. How can I get this to compile?
Strangely Objective-C deals with this just fine – take a look at the FourInARow example code which does something like this.
The protocol requires that the properties be typed exactly as shown. In other words, an array of GKGameModelPlayers and a single optional GKGameModelPlayer?. If your Player type conforms to the protocol, then an array of Players can be passed to the protocol property if casted / typed as [GKGameModelPlayer].
But the requirement here is not, for example, an activePlayer property that has a type that conforms to GKGameModelPlayer, but rather an activePlayer property that references an instance that it typed as / cast as a GKGameModelPlayer.
I.e. this would fix the error:
class GameModel : NSObject, GKGameModel {
//...
public var players: [GKGameModelPlayer]?
public var activePlayer: GKGameModelPlayer?
}
players and activePlayer property has a type that conforms to GKGameModelPlayer. So just change it to GKGameModelPlayer type instead of Player
class GameModel : NSObject, GKGameModel {
//...
public var players: [GKGameModelPlayer]?
public var activePlayer: GKGameModelPlayer?
}