Issue with Google Analytics in Swift 2 or 3

6 Solutions Collect From Internet About “Issue with Google Analytics in Swift 2 or 3”

Update for Swift 3 (2016.10.19)

let tracker = GAI.sharedInstance().defaultTracker
let build = (GAIDictionaryBuilder.createScreenView().build() as NSDictionary) as! [AnyHashable: Any]

Still an ugly approach, let me know if there’s an cleaner conversion.


Same here, struggling to resolve tons of errors.

What I did (deprecated):

var build = GAIDictionaryBuilder.createAppView().build() as [NSObject : AnyObject]

Edit (2015)

Thanks to @George Poulos. . Recently they updated the options, now createAppView is deprecated, should use createScreenView instead.

var build = GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject]

In addition to the accepted answer:

Changed this:

tracker.send(GAIDictionaryBuilder.createEventWithCategory("UX", action: "User sign in", label: nil, value: nil).build())

To this:

tracker.send(GAIDictionaryBuilder.createEventWithCategory("UX", action: "User sign in", label: nil, value: nil).build()  as [NSObject : AnyObject])

This might be a bit of an overkill, but I prefer creating a short extension and not need to type the castings every time:

In any swift file, paste the following code:

extension GAIDictionaryBuilder
    func buildSwiftCompatible() -> [NSObject:AnyObject]
        return as [NSObject:AnyObject]

Then you can call buildSwiftCompatible() instead of the usual build():


Have fun.

This is a solution I came up with.. Maybe it could help some of you. It’s a struct you need to instantiate in every UIViewController, but it helps with the boilerplate.

import UIKit

struct Analytics {
    fileprivate let viewController: UIViewController
    fileprivate let tracker = GAI.sharedInstance().defaultTracker

    init (forScreen viewController: UIViewController) {
        self.viewController = viewController

    func startTracking () {
        let screenView = GAIDictionaryBuilder.createScreenView().build() as NSDictionary
            let tracker = tracker,
            let build = screenView as? [AnyHashable: Any]
        else { return }

        tracker.set(kGAIScreenName, value: String(describing: viewController))

class HomeViewController: UIViewController {

    lazy var analytics: Analytics = {
        return Analytics(forScreen: self)

    override func viewDidLoad() {

    override func viewWillAppear() {

For swift 3:

let build:NSObject = GAIDictionaryBuilder.createScreenView().build()

tracker?.send(build as! [AnyHashable: Any])

let build = GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject]