Coder Social home page Coder Social logo

yonat / sweeterswift Goto Github PK

View Code? Open in Web Editor NEW
11.0 2.0 12.0 85 KB

Extensions and syntactic sugar to enrich the Swift standard library, iOS frameworks, and SwifterSwift.

License: MIT License

Swift 89.56% Ruby 8.71% Objective-C 1.73%
cocoapods swift swift-extensions ios swifterswift uikit swift-library syntactic-sugar

sweeterswift's Introduction

SweeterSwift

Swift Version Build Status License CocoaPods Compatible
Platform PRs Welcome

Extensions and syntactic sugar to enrich the Swift standard library, iOS frameworks, and SwifterSwift.

Installation

CocoaPods:

pod 'SweeterSwift'

Swift Package Manager:

dependencies: [
    .package(url: "https://github.com/yonat/SweeterSwift", from: "1.2.5")
]

Usage

Auto Layout

Add button at the center of view:

view.addConstrainedSubview(button, constrain: .centerX, .centerY)

Put label over textField:

view.constrain(label, at: .leading, to: textField)
view.constrain(textField, at: .top, to: label, at: .bottom, diff: 8)

Add child view controller covering all but the bottom margin:

addConstrainedChild(vc, constrain: .bottomMargin, .top, .left, .right)

Bundle

App name with reasonable fallback to process name:

let appName = Bundle.main.name

App info string with name, version, and build number:

let appInfo = Bundle.main.infoString // "MyApp 1.0 #42"

Codable

Create object from a dictionary:

let decodableObject = MyDecodableClass(dictionary: aDictionary)

Export object to a dictionary:

let aDictionary = encodableObject.dictionary

DateFormatter

Create with format:

let dateFormatter = DateFormatter(format: "cccc, MMMM dd")

NotificationCenter

Post a local notification using NotificationCenter.default:

notify(notificationName, userInfo: infoDictionary)

Respond to a local notification from NotificationCenter.default:

