---
title: "Operations"
url: https://docs.zeroc.com/ice/3.8/slice/operations
language: swift
docs_index: https://docs.zeroc.com/llms.txt
---

> For an index of every page, see [llms.txt](https://docs.zeroc.com/llms.txt).

# Operations

Programming language: Swift. Other languages: [C++](https://docs.zeroc.com/ice/3.8/slice/operations/cpp.md), [C#](https://docs.zeroc.com/ice/3.8/slice/operations/csharp.md), [Java](https://docs.zeroc.com/ice/3.8/slice/operations/java.md), [JavaScript](https://docs.zeroc.com/ice/3.8/slice/operations/js.md), [MATLAB](https://docs.zeroc.com/ice/3.8/slice/operations/matlab.md), [PHP](https://docs.zeroc.com/ice/3.8/slice/operations/php.md), [Python](https://docs.zeroc.com/ice/3.8/slice/operations/python.md), [Ruby](https://docs.zeroc.com/ice/3.8/slice/operations/ruby.md).

## Operation Syntax

An operation definition has a name, a return type, and zero or more parameters.

For example:

```slice
module M
{
    struct TimeOfDay
    {
        short hour;         // 0 - 23
        short minute;       // 0 - 59
        short second;       // 0 - 59
    }

    interface Clock
    {
        TimeOfDay getTime();
        void setTime(TimeOfDay time);
    }
}
```

An operation that returns no value, such as `setTime`, declares `void` as its return type.

Parameters are input parameters by default: their values go from the client to the server. An output parameter, marked with the `out` keyword, carries a value from the server back to the client. An operation can have several input and output parameters, and its output parameters must follow its input parameters:

```slice
module M
{
    interface CircadianRhythm
    {
        void setSleepPeriod(TimeOfDay startTime, TimeOfDay stopTime);
        void getSleepPeriod(out TimeOfDay startTime, out TimeOfDay stopTime);
        void changeSleepPeriod(
            TimeOfDay startTime,
            TimeOfDay stopTime,
            out TimeOfDay prevStartTime,
            out TimeOfDay prevStopTime);
    }
}
```

Each parameter must have a name, and a parameter cannot be both an input and an output parameter.

## Optional Parameters and Return Values

An operation's return value and parameters may be declared as optional to indicate that a program can leave their values unset. Parameters not declared as optional are known as *required* parameters. In the discussion below, we use *parameter* to refer to input parameters, output parameters, and return values.

A unique, non-negative integer *tag* must be assigned to each optional parameter:

```slice
optional(3) bool example(optional(2) string name, out optional(1) int value);
```

The scope of a tag is limited to its operation and has no effect on other operations. You can assign tags in any order.

An optional parameter cannot have a class type, or a constructed type that holds a class type.

An operation's signature can include any combination of required and optional parameters, but output parameters still must follow input parameters:

```slice
bool example(
    string name,
    optional(3) string referrer,
    out optional(1) string promo,
    out int id);
```

Language mappings specify an API for passing optional parameters and testing whether a parameter is present.

## Exception Specifications

An operation lists the user exceptions it can throw in its [exception specification](https://docs.zeroc.com/ice/3.8/slice/exceptions/swift.md#exception-specification-in-operations), a `throws` clause.

## Overloading Operations

Slice does not support overloading: operations in the same interface must have different names, regardless of the type and number of their parameters. A request identifies the operation it invokes by name only.

## Idempotent Operations

An operation is idempotent when calling it several times with the same arguments has the same effect as calling it once. Operations that do not modify the state of the object, such as `getTime` in the `Clock` interface, are idempotent; so is `setTime`, even though it modifies the state. You mark such operations with the `idempotent` keyword:

```slice
interface Clock
{
    idempotent TimeOfDay getTime();
    idempotent void setTime(TimeOfDay time);
}
```

The `idempotent` keyword makes this property part of the contract: the implementation must keep the operation idempotent, and callers can rely on it. Ice relies on it to retry invocations it would not retry otherwise; see [Automatic Retries](https://docs.zeroc.com/ice/3.8/runtime/invocation/automatic-retries/swift.md).

## Client-Side Mapping for Operations

### Mapping for Operations

As we saw in the [Client-Side Swift Mapping for Interfaces](https://docs.zeroc.com/ice/3.8/slice/interfaces/swift.md#client-side-mapping-for-interfaces), for each operation on an interface, the generated proxy protocol extension contains a method with the same name. To invoke an operation, you call this method on the proxy. For example, let’s take the generated code from the [greeter example](https://docs.zeroc.com/ice/3.8/greeter-example/defining-the-greeter-interface-in-slice/swift.md):

```slice
module VisitorCenter
{
    interface Greeter
    {
        string greet(string name);
    }
}
```

The proxy protocol generated from the `Greeter` interface, after removing extra details, is as follows:

```swift
public protocol GreeterPrx: Ice.ObjectPrx {}

public extension GreeterPrx {
    func greet(
        _ iceP_name: Swift.String,
        context: Ice.Context? = nil
    ) async throws -> Swift.String {
        // ...
    }
}
```

Given a proxy to an object of type `Greeter`, the client can invoke the `greet` operation as follows:

```swift
let greeter = try makeProxy(
    communicator: communicator, proxyString: "greeter:tcp -h localhost -p 4061",
    type: GreeterPrx.self)

let greeting = try await greeter.greet("Alice") // Get name via RPC
```

This code asynchronously calls `greet` on the proxy, which sends the request to the server, waits until the operation is complete, and then unmarshals the return value and returns it to the caller.

### Async Methods

All proxy methods generated by the Slice compiler are async which align with Swift's structured concurrency and async/await model. Therefore, synchronous invocations are not supported.

### Exception Handling

Any operation invocation may throw a [runtime exception](https://docs.zeroc.com/ice/3.8/runtime/local-and-dispatch-exceptions/swift.md) and, if the operation has an exception specification, may also throw [user exceptions](https://docs.zeroc.com/ice/3.8/runtime/local-and-dispatch-exceptions/swift.md). Suppose we have the following simple interface:

```slice
exception Tantrum
{
    string reason;
}

interface Child
{
    void askToCleanUp() throws Tantrum;
}
```

Slice exceptions are thrown as Swift exceptions, so you can simply enclose one or more operation invocations in a do-`catch` block:

```swift
let child: ChildPrx = ...   // Get child proxy...

do {
    try await child.askToCleanUp()
} catch let t as Tantrum {
    print("The child says: \(t.reason)")
}
```

## Server-Side Mapping for Operations

### Default Mapping for Operations

As we saw in the [Server-Side Swift Mapping for Interfaces](https://docs.zeroc.com/ice/3.8/slice/interfaces/swift.md#server-side-mapping-for-interfaces), for each operation on an interface, the generated skeleton protocol contains a method requirement with the same name.

For example, let’s take the generated code from the [greeter example](https://docs.zeroc.com/ice/3.8/greeter-example/defining-the-greeter-interface-in-slice/swift.md):

```slice
module VisitorCenter
{
    interface Greeter
    {
        string greet(string name);
    }
}
```

The skeleton protocol generated from the `Greeter` interface, after removing extra details, is as follows:

```swift
public protocol Greeter: Ice.Dispatcher {
    func greet(name: String, current: Ice.Current) async throws -> String
}
```

The `greet` method takes a `name: String` and a `Current`, then returns a value of type `String`. This method should be implemented in your derived servant class with something like:

```swift
struct Chatbot: Greeter {
    func greet(name: String, current _: Ice.Current) -> String {
        return "Hello, \(name)!"
    }
}
```

Since our implementation doesn't call any asynchronous operations or throw any exception, we can omit the `async` and `throws` keywords from the function declaration.

### AMD Mapping for Operations

The `["amd"]` metadata has no effect in Swift. All dispatch methods generated by the Slice compiler are async which align with Swift's structured concurrency and async/await model.

### Throwing Exceptions

To throw an exception from an operation implementation, you simply construct the exception and throw it. For example:

```swift
func write(text: [String], current _: Ice.Current) throws {
    ...
    if (error) {
        throw WriteException(reason: "file too large")
    }
}
```

If you throw an arbitrary Swift exception, the Ice runtime catches the exception and then returns an `UnknownException` to the client.

If you throw a [dispatch exception](https://docs.zeroc.com/ice/3.8/runtime/local-and-dispatch-exceptions/swift.md#dispatch-exceptions), such as `ObjectNotExistException`, the client receives the same exception. If you throw any other Ice local exception, such as `MarshalException`, the client receives an `UnknownLocalException`.

The server-side Ice runtime does not validate user exceptions thrown by an operation implementation to ensure they are compatible with the operation's Slice definition. Rather, Ice returns the user exception to the client, where the client-side runtime will validate the exception as usual and throws `UnknownUserException` for an unexpected exception type.

## Mapping for Parameters and Return Values

### In Parameters

An in parameter is mapped to a Swift parameter with the same name; its type is the mapped Swift type.

For example, a Slice parameter `string name` is mapped to a Swift parameter `name` with type `String`. The rules are the same as for [Fields](https://docs.zeroc.com/ice/3.8/slice/fields/swift.md).

The mapped types of a Slice class, and of a [structure](https://docs.zeroc.com/ice/3.8/slice/user-defined-types/structures/swift.md), sequence or dictionary that contains a class, don't conform to `Sendable`. When the type of an in parameter contains a class, the mapped skeleton method declares this parameter `sending`, which transfers the unmarshaled value into the isolation domain of your servant method. For example:

```slice
class Photo
{
    ...
}

interface Archive
{
    void store(string name, Photo photo);
}
```

maps to the skeleton protocol:

```swift
public protocol Archive: Ice.Dispatcher {
    func store(name: String, photo: sending Photo?, current: Ice.Current) async throws
}
```

#### Parameter Labels

The mapped method (in the proxy and skeleton) always uses the Slice parameter names as parameter labels except in one situation: when the operation has exactly one in parameter, the mapped proxy method doesn’t use any label for this sole in parameter. (But the mapped skeleton method does, as usual.)

Consider the following Slice interface:

```slice
interface Greeter
{
    string greet(string name);
}
```

The generated code is as follows:

```swift
// Client-side
public protocol GreeterPrx: Ice.ObjectPrx {}

public extension GreeterPrx {
    func greet(
        _ iceP_name: String, context: Ice.Context? = nil) async throws ->
        Swift.String {
        ...
    }
}

// Server-side
public protocol Greeter: Ice.Dispatcher {
    func greet(name: String, current: Ice.Current) async throws -> Swift.String
}
```

### Out Parameters and Return Values

The mapping for an operation depends on how many values it returns, including out parameters and a non-`void` return value:

- **Zero values** The corresponding Swift method returns nothing.
- **One value** The corresponding Swift method returns the mapped type, regardless of whether the Slice definition of the operation declared it as a return value or as an out parameter.
- **Multiple values** The mapped Swift method returns a tuple. If the operation declares a return value, this value is provided as the first element of the tuple with the name `returnValue`.

Consider this example:

```slice
interface Example
{
    double op(int inp1, string inp2, out bool outp1, out long outp2);
}
```

The Slice compiler generates the following Swift code for this interface:

```swift
// Client-side
public protocol ExamplePrx: Ice.ObjectPrx {}

public extension ExamplePrx {
    func op(inp1: Int32, inp2: String, context: Ice.Context? = nil) async throws ->
        (returnValue: Double, outp1: Bool, outp2: Int64) {
        ...
    }
}

// Server-side
public protocol Example: Ice.Dispatcher {
    func op(inp1: Int32, inp2: String, current: Ice.Current) async throws ->
        (returnValue: Double, outp1: Bool, outp2: Int64)
}
```

### Optional Parameters

An [optional parameter](#optional-parameters-and-return-values) is mapped to a Swift parameter with the corresponding Swift optional type.

Consider the following operation:

```slice
optional(1) int execute(optional(2) string p);
```

The corresponding proxy function is:

```swift
func execute(_ iceP_p: String? = nil, context: Ice.Context? = nil) async throws ->
    Int32? {
    ...
}
```

Mapped optional parameters get a default value (`nil`). As a result, if you don’t specify an argument for an optional parameter when making an invocation, the target object receives “not set” for this parameter.
