Access Enum Associated Value as Optional

Why does a Swift enum with optional associated value require trailing parentheses when being declared?

It compiles with Xcode 11 beta and produces a case constructor. Here is the link to Swift evolution proposal.

Your exoticBird is not Animal, it is rather a case constructor. Alt + Click on your exoticBird variable and you will see type of it defined as follows.

let exoticBird: (String?) -> Animal

I think when you leave out associated type in enum, it creates a function based on associated type.

You could pass string to it and then call isFriendly on it like so,

isExoticBird(nil).isFriendly

So, it seems that you cannot leave associated type if you want to create the type explicitly unless you want to do some functional programming.

Now, Small functional transformation with the case constructor type.

Define a function like so,

func isOtherAnimalFriendly(_ f: @escaping (String?) -> Animal) -> (String?) -> Bool {
return { animalName in
f(animalName).isFriendly
}
}

And now, use the following code,

let exoticFish = Animal.other
let namedAnimal = isOtherAnimalFriendly(exoticFish)

Notice that the type of namedAnimal is now,

let namedAnimal: (String?) -> Bool

And you could use this new function with name,

print("Is exotic fish friendly: \(namedAnimal(nil))")

Also use higher order functions such as map on it,

["Cat", "Cow", "Horse"].map(Animal.other) // array of animals with associated values

How to get a swift enum's associated value regardless of the enum case

Define a method isMissing() inside the enum - write it once and only once. Then you get nearly exactly what you prefer:

for field in self.fields {
if field.value.isMissing() {
missingFields.append(field.name)
}
}

It would look something like this (from the Swift Interpreter):

  1> class Foo {}
>
2> enum Value {
3. case One(Foo!)
4. case Two(Foo!)
5.
6. func isMissing () -> Bool {
7. switch self {
8. case let .One(foo): return foo == nil
9. case let .Two(foo): return foo == nil
10. }
11. }
12. }
13> let aVal = Value.One(nil)
aVal: Value = One {
One = nil
}
14> aVal.isMissing()
$R0: Bool = true

Swift Enum associated values conforming to single protocol

I've found the solution in case anyone will need this too.

enum ContentType {
case content1(Type1 & Refreshable)
case content2(Type2 & Refreshable)
case content3(someLabel: Type3 & Refreshable)

func refreshMe() {
let caseReflection = Mirror(reflecting: self).children.first!.value
(caseReflection as? Refreshable)?.refresh() //If associated type doesn't have label

let refreshable = Mirror(reflecting: caseReflection).children.first?.value as? Refreshable
refreshable?.refresh() //If associated type has label
}
}

How to access a Swift enum associated value outside of a switch statement

As others have pointed out, this is now kind of possible in Swift 2:

import CoreGraphics

enum Line {
case Horizontal(CGFloat)
case Vertical(CGFloat)
}

let min = Line.Horizontal(0.0)
let mid = Line.Horizontal(0.5)
let max = Line.Horizontal(1.0)

func doToLine(line: Line) -> CGFloat? {
if case .Horizontal(let value) = line {
return value
}
return .None
}

doToLine(min) // prints 0
doToLine(mid) // prints 0.5
doToLine(max) // prints 1

Unwrap optional properties automatically in enum

Use optional enum's .some binding:

enum StoreAPI {
case newNote(String, Data?)
}

// sample data
let api = StoreAPI.newNote("title", "data".data(using: .utf8))

switch api {

case let .newNote(title, .some(data)):
print("title: \(title), data: \(data)")

default:
break

}

Accessing an Enumeration association value in Swift

The value is associated to an instance of the enumeration. Therefore, to access it without a switch, you need to make a getter and make it available explicitly. Something like below:

enum Number {
case int(Int)
case float(Float)

func get() -> NSNumber {
switch self {
case .int(let num):
return num
case .float(let num):
return num
}
}
}

var vInteger = Number.int(10)
var vFloat = Number.float(10.5)

println(vInteger.get())
println(vFloat.get())

Maybe in the future something like that may be automatically created or a shorter convenience could be added to the language.



Related Topics



Leave a reply



Submit