{"id":15066933,"url":"https://github.com/anscoder/swift-extension","last_synced_at":"2026-04-04T13:39:46.629Z","repository":{"id":103901886,"uuid":"119167824","full_name":"ANSCoder/Swift-Extension","owner":"ANSCoder","description":"Swift-Extension Files for easy to use in Swift 4.0 version. Need to download file and drag and drop in your Xcode Project.","archived":false,"fork":false,"pushed_at":"2018-10-14T18:10:22.000Z","size":69,"stargazers_count":11,"open_issues_count":0,"forks_count":6,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-24T12:39:24.745Z","etag":null,"topics":["alertviewcontroller","date-extension","extension","hex-color","navigationbar","scrollview-component","string","stringextension","swift","swift-4","swift-library","swift4","swiftextension","textfield","uiview-extension"],"latest_commit_sha":null,"homepage":null,"language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ANSCoder.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-01-27T13:42:14.000Z","updated_at":"2024-07-19T07:46:28.000Z","dependencies_parsed_at":null,"dependency_job_id":"b50b5665-1afb-4d49-a6ad-9fcd4f4a8b52","html_url":"https://github.com/ANSCoder/Swift-Extension","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ANSCoder%2FSwift-Extension","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ANSCoder%2FSwift-Extension/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ANSCoder%2FSwift-Extension/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ANSCoder%2FSwift-Extension/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ANSCoder","download_url":"https://codeload.github.com/ANSCoder/Swift-Extension/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248229315,"owners_count":21068875,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["alertviewcontroller","date-extension","extension","hex-color","navigationbar","scrollview-component","string","stringextension","swift","swift-4","swift-library","swift4","swiftextension","textfield","uiview-extension"],"created_at":"2024-09-25T01:14:04.931Z","updated_at":"2026-04-04T13:39:46.586Z","avatar_url":"https://github.com/ANSCoder.png","language":"Swift","readme":"# Swift-Extension\n\nSwift-Extension Files for easy to use in **Swift 4.1** version. Need to download file and drag and drop in your Xcode Project.\n\n# Documentation \n\n[Check here.](https://anscoder.github.io/Swift-Extension/)\n\n# Installation\n\nDrag and drop [Extension](https://github.com/ANSCoder/Swift-Extension/tree/master/Swift-Extension/Extensions) folder inside your project and use it.\n\nOr directly you can copy and paste inside your class. 🚀\n\n### Contents  🎉\n \n - **Array**\n \n ```swift\n extension Array {\n    func atIndex(_ index: Int) -\u003e Element? {\n        if index \u003c 0 || index \u003e self.count - 1 {\n            return nil\n        }\n        return self[index]\n    }\n}\n```\n \n - **UILabel**\n \n ```swift\n extension UILabel{\n    \n    func setLeft(){\n        self.textAlignment = .left\n    }\n    \n    func setRight(){\n        self.textAlignment = .right\n    }\n    \n    func attribute(_ with: String, effect: String){\n        let mainString = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont(name: self.font.fontName, size: self.font.pointSize)!]\n        let effectString = [NSAttributedStringKey.foregroundColor: UIColor.black, NSAttributedStringKey.font: UIFont.systemFont(ofSize: self.font.pointSize)]\n        \n        let partOne = NSMutableAttributedString(string: with, attributes: mainString)\n        let partTwo = NSMutableAttributedString(string: effect, attributes: effectString)\n        \n        let combination = NSMutableAttributedString()\n        combination.append(partOne)\n        combination.append(partTwo)\n        self.attributedText = combination\n    }\n    \n    func underline() {\n        if let textString = self.text {\n            let attributedString = NSMutableAttributedString(string: textString)\n            attributedString.addAttribute(NSAttributedStringKey.underlineStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: attributedString.length))\n            attributedText = attributedString\n        }\n    }\n}\n ```\n \n - **UIViewController**\n \n ```swift\n extension UIViewController{\n    \n    //MARK:- Aleart View\n    func showAleartViewwithTitle(_ title: String, message: String) {\n        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)\n        alert.addAction(UIAlertAction(title: \"Ok\", style: UIAlertActionStyle.default, handler: nil))\n        self.present(alert, animated: true, completion: nil)\n    }\n    \n    func showAlertWithMessage(_ message: String, with completion: (() -\u003e Void)?){\n        let alertController = UIAlertController(title: \"Message\", message: message, preferredStyle: .alert)\n        self.present(alertController, animated: true, completion: nil)\n        let delay = 3.0 * Double(NSEC_PER_SEC)\n        let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)\n        DispatchQueue.main.asyncAfter(deadline: time, execute: {\n            alertController.dismiss(animated: true, completion: nil)\n            completion?()\n        })\n    }\n    \n}\n ```\n - **UIScrollView**\n \n ```swift\n extension UIScrollView {\n    \n    // Scroll to a specific view so that it's top is at the top our scrollview\n    func scrollToView(view:UIView, animated: Bool) {\n        if let origin = view.superview {\n            UIView.animate(withDuration: 0.4, animations: {\n                // Get the Y position of your child view\n                let childStartPoint = origin.convert(view.frame.origin, to: self)\n                // Scroll to a rectangle starting at the Y of your subview, with a height of the scrollview\n                self.scrollRectToVisible(CGRect(x:0, y:childStartPoint.y, width:1, height:self.frame.height), animated: animated)\n            })\n        }\n    }\n    \n    // Bonus: Scroll to top\n    func scrollToTop(animated: Bool) {\n        let topOffset = CGPoint(x: 0, y: -contentInset.top)\n        setContentOffset(topOffset, animated: animated)\n    }\n    \n    // Bonus: Scroll to bottom\n    func scrollToBottom() {\n        let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)\n        if(bottomOffset.y \u003e 0) {\n            setContentOffset(bottomOffset, animated: true)\n        }\n    }\n}\n ```\n - **UINavigationBar**\n \n ```swift\n public extension UINavigationBar {\n    \n    /// SwifterSwift: Set Navigation Bar title, title color and font.\n    ///\n    /// - Parameters:\n    ///   - font: title font\n    ///   - color: title text color (default is .black).\n    public func setTitleFont(_ font: UIFont, color: UIColor = .black) {\n        var attrs = [NSAttributedStringKey: Any]()\n        attrs[.font] = font\n        attrs[.foregroundColor] = color\n        titleTextAttributes = attrs\n    }\n    \n    /// SwifterSwift: Make navigation bar transparent.\n    ///\n    /// - Parameter tint: tint color (default is .white).\n    public func makeTransparent(withTint tint: UIColor = .white) {\n        isTranslucent = true\n        backgroundColor = .clear\n        barTintColor = .clear\n        setBackgroundImage(UIImage(), for: .default)\n        tintColor = tint\n        titleTextAttributes = [.foregroundColor: tint]\n        shadowImage = UIImage()\n    }\n    \n    /// SwifterSwift: Set navigationBar background and text colors\n    ///\n    /// - Parameters:\n    ///   - background: backgound color\n    ///   - text: text color\n    public func setColors(background: UIColor, text: UIColor) {\n        isTranslucent = false\n        backgroundColor = background\n        barTintColor = background\n        setBackgroundImage(UIImage(), for: .default)\n        tintColor = text\n        titleTextAttributes = [.foregroundColor: text]\n    }\n}\n ```\n - **String**\n \n ```swift\n extension String {\n    \n    public var isNotEmpty: Bool {\n        return !isEmpty\n    }\n    \n    var trim: String {\n        if self.isNotEmpty {\n            return self.trimmingCharacters(in: CharacterSet.whitespaces)\n        }else{\n            return \"\"\n        }\n    }\n    \n    var trimLine: String {\n        if self.isNotEmpty {\n            return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)\n        }else{\n            return \"\"\n        }\n    }\n    \n    var isAlphanumeric: Bool {\n        return !isEmpty \u0026\u0026 range(of: \"[^a-zA-Z0-9]\", options: .regularExpression) == nil\n    }\n    \n    var isEmail: Bool {\n        guard !self.isEmpty else{\n            return false\n        }\n        let emailRegex: String = \"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,4}\"\n        let emailTest = NSPredicate(format: \"SELF MATCHES %@\", emailRegex)\n        return emailTest.evaluate(with: self)\n    }\n    \n    var isMobile: Bool {\n        guard !self.isEmpty else{\n            return false\n        }\n        let phoneRegix = \"[123456789][0-9]{8}([0-9]{1})?\"\n        let phoneTest = NSPredicate(format: \"SELF MATCHES %@\", phoneRegix)\n        return phoneTest.evaluate(with: self)\n    }\n    \n    func changeDate(_ mydate:String) -\u003e String {\n        let dateFormatter = DateFormatter()\n        dateFormatter.dateStyle = DateFormatter.Style.long\n        dateFormatter.dateFormat = \"yyyy/M/dd\"\n        let convertedDate = dateFormatter.date(from: mydate)\n        dateFormatter.dateFormat = \"MMMM dd, yyyy\"\n        let date = dateFormatter.string(from: convertedDate!)\n        return date\n    }\n    \n    //MARK : - For First Capital letter of String\n    private func capitalizingFirstLetter() -\u003e String {\n        let first = String(self.prefix(1)).capitalized\n        let other = String(self.dropFirst())\n        return first + other\n    }\n    \n    mutating func capitalizeFirstLetter() {\n        self = self.capitalizingFirstLetter()\n    }\n    \n    func trimWhiteSpace() -\u003e String {\n        return self.trimmingCharacters(in: .whitespaces)\n    }\n    \n    //MARK: - Removing space from String\n    var removeSpace: String {\n        if self.isNotEmpty {\n            return self.components(separatedBy: .whitespaces).joined()\n        }else{\n            return \"\"\n        }\n    }\n}\n ```\n - **UITextField**\n \n ```swift\n extension UITextField {\n    \n    func setBorderAndCorner(){\n        DispatchQueue.main.async {\n            self.layer.borderWidth = 1.0\n            self.layer.borderColor = ExFunction.hexStringToUIColor(hex: \"61906B\").cgColor\n            self.layer.cornerRadius = 5\n        }\n    }\n    \n    func setLeftPaddingPoints(_ amount:CGFloat){\n        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))\n        self.leftView = paddingView\n        self.leftViewMode = .always\n    }\n    \n    func setRightPaddingPoints(_ amount:CGFloat) {\n        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))\n        self.rightView = paddingView\n        self.rightViewMode = .always\n    }\n    \n    var isValidEmail: Bool {\n        let emailRegEx = \"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,64}\"\n        let emailTest = NSPredicate(format:\"SELF MATCHES %@\", emailRegEx)\n        return emailTest.evaluate(with: self.text ?? \"\")\n    }\n    \n    var isPhoneNumber: Bool {\n        do {\n            let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)\n            let matches = detector.matches(in: self.text ?? \"\", options: [], range: NSMakeRange(0, (self.text ?? \"\").count))\n            if let res = matches.first {\n                return res.resultType == .phoneNumber \u0026\u0026 res.range.location == 0 \u0026\u0026 res.range.length == (self.text ?? \"\").count \u0026\u0026 (self.text ?? \"\").count == 10\n            } else {\n                return false\n            }\n        } catch {\n            return false\n        }\n    }\n}\n ```\n - **Date**\n \n ```swift\n extension Date {\n    func toString() -\u003e String {\n        let dateFormatter = DateFormatter()\n        dateFormatter.dateFormat = \"dd-MM-yyyy\"\n        return dateFormatter.string(from: self)\n    }\n    func toTimeString() -\u003e String {\n        let dateFormatter = DateFormatter()\n        dateFormatter.dateFormat = \"HH:mm\"\n        return dateFormatter.string(from: self)\n    }\n}\n ```\n - **NSMutableAttributedString**\n \n ```swift\n extension NSMutableAttributedString {\n    \n    @discardableResult\n    func bold(_ text: String) -\u003e NSMutableAttributedString {\n        let attrs = [NSAttributedStringKey.font : UIFont(name: \"AvenirNext-Medium\", size: 12)!]\n        let boldString = NSMutableAttributedString(string: text, attributes: attrs)\n        self.append(boldString)\n        return self\n    }\n    \n    @discardableResult\n    func normal(_ text:String)-\u003eNSMutableAttributedString {\n        let normal =  NSAttributedString(string: text)\n        self.append(normal)\n        return self\n    }\n}\n ```\n - **UIColor (HEX)**\n \n ```swift\n  extension UIColor {\n    convenience init(hex: String) {\n        \n        let scanner = Scanner(string: hex)\n        scanner.scanLocation = 0\n        \n        var rgbValue: UInt64 = 0\n        \n        scanner.scanHexInt64(\u0026rgbValue)\n        \n        let r = (rgbValue \u0026 0xff0000) \u003e\u003e 16\n        let g = (rgbValue \u0026 0xff00) \u003e\u003e 8\n        let b = rgbValue \u0026 0xff\n        \n        self.init(\n            red: CGFloat(r) / 0xff,\n            green: CGFloat(g) / 0xff,\n            blue: CGFloat(b) / 0xff, alpha: 1\n        )\n    }\n}\n ```\n \n - **UIImage**\n \n ```swift\n extension UIImage {\n    \n    var toBase64String:String {\n        let imageData = UIImagePNGRepresentation(self)\n        return imageData!.base64EncodedString(options: .lineLength64Characters)\n    }\n    \n    // Return half- Size version of Current image\n    var halfSizeImage: UIImage? {\n        \n//        let halfWidth = 250\n//        let halfHeight = 250\n        \n       let halfWidth = self.size.width / 2\n       let halfHeight = self.size.height / 2\n        \n        UIGraphicsBeginImageContext(CGSize(width: halfWidth, height: halfHeight))\n        \n        self.draw(in: CGRect(x: 0, y: 0, width: halfWidth, height: halfHeight))\n        \n        let image = UIGraphicsGetImageFromCurrentImageContext()\n        \n        UIGraphicsEndImageContext()\n        \n        return image\n    }\n    \n    // Return Quarter- Size version of Current image\n    var quarterhalfSizeImage:UIImage? {\n        \n        let halfWidth = self.size.width / 4\n        let halfHeight = self.size.height / 4\n        \n        UIGraphicsBeginImageContext(CGSize(width: halfWidth, height: halfHeight))\n        \n        self.draw(in: CGRect(x: 0, y: 0, width: halfWidth, height: halfHeight))\n        \n        let image = UIGraphicsGetImageFromCurrentImageContext()\n        \n        UIGraphicsEndImageContext()\n        \n        return image\n    }\n    \n    \n    //Loading Image From Document Directory\n    func loadImageFromDocumentDirPath(_ path: String) -\u003e UIImage? {\n        let data = try? Data(contentsOf: URL(fileURLWithPath: path))\n        if (data != nil){\n            let image = UIImage(data: data!)\n            return image\n        }else{\n            return nil\n        }\n    }\n    \n}\n ```\n - **UIImageView**\n \n ```swift\n extension UIImageView {\n    \n    func setRounded() {\n        let radius = self.frame.width / 2\n        self.layer.cornerRadius = radius\n        self.layer.masksToBounds = true\n    }\n    \n    func setCornerRadious() {\n        let radius = self.frame.height / 20\n        self.layer.cornerRadius = radius\n        self.layer.masksToBounds = true\n    }\n}\n ```\n - **ExFunction (Public functions for String to Dictionary \u0026 Dictionary to String)**\n \n ```swift\n public struct ExFunction {\n    \n    //MARK:- String to Dictionary Conversion\n    static func convertStringToDictionary(_ json: String) -\u003e [String: Any] {\n        if let data = json.data(using: String.Encoding.utf8) {\n            do{\n                let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String: Any]\n                return json ?? [:]\n            }catch{\n                print(error)\n            }\n        }\n        return [:]\n    }\n    \n    static func getRawJSON(from dictionary:[String: Any]) -\u003e String{\n        guard let theJSONData = try? JSONSerialization.data(withJSONObject: dictionary, options: []) else {\n            //Handle Error here\n            return \"\"\n        }\n        let jsonString = String(data: theJSONData, encoding: .ascii) ?? \"\"\n        return jsonString\n    }\n    \n    static func hexStringToUIColor(hex:String) -\u003e UIColor {\n        \n        var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()\n        \n        if (cString.hasPrefix(\"#\")) {\n            cString.remove(at: cString.startIndex)\n        }\n        \n        if ((cString.count) != 6) {\n            return UIColor.gray\n        }\n        \n        var rgbValue:UInt32 = 0\n        Scanner(string: cString).scanHexInt32(\u0026rgbValue)\n        \n        return UIColor(\n            red: CGFloat((rgbValue \u0026 0xFF0000) \u003e\u003e 16) / 255.0,\n            green: CGFloat((rgbValue \u0026 0x00FF00) \u003e\u003e 8) / 255.0,\n            blue: CGFloat(rgbValue \u0026 0x0000FF) / 255.0,\n            alpha: CGFloat(1.0)\n        )\n    }\n}\n ```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanscoder%2Fswift-extension","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fanscoder%2Fswift-extension","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fanscoder%2Fswift-extension/lists"}