0

I am using SnapKit.swift and other framework. I wonder why sometime I need to add import SnapKit.swift and why sometime I don't have to in file that use SnapKit.

Can anyone point me to some resource about how Swift import system works?

Edit: The below code works all fine without importing SnapKit

import UIKit

class ImageEditViewController: UIViewController {

    private var imageView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView = UIImageView(image: UIImage.init(named: "img.jpg"))
        self.view.addSubview(imageView)
        imageView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.view)
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
Morty Choi
  • 373
  • 2
  • 10

2 Answers2

0

In the fact, you have to import SnapKit whenever you use it directly in a Swift file. You can't use it unless you import it.

In another hand, if other framework already import SnapKit, you don't need to import it again.

i.e: In swift standard lib.

If you want to use Foundation, you should import Foundation. If you import UIKit, you don't need to import Foundation, because UIKit already had import Foundation

Huy Le
  • 2,503
  • 1
  • 15
  • 15
0

This i because that the import statement in Swift works very differently from other languages like Python and Java. And let me clarify some terminology here, what you import is called a "module", not a framework.

In Swift, some modules import other modules. e.g. The UIKit module imports Foundation. So when you import UIKit, you don't need to import Foundation anymore. Because UIKit already imports it.

So in your case, you always have to import SnapKit in your swift file in order to use the stuff in it, just like the Foundation example. However, if you import another module that imports SnapKit, (I don't know anything about this so) let's call it MyKit. You just need to write

import MyKit

to use all the stuff in SnapKit and MyKit!

In short, some modules import other ones. This is why you sometimes can omit imports.

Sweeper
  • 213,210
  • 22
  • 193
  • 313