Reputation: 7772
For example, I want to use this extension:
import Foundation
extension String {
func exec (str: String) -> Array<String> {
....
}
}
Where should I save it? Should I create a new file extensions.swift
?
Upvotes: 6
Views: 2954
Reputation: 2494
The old-way on objective-c
was to name like:
UIView+FrameUtils.h
NSMutableArray+Sort.h
UIColor+HEX.h
NSDictionary+Nil.h
So it's clear what is extended (categorized in objective-c) and what new functional implemented. So you may use this style in Swift
too
Upvotes: 1
Reputation: 7906
I'd recommend keeping a group in the project and then creating Files called [Class]Extension. If you store all extension in the same file as mentioned in the other answers you might end up having a lot of issues finding the extension you are looking for and you end up with a file full of different responsibilities. In a small project that might not matter but its better to force good organisation early in a project because you never know which project might grow.
Upvotes: 2
Reputation: 19758
For global extensions such as the one above I think it would be best to put it in an extensions.swift
file. If your extending one of your own classes I find it best to keep it in the same file as the original class so that other developers know about it.
If you have multiple extensions for a particular global class such as String
, you could group them into a StringExtensions.swift
file.
Upvotes: 11