Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

theprizerevealed

macrumors regular
Original poster
Feb 26, 2016
183
12
I am writing a new app and I have several view controllers that segue in sequence. In an earlier view controller I added an extension with a function just after the "import UIKit". Then I call this function in ViewDidLoad.

Later in the app another view controller is meant to use the same function in that view controller. So I thought that I should add the extension with that function in the same place in the code for that view controller - just after "import UIKit".

However when I try to build that app then I receive the swift compiler error that it is an invalid redeclaration of that function and it lists both the earlier view controller in the sequence as well as the latest view controller. Why does that happen?

When I remove the code from the latest view controller but leave the extension in the earlier view controller then both view controllers work and the app is built and seems to work correctly.

Could someone explain what is happening in this case? thanks for your help
 
Swift code in a module is visible to all the source code in that module (limited by access modifiers like file private etc.) You only need to add an extension one time in your app. It will be visible to all the code in your app.

It's probably best to place it in its own file. It's customary to place extensions in files named like UIColor+SomeName.swift where SomeName is your description of what the extension does and UIColor is the class that is being added to. The + indicates that it's an extension.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.