observeNotification(notificationName, selector: #selector(someFunc))

NSAttributedString

Create from HTML:

let attributedString = NSAttributedString(htmlString: "Hello, <b>world</b>!")

Turn a substring into a link:

mutableAttributedString.link(anchorText: "Hello", url: "https://ootips.org")

NSManagedObjectContext

Dump contents to console for debugging:

managedObjectContext.printAllObjects()

Create a copy of the store for backup or for using later as initial setup:

managedObjectContext.backupStore()

String

Separate CamelCase into capitalized words:

let words = "winterIsComing".unCamelCased // "Winter Is Coming"

Change CamelCase into snake_case:

let key = "winterIsComing".camelToSnakeCased // "winter_is_coming"

Swift Standard Library

Index of current enum case in allCases:

let index = MyEnum.someCase.index

Unwrap collection, shorthand for compactMap { $0 }:

let nonOptionals = optionalsCollection.compact

Avoid retain cycles when passing a member function as an @escaping closure:

var closure = weak(self, in: MyClass.someFunction)

TimeInterval

Standard time intervals:

let myInterval: TimeInterval = .year + .month + .week + .day + .hour + .minute

UIApplication

Find the top-most view controller:

let topVC = UIApplication.topViewController()

Present modal over the top view controller:

UIApplication.present(modalVC)

UILabel / UITextView

Create a label with links by using a UITextView to auto-detect links and simulate UILabel appearance:

let hyperlinkedLabel = UITextView(simulatedLabelWithLinksInText: "More at https://ootips.org")

UIStackView

Remove an arranged subview from the view hierarchy, not just the stack arrangement:

stackView.removeArrangedSubviewCompletely(subview)

Remove all arranged subviews from the view hierarchy, not just the stack arrangement:

stackView.removeAllArrangedSubviewsCompletely()

UIView

Search the view hierarchy recursively for a subview that meets a condition:

let blueSubview = view.viewInHierarchy(where { $0.backgroundColor == .blue })

Search the view hierarchy recursively for a subview with a specific class:

let button = view.viewWithClass(UIButton.self)

Meta

@yonatsharon

https://github.com/yonat/SweeterSwift

sweeterswift's People

Contributors

mcomisso avatar yonat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

sweeterswift's Issues

Foundation import needed

Cannot compile when used as a dependency in a project.
Swift+Sweeter.swift recently added some references to "IndexSet" and "CharacterSet" which are not native swift types, and are declared in Foundation.

Adding:
import Foundation
to the top of the file fixes the issue.

crash going from 1.0.5 to 1.1.0, fatal error use of unimplemented initializer 'init()' for class

Description of the problem:
[description]
weird crashes in working code after going from 1.0.5 to 1.1.0
-- e.g. crash in a class, fatal error use of unimplemented initializer 'init()' for class

Verified that it's this pod. going back to 1.0.5 on a single pod fixes issues. There were no code changes between - just updates on the pod.

Minimal project that reproduces the problem (so I'll be able to figure out how to fix it):
[github repo or a zipped project]

This class worked fine before:

class MyThread: Thread {
init(param1: Int = 1, param2 : Int = 1) {
super.init()
// init code
}

final override func main() {
// do stuff
}
}

calling this in appDelegate as let t = MyThread() causes the crash.
fatal error use of unimplemented initializer 'init()' for class MyThread

Build error when import with SPM

When import with lib: MultiSlider with SPM
Error in file : UITextView+Sweeter.swift :

  • 'labelFontSize' is unavailable in tvOS
  • 'isEditable' is unavailable in tvOS
  • 'dataDetectorTypes' is unavailable in tvOS

used version : 1.1.2
target: only iOS

Runtime error upon startup on iOS 14 devices when compiled with Xcode 13.3+

(Copied from yonat/MultiSelectSegmentedControl#50 for reference)

Description of the problem:
This module has been very helpful for me and my project, but starting with Xcode 13.3, I began receiving many reports from iOS 14 users stating that my app had begun crashing immediately at startup, and this module has been identified as the culprit. More specifically, the issue is in the SweeterSwift dependency which this package relies on.

My colleague forked the SweeterSwift package to devise a workaround here: https://github.com/zabolotiny/SweeterSwift

Similarly, I can see another fork of this dependency has been created by another user ( @Janek-CL ) that claims to fix the issue in a different way: https://github.com/CONVELOP-GbR/SweeterSwift

Cannot compile when an extension is present.

Imported as a part of MultiSelectSegmentedControl install, my project has an extension.

I try to build the project and I get this error on the file "UIApplication+Sweeter.swift":

'shared' is unavailable in application extensions for iOS: Use view controller based solutions where appropriate instead.

This occurs on line 11:

public class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

Codable+Sweeter Overloading Breaks Implementations

Description of the problem:

Hi,

we just evaluated using your library "MultiSelectSegmentedControl". After implementing it we suddenly noticed some crashes which we could trace back to the extension included in this library Codable+Sweeter.

In this file you're overloading Decodable with a new init:

extension Decodable {
    /// Sweeter: Create object from a dictionary
    public init?(from: Any) {
        guard let data = try? JSONSerialization.data(withJSONObject: from, options: .prettyPrinted) else { return nil }
        guard let decodedSelf = try? JSONDecoder().decode(Self.self, from: data) else { return nil }
        self = decodedSelf
    }
}

As you're overloading the init with type from: Any this is being used unintentionally by other implementations.

For example, we're also using the library R.swift which generates the following line to use when passing arguments to translations:

fileprivate static let applicationLocale = hostingBundle.preferredLocalizations.first.flatMap(Locale.init) ?? Locale.current

After adding your Library this line (Locale.init in particular) is using your overloaded init instead of the default Codable one. And this causes the app to crash as, of course, this is not passing any valid JSON as an argument.

Normally it should use

extension Locale : Codable {
    /// Creates a new instance by decoding from the given decoder.
    ///
    /// This initializer throws an error if reading from the decoder fails, or
    /// if the data read is corrupted or otherwise invalid.
    ///
    /// - Parameter decoder: The decoder to read data from.
    public init(from decoder: Decoder) throws

    /// Encodes this value into the given encoder.
    ///
    /// If the value fails to encode anything, `encoder` will encode an empty
    /// keyed container in its place.
    ///
    /// This function throws an error if any values are invalid for the given
    /// encoder's format.
    ///
    /// - Parameter encoder: The encoder to write data to.
    public func encode(to encoder: Encoder) throws
}

I guess in general it is pretty dangerous to overload something with type Any but maybe this can also be fixed by using another Keyword instead of from:.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.