Swift compiler crashes on switch statement, need workaround - swift

I've got code that basically looks like this, although I'm not sure that this distilled version exactly reproduces the compiler crash:
enum Response<T> {
case Success(T)
case Failure(String)
}
struct ResponseData {
let someData = "some data"
}
func evaluate() {
let response = Response.Success(ResponseData())
switch response {
case let .Success(data):
println("Got response with \(data)")
case let .Failure(reason):
println("Got failure: \(reason)")
default: ()
}
}
The Xcode editor doesn't detect any problems, but when I build, the compiler crashes with this error:
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
When I comment out the .Success case, I can build just fine. I'm guessing the Swift compiler doesn't like generics as associated values with the enum. However, that pattern is extremely useful for me, and it makes the code much more readable. Any idea how I can work around this? As far as I can tell, there's no way to access associated values except with a switch statement.
I should also mention that I have found the question here, but have not managed to make much use of the solutions presented.
Edit Actually the following already throws a seg-fault:
enum Response<T> {
case Success(T)
case Failure(String)
}
struct ResponseData {
let someData = "some data"
}
func evaluate() {
let response = Response.Success(ResponseData())
}
unimplemented IR generation feature non-fixed multi-payload enum layout
enum Response {

Credit to the solution really goes to everyone who commented above.
The problem seems to be that the Swift compiler wants to know exactly how large the enum is in memory. Generics make that impossible, thus the compiler does not behave correctly.
The solution I went with was taken from Rob Rix's library, which is to box the generic in another type. Note that it must be a class, since a reference has a known size but a struct with the generic does not.
The #autoclosure solution seemed interesting also, but it does not work with the latest version of Xcode. This was by design; as I understand, the developers don't want closures to run each time the enum is evaluated.
Thanks everyone!

Looks like you can use only objects that inherit from NSObject
Like this
enum Result<T: NSObject>: Printable {
case Success(T)
case Error(NSError)
var description: String {
switch self{
case .Success(let obj):
return obj.description
case .Error(let error):
return error.description
}
}
And then
let r = Result.Success("Xcode")
r.description
UPD:
You can do something like this
#objc
protocol ResultObjectProtocol {
var description: String { get }
}
extension NSDictionary: ResultObjectProtocol {}
enum Result<T: ResultObjectProtocol>: Printable {
case Success(T)
case Failure(NSError)
var description: String {
switch self{
case .Success(let obj):
return obj.description
case .Failure(let error):
return error.description
}
}
}
let r = Result.Success(["d" : 132]).description
Note: var description - only for example
Upd. (Swift 4)
You are free to use generic type in enum:
enum Result<T> {
case success(T)
case error(Error)
}

Related

How can I get similar print result of NSLog for int enum in swift?

enum ImportType: Int {
case First = 1
case None
case Original
}
var type: ImportType = .First
print(type) --------------------> This will output "First"
NSLog("%#", String(type) --------------------> I can't do this.
NSLog("%d", type.rawValue) --------------------> This will output "1"
Hi All,
I want to get similar result of NSLog as the print function, it more readable for people, but I can't found a way to do this, I got some result that need to do additional handling inside the enum, but I am using other body's source code and just want to collect some information directly.
Are there easy transform way to do what I want?
Thanks~~
Eric
print uses String.init(describing:) under the hood to convert whatever you give it to a String, so you can do that too:
NSLog("%#", String(describing: type))
But really though, the enum should conform to CustomStringConvertible:
enum ImportType: Int, CustomStringConvertible {
case First = 1
case None
case Original
var description: String {
switch self {
case .First:
return "First"
case .None:
return "None"
case .Original:
return "Original"
}
}
}
and you should not rely on this default behaviour of String(describing:), because its behaviour is not specified unless the type conforms to TextOutputStreamable, CustomStringConvertible or CustomDebugStringConvertible. See here for more info.

Sub enumeration rawValue

Consider the following code, where I declared an enum with sub enums inside of it.
enum LocalizeKey {
case message(Messages)
case buttons(Buttons)
enum Buttons: String {
case remove = "Remove"
case add = "Add"
}
enum Messages: String {
case success = "Success"
case failure = "Failure"
}
}
In a normal enum with no sub enums we can easily access .rawValue property and get the raw value of whatever case we picked.
For this case, i created a function like this just to check out what am i getting .
func keyString(for type: LocalizeKey) {
print(type)
}
keyString(for: .message(.failure)) // usage
Problem : there are no other properties than .self to access for this LocalizeKey enum .
What I am trying to achieve: perhaps you can relate by the naming, i am trying to wrap my localized keys, so i can access them easily based on the key type etc, and the rawValue that is refering to the actual key will go into the getLocalizedValue function .
Playground Output : using the function above the playground output was
message(__lldb_expr_21.LocalizeKey.Messages.failure)
Edit: without having to create a variable that switches self on every case, imagine if we had +400 key that would be a huge mess probably.
You need to switch on the type parameter and do pattern matching:
switch type {
case .message(let messages): return messages.rawValue
case .buttons(let buttons): return buttons.rawValue
}
You can also make this an extension of LocalizeKey:
extension LocalizeKey {
var keyString: String {
switch self {
case .message(let messages): return messages.rawValue
case .buttons(let buttons): return buttons.rawValue
}
}
}
You are going to have to switch somewhere. If there are only a handful of "sub-enums", it is probably the easiest to just write a switch manually:
func keyString(for type: LocalizeKey) {
switch type {
case .message(let message):
print(message.rawValue)
case .buttons(let button):
print(button.rawValue)
}
}
If you don't want to write this manually, you either have to change your data structure so it is not needed, or use a code generation tool that generates the boilerplate for you.
Although The mentioned answers do provide the solution, I'd mention the issue of the approach itself:
At this point, each new case (key) has to be added in your switch statement with an associated value, which seems to be undesired boilerplate coding; I assume that you could imagine how it will look like when having many cases in the enums.
Therefore, I'd recommend to follow an approach to be more dynamic instead of adding the value of each case manually in a switch statement. Example:
protocol Localizable {
var value: String { get }
}
extension RawRepresentable where Self: Localizable, Self.RawValue == String {
var value: String { return rawValue }
}
extension CustomStringConvertible where Self: RawRepresentable, Self.RawValue == String {
var description: String { return rawValue }
}
struct LocalizeKey {
enum Buttons: String, Localizable, CustomStringConvertible {
case remove = "Remove"
case add = "Add"
}
enum Messages: String, Localizable, CustomStringConvertible {
case success = "Success"
case failure = "Failure"
}
}
We are applying the same logic for your code, with some improvements to make it easier to maintain.
Based on that, you still able to implement your function as:
func keyString(for type: Localizable) {
print(type)
}
Usage:
keyString(for: LocalizeKey.Buttons.add) // Add
keyString(for: LocalizeKey.Messages.success) // Success
IMO, I find calling it this way seems to be more readable, straightforward rather than the proposed approach (keyString(for: .message(.failure))).

In Swift, is there a way of determining whether an enum is based on a certain type (eg. String)?

In order to write generic code for an NSValueTransformer, I need to be able to check that an enum is of type String for example. Ie.:
enum TestEnum: String {
case Tall
case Short
}
I am expecially interested in a test that can be used with the guard statement. Something allong the line of:
guard let e = myEnum as <string based enum test> else {
// throw an error
}
Please note that not all enums have raw values. For eample:
enum Test2Enum {
case Fat
case Slim
}
Hence a check on the raw value type can not be used alone for this purpose.
EDIT
After some further investigation it has become clear that NSValueTransformer can not be used to transform Swift enums. Please see my second comment from matt's answer.
First, it's your enums, so you can't not know what type they are. Second, you're not going to receive an enum type, but an enum instance. Third, even if you insist on pretending not to know what type this enum is, it's easy to make a function that can be called only with an enum that has a raw value and check what type that raw value is:
enum E1 {
case One
case Two
}
enum E2 : String {
case One
case Two
}
enum E3 : Int {
case One
case Two
}
func f<T:RawRepresentable>(t:T) -> Bool {
return T.RawValue.self == String.self
}
f(E3.One) // false
f(E2.One) // true
f(E1.One) // compile error
Generics to the rescue :
func enumRawType<T>(of v:T)-> Any?
{ return nil }
func enumRawType<T:RawRepresentable>(of v:T)-> Any?
{
return type(of:v.rawValue)
}
enumRawType(of:E1.One) // nil
enumRawType(of:E2.One) // String.Type
enumRawType(of:E3.One) // Int.Type

How do you use a switch statement with a nested enum?

I've created an enum for Instagram endpoints with nested enums similar to Moya.
enum Instagram {
enum Media {
case Popular
case Shortcode(id: String)
case Search(lat: Float, lng: Float, distance: Int)
}
enum Users {
case User(id: String)
case Feed
case Recent(id: String)
}
}
I would like to return the path for each endpoint.
extension Instagram: TargetType {
var path: String {
switch self {
case .Media.Shortcode(let id):
return "/media/shortcode"
}
}
}
However I'm getting an error on the switch statement above for the path.
Enum case Shortcode is not a member of type Instagram
How to fix?
Advanced Practical Enums
I'm adding a more general answer for a few reasons.
This is the only open question regarding nested enums and switch statements. The other one is sadly closed.
The only legit answer does not show how to assign the value of a nested enum to a symbol. The syntax was not intuitive to me.
None of the other answers have extensive case examples.
An enum nested 3 levels deep is more illustrative of the required syntax. Using efremidze answer still took me a while to work it out.
enum Action {
case fighter(F)
case weapon(W)
enum F {
case attack(A)
case defend(D)
case hurt(H)
enum A {
case fail
case success
}
enum D {
case fail
case success
}
enum H {
case none
case some
}
}
enum W {
case swing
case back
}
}
// Matches "3 deep"
let action = Action.fighter(.attack(.fail))
// Matches "1 deep" because more general case listed first.
let action2 = Action.weapon(.swing)
switch action {
case .fighter(.attack(.fail)):
print("3 deep")
case .weapon:
print("1 deep")
case .weapon(.swing):
print("2 deep to case")
case .fighter(.attack):
print("2 deep to another enum level")
default:
print("WTF enum")
}
By adding an associated value for the nested enum you can access it using a switch statement.
enum Instagram {
enum MediaEndpoint {
case Search(lat: Float, lng: Float, distance: Int)
}
case Media(MediaEndpoint)
}
extension Instagram: TargetType {
var path: String {
switch self {
case .Media(.Search):
return "/media/search"
}
}
}
// Demo
protocol TargetType {
var path: String { get }
}
class MoyaProvider<Target: TargetType> {
func request(_ target: Target, completion: #escaping () -> ()) {}
}
let provider = MoyaProvider<Instagram>()
provider.request(.Media(.Search(lat: 0, lng: 0, distance: 0))) {}
There is a couple of problems with your architecture. You should know when and why you need to use extensions and protocols and how you should structure your blocks of code.
If your type needs to conform to that protocol, feel free to use it to
ensure you set your own standards. I don't even see that in the github project you referred to.
Extension are good way to have a primitive type and extend its functionality in other parts of the project. It doesn't make sense to me why you should extend the type right after declaration. A good use case of it is where the String type has been extended to support URL Encoded values:
private extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
}
}
When you are using this type of switch-case block
switch self {
case .Zen:
return "/zen"
case .UserProfile(let name):
return "/users/\(name.URLEscapedString)"
case .UserRepositories(let name):
return "/users/\(name.URLEscapedString)/repos"
}
The value in the case should be a member of self. that's why it can not find the type. the type is declared inside Instagram enum but it doesn't hold value in the self. it holds value inside Media. So move your media related function into the declaration of Media and access them there. That way self is referring to Media. Here's the full working code for me:
private extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!
}
}
public enum Instagram {
public enum Media {
case Search(String)
var path:String {
switch self {
case Media.Search(let keyword):
return "/media/search/\(keyword.URLEscapedString)"
}
}
}
}
var me = Instagram.Media.Search("me")
print(me.path)
As a piece of advice, in each step of building your whole architecture just question yourself if that piece of code belongs to that type or should be accessible publicly. In this case it makes complete sense to move search to Media cause you are searching media. You can add the same pattern for something like User and have search under user that returns different value.
Enum case Search is not a member of type Instagram
As the compiler say, Search is not a member of type Instagram. It's just an enum in the scope of Instagram. You have to create a member that is an instance of Search in Instagram
struct Instagram {
enum Media {
case Search(lat: Float, lng: Float, distance: Int)
}
// something like:
var media = .Search(lat: 0, lng: 0, distance: 0)
// I'm not sure this one is right syntax
// because I can't check it right now.
// please just get the idea
}
extension Instagram: TargetType {
var path: String {
switch self.media {
case .Search(let _, let _, let _):
return "/media/search"
}
}
}

