summaryrefslogtreecommitdiff
path: root/swift/src/Ice/LocalObject.swift
blob: 00b1b75844d4dbec2666b274d2155e01c6ec5dda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//
// Copyright (c) ZeroC, Inc. All rights reserved.
//

import IceImpl

class LocalObject<Handle: ICELocalObject> {
    let handle: Handle

    init(handle: Handle) {
        precondition(handle.swiftRef == nil)
        self.handle = handle
        self.handle.swiftRef = self
    }
}

extension ICELocalObject {
    //
    // getSwiftObject returns the Swift object holding a handle to this ICELocalObject or initializes a new one
    //
    func getSwiftObject<Handle, LocalObjectClass>(_: LocalObjectClass.Type,
                                                  initializer: () -> LocalObjectClass) -> LocalObjectClass
        where Handle: ICELocalObject, LocalObjectClass: LocalObject<Handle> {
        objc_sync_enter(self)
        defer { objc_sync_exit(self) }

        if let swiftClass = swiftRef {
            precondition(swiftClass is LocalObjectClass)
            // swiftlint:disable force_cast
            return swiftClass as! LocalObjectClass
        }

        return initializer()
    }

    //
    // getCachedSwiftObject returns the Swift object holding a handle to this ICELocalObject
    //
    func getCachedSwiftObject<Handle, LocalObjectClass>(_: LocalObjectClass.Type) -> LocalObjectClass
        where Handle: ICELocalObject, LocalObjectClass: LocalObject<Handle> {
        guard let swiftClass = swiftRef else {
            preconditionFailure("swiftRef is nil")
        }
        guard let c = swiftClass as? LocalObjectClass else {
            preconditionFailure("Invalid swift type for ICELocalObject")
        }
        return c
    }
}