create enum with arguments in swift

In Swift, you can create an enum with associated values to give it arguments. Here's an example:

main.swift
enum Result<T> {
    case success(T)
    case failure(Error)
}
63 chars
5 lines

In the above example, Result is an enum with two cases: success and failure. The success case has an associated value of type T, representing a successful result, while the failure case has an associated value of type Error, representing a failure with an error.

You can use this enum to handle the result of a function that may either succeed or fail. Here's an example of how you can use it:

main.swift
func divide(_ dividend: Int, by divisor: Int) -> Result<Int> {
    guard divisor != 0 else {
        return .failure(DivisionError.invalidDivisor)
    }
    return .success(dividend / divisor)
}

enum DivisionError: Error {
    case invalidDivisor
}

let result = divide(10, by: 2)
switch result {
case .success(let value):
    print("Result: \(value)")
case .failure(let error):
    print("Error: \(error)")
}
411 chars
19 lines

In this example, the divide function returns a Result<Int> enum. If the divisor is 0, it returns a .failure case with the associated value DivisionError.invalidDivisor. Otherwise, it returns a .success case with the result of the division.

By using the enum in a switch statement, you can handle both cases separately and access the associated values if needed.

Note that the associated values can be of any type, allowing you to pass different types of data with each case of the enum.

related categories

gistlibby LogSnag