Reference Swift enum member without its associated value

I have the following enum:
enum State: Equatable {
case Loading
case Finished
case Error(message: String)
}
func ==(lhs: State, rhs: State) -> Bool {
//...
}
I want to be able to compare enum members. I have overloaded == operator, and it works, but there's a problem:
let state: State = .Loading
// works just fine
let thisWorks = state == .Finished
// this does as well
let thisWorks2 = state == .Error("Derp!")
// this, however, does not, compiler error: "Could not find member 'Error'"
let thisDoesnt = state == .Error
This seems to be a compiler limitation. I don't see why I should not be able to reference the enum member without its associated value. Apparently I don't care about the error message associated with .Error, I just need to know if an error has occurred. This is actually possible with switch, so I don't know why regular statements are limited.
I have to admit that I haven't looked at Swift 2 closely. Should I expect some improvements in the new version? Another question is, until it is released, is there any workaround?
Enums work really well with switch:
let state: State = .Error(message: "Foo")
switch state {
case .Loading:
print("Loading")
case .Finished:
print("Finished")
case .Error(message: "Foo"):
print("Foo!!!")
case .Error(message: _):
print("Some other error")
}
Swift 2.0 will bring another control flow syntax that probably you will appreciate:
Swift 2.0
if case .Error(message: _) = state {
print("An Error")
}
Hope this helps
You are creating a new instance of the enum. You're error enum has a required associated value. It can't be nil. Thus when you create an enum, you must give it a value.
How about if you make your error state's associated value optional?
enum State: Equatable {
case Loading
case Finished
case Error(message: String?)
Then you could use code like this:
let thisDoesnt = state == .Error(nil)
Try it.
let thisWorks2 = state == .Error(message: "Derp!");