<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Combine",
  "identifier" : "/documentation/Combine/Publisher/assign(to:on:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Combine"
    ],
    "preciseIdentifier" : "s:7Combine9PublisherPAAs5NeverO7FailureRtzrlE6assign2to2onAA14AnyCancellableCs24ReferenceWritableKeyPathCyqd__6OutputQzG_qd__tlF"
  },
  "title" : "assign(to:on:)"
}
-->

# assign(to:on:)

Assigns each element from a publisher to a property on an object.

```
func assign<Root>(to keyPath: ReferenceWritableKeyPath<Root, Self.Output>, on object: Root) -> AnyCancellable
```

## Parameters

`keyPath`

A key path that indicates the property to assign. See [Key-Path Expression](https://developer.apple.com/library/archive/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID563) in *The Swift Programming Language* to learn how to use key paths to specify a property of an object.

`object`

The object that contains the property. The subscriber assigns the object’s property every time it receives a new value.

## Return Value

An [`AnyCancellable`](/documentation/Combine/AnyCancellable) instance. Call [`cancel()`](/documentation/Combine/Cancellable/cancel()) on this instance when you no longer want the publisher to automatically assign the property. Deinitializing this instance will also cancel automatic assignment.

## Discussion

Use the [`assign(to:on:)`](/documentation/Combine/Publisher/assign(to:on:)) subscriber when you want to set a given property each time a publisher produces a value.

In this example, the [`assign(to:on:)`](/documentation/Combine/Publisher/assign(to:on:)) sets the value of the `anInt` property on an instance of `MyClass`:

```
class MyClass {
    var anInt: Int = 0 {
        didSet {
            print("anInt was set to: \(anInt)", terminator: "; ")
        }
    }
}

var myObject = MyClass()
let myRange = (0...2)
cancellable = myRange.publisher
    .assign(to: \.anInt, on: myObject)

// Prints: "anInt was set to: 0; anInt was set to: 1; anInt was set to: 2"
```

> Important: The ``doc://com.apple.Combine/documentation/Combine/Subscribers/Assign`` instance created by this operator maintains a strong reference to `object`, and sets it to `nil` when the upstream publisher completes (either normally or with an error).

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)