label
int64
0
1
text
stringlengths
0
2.8M
0
// // ImageStyle.swift // ExpertChow // // Created by Adam Sterrett on 3/11/21. // import Foundation import UIKit enum ImageType: Int, CaseIterable { case arrowBack case closeButton func imageName() -> String { var imageName = "" switch self { case .arrowBack: imageName = "Icon-Back" case .closeButton: imageName = "Icon-Close" } return imageName } func image() -> UIImage { let imageName = self.imageName() return UIImage(named: imageName) ?? UIImage() } func tintableImage() -> UIImage { return self.image().withRenderingMode(.alwaysTemplate) } }
0
// // CodeSystems.swift // HealthRecords // // Generated from FHIR 4.0.1-9346c8cc45 // Copyright 2022 Apple Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import FMCore /** This value set includes a smattering of Adjudication Value codes which includes codes to indicate the amounts eligible under the plan, the amount of benefit, copays etc. URL: http://terminology.hl7.org/CodeSystem/adjudication ValueSet: http://hl7.org/fhir/ValueSet/adjudication */ public enum AdjudicationValueCodes: String, FHIRPrimitiveType { /// The total submitted amount for the claim or group or line item. case submitted /// Patient Co-Payment case copay /// Amount of the change which is considered for adjudication. case eligible /// Amount deducted from the eligible amount prior to adjudication. case deductible /// The amount of deductible which could not allocated to other line items. case unallocdeduct /// Eligible Percentage. case eligpercent /// The amount of tax. case tax /// Amount payable under the coverage case benefit }
0
// // RanchForecastUITests.swift // RanchForecastUITests // // Created by Hanguang on 1/2/16. // Copyright © 2016 Hanguang. All rights reserved. // import XCTest class RanchForecastUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
0
// // EitherType+Result.swift // Lustre // // Created by Zachary Waldowski on 7/25/15. // Copyright © 2014-2015. Some rights reserved. // extension EitherType where LeftType == Error { public var isSuccess: Bool { return isRight } public var isFailure: Bool { return isLeft } public var error: LeftType? { return left } public var value: RightType? { return right } } // MARK: Throws compatibility extension EitherType where LeftType == Error { public init(_ fn: () throws -> RightType) { do { self.init(right: try fn()) } catch { self.init(left: error) } } public func extract() throws -> RightType { var error: LeftType! guard let value = analysis(ifLeft: { error = $0; return .none }, ifRight: { $0 }) as RightType? else { throw error } return value } } // MARK: Value recovery extension EitherType where LeftType == Error { public init(_ value: RightType?, failWith: @autoclosure () -> LeftType) { if let value = value { self.init(right: value) } else { self.init(left: failWith()) } } public func recover(_ fallbackValue: @autoclosure () -> RightType) -> RightType { return analysis(ifLeft: { _ in fallbackValue() }, ifRight: { $0 }) } } public func ??<Either: EitherType>(lhs: Either, rhs: @autoclosure () -> Either.RightType) -> Either.RightType where Either.LeftType == Error { return lhs.recover(rhs()) } // MARK: Result equatability extension Error { public func matches(_ other: Error) -> Bool { return (self as NSError) == (other as NSError) } } public func ==<LeftEither: EitherType, RightEither: EitherType>(lhs: LeftEither, rhs: RightEither) -> Bool where LeftEither.LeftType == Error, RightEither.LeftType == Error, LeftEither.RightType: Equatable, RightEither.RightType == LeftEither.RightType { return lhs.equals(rhs, leftEqual: { $0.matches($1) }, rightEqual: ==) } public func !=<LeftEither: EitherType, RightEither: EitherType>(lhs: LeftEither, rhs: RightEither) -> Bool where LeftEither.LeftType == Error, RightEither.LeftType == Error, LeftEither.RightType: Equatable, RightEither.RightType == LeftEither.RightType { return !(lhs == rhs) } public func ==<LeftEither: EitherType, RightEither: EitherType>(lhs: LeftEither, rhs: RightEither) -> Bool where LeftEither.LeftType == Error, RightEither.LeftType == Error, LeftEither.RightType == Void, RightEither.RightType == Void { return lhs.equals(rhs, leftEqual: { $0.matches($1) }, rightEqual: { _ in true }) } public func !=<LeftEither: EitherType, RightEither: EitherType>(lhs: LeftEither, rhs: RightEither) -> Bool where LeftEither.LeftType == Error, RightEither.LeftType == Error, LeftEither.RightType == Void, RightEither.RightType == Void { return !(lhs == rhs) }
0
// // 🦠 Corona-Warn-App // import Foundation import UIKit protocol ENANavigationControllerWithFooterChild: UIViewController { var footerView: ENANavigationFooterView? { get } func navigationController(_ navigationController: ENANavigationControllerWithFooter, didTapPrimaryButton button: UIButton) func navigationController(_ navigationController: ENANavigationControllerWithFooter, didTapSecondaryButton button: UIButton) } extension ENANavigationControllerWithFooterChild { var navigationControllerWithFooter: ENANavigationControllerWithFooter? { navigationController as? ENANavigationControllerWithFooter } var navigationFooterItem: ENANavigationFooterItem? { navigationItem as? ENANavigationFooterItem } var footerView: ENANavigationFooterView? { navigationControllerWithFooter?.footerView } func navigationController(_ navigationController: ENANavigationControllerWithFooter, didTapPrimaryButton button: UIButton) { } func navigationController(_ navigationController: ENANavigationControllerWithFooter, didTapSecondaryButton button: UIButton) { } }
0
// // Entity.swift // Example // // Created by Luciano Polit on 11/14/17. // Copyright © 2017 Luciano Polit. All rights reserved. // import Foundation @testable import Leash struct PrimitiveEntity: Codable, Equatable { let first: String let second: Int let third: Bool func toJSON() -> [String: Any] { return [ "first": first, "second": second, "third": third ] } } func == (lhs: PrimitiveEntity, rhs: PrimitiveEntity) -> Bool { return lhs.first == rhs.first && lhs.second == rhs.second && lhs.third == rhs.third } struct DatedEntity: Codable, Equatable { let date: Date } func == (lhs: DatedEntity, rhs: DatedEntity) -> Bool { return lhs.date == rhs.date } struct QueryEntity: QueryEncodable { let first: String let second: Int let third: Bool func toQuery() -> [String: CustomStringConvertible] { return [ "first": first, "second": second, "third": third ] } }
0
// // ViewController.swift // ScrollerTest // // Created by Andreas Verhoeven on 08/03/2021. // import UIKit class ViewController: UITableViewController { var itemHeights = Array<CGFloat>() func reload() { itemHeights = (0..<3000).map { _ in CGFloat(Int.random(in: 40..<150)) } tableView.reloadData() } func scroll(usesUIKit: Bool) { let row = Int.random(in: 0..<itemHeights.count) if usesUIKit == true { tableView.scrollToRow(at: IndexPath(row: row, section: 0), at: .top, animated: true) } else { print("Started Scrolling") tableView.reallyScrollToRow(at: IndexPath(row: row, section: 0), at: .top, animated: true, completion: { tableView, completed in if completed == true { print("Finished Scrolling") } else { print("Interrupted Scrolling") } }) } title = "scrolled to: \(row)" } override func viewDidLoad() { super.viewDidLoad() tableView.register(CustomHeightCell.self, forCellReuseIdentifier: "Cell") tableView.estimatedRowHeight = 10 tableView.rowHeight = UITableView.automaticDimension let scrollBarButtonItem = UIBarButtonItem(title: "Scroll", style: .plain, target: nil, action: nil) scrollBarButtonItem.menu = UIMenu(title: "", children: [ UIAction(title: "UIKit Scrolling", handler: { [weak self] _ in self?.scroll(usesUIKit: true) }), UIAction(title: "Improved Scrolling", handler: { [weak self] _ in self?.scroll(usesUIKit: false) }) ]) let reloadBarButtonItem = UIBarButtonItem(systemItem: .refresh, primaryAction: UIAction(handler: { [weak self] _ in self?.reload() })) navigationItem.rightBarButtonItems = [ reloadBarButtonItem, scrollBarButtonItem, ] reload() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemHeights.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomHeightCell let height = itemHeights[indexPath.row] cell.customHeight = height cell.textLabel?.text = "row \(indexPath.row), height = \(height)" return cell } } class CustomHeightCell: UITableViewCell { var customHeight: CGFloat? override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize { var size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority) customHeight.map { size.height = $0 } return size } }
0
/// A sequence that maps the base elements using `transform` and stops /// when the transform returns `nil`. public struct MapWhileSequence<Base: Sequence, A> { internal let base: Base internal let transform: (Base.Element) -> A? } extension MapWhileSequence { /// An iterator that provides mapped elements until it provides `nil` public struct Iterator { internal var base: Base.Iterator internal let transform: (Base.Element) -> A? } } extension MapWhileSequence.Iterator: IteratorProtocol { public mutating func next() -> A? { base.next().flatMap(transform) } } extension MapWhileSequence: Sequence { public func makeIterator() -> Iterator { Iterator(base: base.makeIterator(), transform: transform) } } extension MapWhileSequence: LazySequenceProtocol {} extension Sequence { /// Returns a `MapWhileSequence` /// /// - Parameter transform: /// A transformation that maps `Self.Element` to an A? /// /// - Note: /// The transform will be called _n + 1_ times where /// _n_ is the number of elements that return non-optional /// values. public func mapWhile<A>( _ transform: @escaping (Self.Element) -> A? ) -> MapWhileSequence<Self, A> { MapWhileSequence(base: self, transform: transform) } }
0
// CredentialsManager.swift // // Copyright (c) 2017 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import SimpleKeychain #if os(iOS) import LocalAuthentication #endif /// Credentials management utility public struct CredentialsManager { private let storage = A0SimpleKeychain() private let storeKey: String private let authentication: Authentication #if os(iOS) private var bioAuth: BioAuthentication? #endif /// Creates a new CredentialsManager instance /// /// - Parameters: /// - authentication: Auth0 authentication instance /// - storeKey: Key used to store user credentials in the keychain, defaults to "credentials" public init(authentication: Authentication, storeKey: String = "credentials") { self.storeKey = storeKey self.authentication = authentication } /// Enable Touch ID Authentication for additional security during credentials retrieval. /// /// - Parameters: /// - title: main message to display in TouchID prompt /// - cancelTitle: cancel message to display in TouchID prompt (iOS 10+) /// - fallbackTitle: fallback message to display in TouchID prompt after a failed match #if os(iOS) @available(*, deprecated, message: "see enableBiometrics(withTitle title:, cancelTitle:, fallbackTitle:)") public mutating func enableTouchAuth(withTitle title: String, cancelTitle: String? = nil, fallbackTitle: String? = nil) { self.enableBiometrics(withTitle: title, cancelTitle: cancelTitle, fallbackTitle: fallbackTitle) } #endif /// Enable Biometric Authentication for additional security during credentials retrieval. /// /// - Parameters: /// - title: main message to display when Touch ID is used /// - cancelTitle: cancel message to display when Touch ID is used (iOS 10+) /// - fallbackTitle: fallback message to display when Touch ID is used after a failed match #if os(iOS) public mutating func enableBiometrics(withTitle title: String, cancelTitle: String? = nil, fallbackTitle: String? = nil) { self.bioAuth = BioAuthentication(authContext: LAContext(), title: title, cancelTitle: cancelTitle, fallbackTitle: fallbackTitle) } #endif /// Store credentials instance in keychain /// /// - Parameter credentials: credentials instance to store /// - Returns: if credentials were stored public func store(credentials: Credentials) -> Bool { return self.storage.setData(NSKeyedArchiver.archivedData(withRootObject: credentials), forKey: storeKey) } /// Clear credentials stored in keychain /// /// - Returns: if credentials were removed public func clear() -> Bool { return self.storage.deleteEntry(forKey: storeKey) } /// Checks if a non-expired set of credentials are stored /// /// - Returns: if there are valid and non-expired credentials stored public func hasValid() -> Bool { guard let data = self.storage.data(forKey: self.storeKey), let credentials = NSKeyedUnarchiver.unarchiveObject(with: data) as? Credentials, credentials.accessToken != nil, let expiresIn = credentials.expiresIn else { return false } return expiresIn > Date() || credentials.refreshToken != nil } /// Retrieve credentials from keychain and yield new credentials using refreshToken if accessToken has expired /// otherwise the retrieved credentails will be returned as they have not expired. Renewed credentials will be /// stored in the keychain. /// /// /// ``` /// credentialsManager.credentials { /// guard $0 == nil else { return } /// print($1) /// } /// ``` /// /// - Parameters: /// - scope: scopes to request for the new tokens. By default is nil which will ask for the same ones requested during original Auth /// - callback: callback with the user's credentials or the cause of the error. /// - Important: This method only works for a refresh token obtained after auth with OAuth 2.0 API Authorization. /// - Note: [Auth0 Refresh Tokens Docs](https://auth0.com/docs/tokens/refresh-token) #if os(iOS) public func credentials(withScope scope: String? = nil, callback: @escaping (CredentialsManagerError?, Credentials?) -> Void) { guard self.hasValid() else { return callback(.noCredentials, nil) } if let bioAuth = self.bioAuth { guard bioAuth.available else { return callback(.touchFailed(LAError(LAError.touchIDNotAvailable)), nil) } bioAuth.validateBiometric { guard $0 == nil else { return callback(.touchFailed($0!), nil) } self.retrieveCredentials(withScope: scope, callback: callback) } } else { self.retrieveCredentials(withScope: scope, callback: callback) } } #else public func credentials(withScope scope: String? = nil, callback: @escaping (CredentialsManagerError?, Credentials?) -> Void) { guard self.hasValid() else { return callback(.noCredentials, nil) } self.retrieveCredentials(withScope: scope, callback: callback) } #endif private func retrieveCredentials(withScope scope: String? = nil, callback: @escaping (CredentialsManagerError?, Credentials?) -> Void) { guard let data = self.storage.data(forKey: self.storeKey), let credentials = NSKeyedUnarchiver.unarchiveObject(with: data) as? Credentials else { return callback(.noCredentials, nil) } guard let expiresIn = credentials.expiresIn else { return callback(.noCredentials, nil) } guard expiresIn < Date() else { return callback(nil, credentials) } guard let refreshToken = credentials.refreshToken else { return callback(.noRefreshToken, nil) } self.authentication.renew(withRefreshToken: refreshToken, scope: scope).start { switch $0 { case .success(let credentials): let newCredentials = Credentials(accessToken: credentials.accessToken, tokenType: credentials.tokenType, idToken: credentials.idToken, refreshToken: refreshToken, expiresIn: credentials.expiresIn, scope: credentials.scope) _ = self.store(credentials: newCredentials) callback(nil, newCredentials) case .failure(let error): callback(.failedRefresh(error), nil) } } } }
0
// // HQACellTopView.swift // HQSwiftMVVM // // Created by 王红庆 on 2017/8/28. // Copyright © 2017年 王红庆. All rights reserved. // import UIKit class HQACellTopView: UIView { var viewModel: HQStatusViewModel? { didSet { avatarImageView.hq_setImage(urlString: viewModel?.status.user?.profile_image_url, placeholderImage: UIImage(named: "avatar_default_big"), isAvatar: true) nameLabel.text = viewModel?.status.user?.screen_name memberIconView.image = viewModel?.memberIcon?.hq_rectImage(size: CGSize(width: 17, height: 17)) vipIconImageView.image = viewModel?.vipIcon } } fileprivate lazy var carveView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.hq_screenWidth(), height: 8)) view.backgroundColor = UIColor.hq_color(withHex: 0xF2F2F2) return view }() /// 头像 fileprivate lazy var avatarImageView: UIImageView = UIImageView(hq_imageName: "avatar_default_big") /// 姓名 fileprivate lazy var nameLabel: UILabel = UILabel(hq_title: "吴彦祖", fontSize: 14, color: UIColor.hq_color(withHex: 0xFC3E00)) /// 会员 fileprivate lazy var memberIconView: UIImageView = UIImageView(hq_imageName: "common_icon_membership_level1") /// 时间 fileprivate lazy var timeLabel: UILabel = UILabel(hq_title: "现在", fontSize: 11, color: UIColor.hq_color(withHex: 0xFF6C00)) /// 来源 fileprivate lazy var sourceLabel: UILabel = UILabel(hq_title: "来源", fontSize: 11, color: UIColor.hq_color(withHex: 0x828282)) /// 认证 fileprivate lazy var vipIconImageView: UIImageView = UIImageView(hq_imageName: "avatar_vip") override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UI extension HQACellTopView { fileprivate func setupUI() { addSubview(carveView) addSubview(avatarImageView) addSubview(nameLabel) addSubview(memberIconView) addSubview(timeLabel) addSubview(sourceLabel) addSubview(vipIconImageView) avatarImageView.snp.makeConstraints { (make) in make.top.equalTo(carveView.snp.bottom).offset(margin) make.left.equalTo(self).offset(12) make.width.equalTo(AvatarImageViewWidth) make.height.equalTo(AvatarImageViewWidth) } nameLabel.snp.makeConstraints { (make) in make.top.equalTo(avatarImageView).offset(4) make.left.equalTo(avatarImageView.snp.right).offset(margin - 4) } memberIconView.snp.makeConstraints { (make) in make.left.equalTo(nameLabel.snp.right).offset(margin / 2) make.centerY.equalTo(nameLabel) } timeLabel.snp.makeConstraints { (make) in make.left.equalTo(nameLabel) make.bottom.equalTo(avatarImageView) } sourceLabel.snp.makeConstraints { (make) in make.left.equalTo(timeLabel.snp.right).offset(margin / 2) make.centerY.equalTo(timeLabel) } vipIconImageView.snp.makeConstraints { (make) in make.centerX.equalTo(avatarImageView.snp.right).offset(-4) make.centerY.equalTo(avatarImageView.snp.bottom).offset(-4) } } }
0
// // RxCollectionViewCell.swift // RxSwift-Table-Collection // // Created by iOS_Tian on 2017/9/19. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit import Kingfisher class RxCollectionViewCell: UICollectionViewCell { @IBOutlet weak var headImage: UIImageView! @IBOutlet weak var focusLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! var anchorModel: AnchorModel? { didSet{ guard let model = anchorModel else { return } nameLabel.text = model.name focusLabel.text = "\(model.focus)人关注" headImage.kf.setImage(with: URL(string: model.pic51)) } } }
0
import Quick import Nimble import Stencil @testable import Sourcery class GeneratorSpec: QuickSpec { override func spec() { describe("Generator") { let fooType = Class(name: "Foo", variables: [Variable(name: "intValue", typeName: "Int")], inheritedTypes: ["NSObject", "Decodable", "AlternativeProtocol"]) let fooSubclassType = Class(name: "FooSubclass", inheritedTypes: ["Foo", "ProtocolBasedOnKnownProtocol"]) let barType = Struct(name: "Bar", inheritedTypes: ["KnownProtocol", "Decodable"]) let complexType = Struct(name: "Complex", accessLevel: .public, isExtension: false, variables: []) let fooVar = Variable(name: "foo", typeName: "Foo", accessLevel: (read: .public, write: .public), isComputed: false) fooVar.type = fooType let barVar = Variable(name: "bar", typeName: "Bar", accessLevel: (read: .public, write: .public), isComputed: false) barVar.type = barType complexType.variables = [ fooVar, barVar, Variable(name: "fooBar", typeName: "Int", isComputed: true) ] complexType.methods = [ Method(selectorName: "foo(some: Int)", parameters: [Method.Parameter(name: "some", typeName: "Int")]), Method(selectorName: "foo2(some: Int)", parameters: [Method.Parameter(name: "some", typeName: "Float")], isStatic: true), Method(selectorName: "foo3(some: Int)", parameters: [Method.Parameter(name: "some", typeName: "Int")], isClass: true) ] let types = [ fooType, fooSubclassType, complexType, barType, Enum(name: "Options", accessLevel: .public, inheritedTypes: ["KnownProtocol"], cases: [Enum.Case(name: "optionA"), Enum.Case(name: "optionB")], containedTypes: [ Type(name: "InnerOptions", accessLevel: .public, variables: [ Variable(name: "foo", typeName: "Int", accessLevel: (read: .public, write: .public), isComputed: false) ]) ]), Enum(name: "FooOptions", accessLevel: .public, inheritedTypes: ["Foo", "KnownProtocol"], rawType: "Foo", cases: [Enum.Case(name: "fooA"), Enum.Case(name: "fooB")]), Type(name: "NSObject", accessLevel: .none, isExtension: true, inheritedTypes: ["KnownProtocol"]), Class(name: "ProjectClass", accessLevel: .none), Class(name: "ProjectFooSubclass", inheritedTypes: ["FooSubclass"]), Protocol(name: "KnownProtocol", variables: [Variable(name: "protocolVariable", typeName: "Int", isComputed: true)]), Protocol(name: "AlternativeProtocol"), Protocol(name: "ProtocolBasedOnKnownProtocol", inheritedTypes: ["KnownProtocol"]) ] let arguments: [String: NSObject] = ["some": "value" as NSString, "number": NSNumber(value: Float(4))] func generate(_ template: String) -> String { let types = ParserComposer().uniqueTypes((types, [])) return (try? Generator.generate(types, template: StencilTemplate(templateString: template), arguments: arguments)) ?? "" } it("generates types.all by skipping protocols") { expect(generate("Found {{ types.all.count }} types")).to(equal("Found 9 types")) } it("generates types.protocols") { expect(generate("Found {{ types.protocols.count }} protocols")).to(equal("Found 3 protocols")) } it("generates types.classes") { expect(generate("Found {{ types.classes.count }} classes, first: {{ types.classes.first.name }}, second: {{ types.classes.last.name }}")).to(equal("Found 4 classes, first: Foo, second: ProjectFooSubclass")) } it("generates types.structs") { expect(generate("Found {{ types.structs.count }} structs, first: {{ types.structs.first.name }}")).to(equal("Found 2 structs, first: Bar")) } it("generates types.enums") { expect(generate("Found {{ types.enums.count }} enums, first: {{ types.enums.first.name }}")).to(equal("Found 2 enums, first: FooOptions")) } it("feeds types.implementing specific protocol") { expect(generate("Found {{ types.implementing.KnownProtocol.count }} types")).to(equal("Found 8 types")) expect(generate("Found {{ types.implementing.Decodable.count|default:\"0\" }} types")).to(equal("Found 0 types")) expect(generate("Found {{ types.implementing.Foo.count|default:\"0\" }} types")).to(equal("Found 0 types")) expect(generate("Found {{ types.implementing.NSObject.count|default:\"0\" }} types")).to(equal("Found 0 types")) expect(generate("Found {{ types.implementing.Bar.count|default:\"0\" }} types")).to(equal("Found 0 types")) } it("feeds types.inheriting specific class") { expect(generate("Found {{ types.inheriting.KnownProtocol.count|default:\"0\" }} types")).to(equal("Found 0 types")) expect(generate("Found {{ types.inheriting.Decodable.count|default:\"0\" }} types")).to(equal("Found 0 types")) expect(generate("Found {{ types.inheriting.Foo.count }} types")).to(equal("Found 2 types")) expect(generate("Found {{ types.inheriting.NSObject.count|default:\"0\" }} types")).to(equal("Found 0 types")) expect(generate("Found {{ types.inheriting.Bar.count|default:\"0\" }} types")).to(equal("Found 0 types")) } it("feeds types.based specific type or protocol") { expect(generate("Found {{ types.based.KnownProtocol.count }} types")).to(equal("Found 8 types")) expect(generate("Found {{ types.based.Decodable.count }} types")).to(equal("Found 4 types")) expect(generate("Found {{ types.based.Foo.count }} types")).to(equal("Found 2 types")) expect(generate("Found {{ types.based.NSObject.count }} types")).to(equal("Found 3 types")) expect(generate("Found {{ types.based.Bar.count|default:\"0\" }} types")).to(equal("Found 0 types")) } describe("accessing specific type via type.Typename") { it("can render accessLevel") { expect(generate("{{ type.Complex.accessLevel }}")).to(equal("public")) } it("can access supertype") { expect(generate("{{ type.FooSubclass.supertype.name }}")).to(equal("Foo")) } it("counts all variables including implements, inherits") { expect(generate("{{ type.ProjectFooSubclass.allVariables.count }}")).to(equal("2")) } it("can use filter on variables") { expect(generate("{% for var in type.Complex.allVariables|computed %}V{% endfor %}")).to(equal("V")) expect(generate("{% for var in type.Complex.allVariables|stored %}V{% endfor %}")).to(equal("VV")) expect(generate("{% for var in type.Complex.allVariables|instance %}V{% endfor %}")).to(equal("VVV")) expect(generate("{% for var in type.Complex.allVariables|static %}V{% endfor %}")).to(equal("")) expect(generate("{{ type.Complex.allVariables|instance|count }}")).to(equal("3")) } it("can use filter on methods") { expect(generate("{% for method in type.Complex.allMethods|instance %}M{% endfor %}")).to(equal("M")) expect(generate("{% for method in type.Complex.allMethods|class %}M{% endfor %}")).to(equal("M")) expect(generate("{% for method in type.Complex.allMethods|static %}M{% endfor %}")).to(equal("M")) expect(generate("{% for method in type.Complex.allMethods|initializer %}{% endfor %}")).to(equal("")) expect(generate("{{ type.Complex.allMethods|count }}")).to(equal("3")) } it("generates type.TypeName") { expect(generate("{{ type.Foo.name }} has {{ type.Foo.variables.first.name }} variable")).to(equal("Foo has intValue variable")) } it("generates contained types properly, type.ParentType.ContainedType properly") { expect(generate("{{ type.Options.InnerOptions.variables.count }} variable")).to(equal("1 variable")) } it("generates enum properly") { expect(generate("{% for case in type.Options.cases %} {{ case.name }} {% endfor %}")).to(equal(" optionA optionB ")) } it("classifies computed properties properly") { expect(generate("{{ type.Complex.variables.count }}, {{ type.Complex.computedVariables.count }}, {{ type.Complex.storedVariables.count }}")).to(equal("3, 1, 2")) } it("can access variable type information") { expect(generate("{% for variable in type.Complex.variables %}{{ variable.type.name }}{% endfor %}")).to(equal("FooBar")) } it("generates proper response for type.inherits") { expect(generate("{% if type.Foo.inherits.ProjectClass %} TRUE {% endif %}")).toNot(equal(" TRUE ")) expect(generate("{% if type.Foo.inherits.Decodable %} TRUE {% endif %}")).toNot(equal(" TRUE ")) expect(generate("{% if type.Foo.inherits.KnownProtocol %} TRUE {% endif %}")).toNot(equal(" TRUE ")) expect(generate("{% if type.Foo.inherits.AlternativeProtocol %} TRUE {% endif %}")).toNot(equal(" TRUE ")) expect(generate("{% if type.ProjectFooSubclass.inherits.Foo %} TRUE {% endif %}")).to(equal(" TRUE ")) } it("generates proper response for type.implements") { expect(generate("{% if type.Bar.implements.ProjectClass %} TRUE {% endif %}")).toNot(equal(" TRUE ")) expect(generate("{% if type.Bar.implements.Decodable %} TRUE {% endif %}")).toNot(equal(" TRUE ")) expect(generate("{% if type.Bar.implements.KnownProtocol %} TRUE {% endif %}")).to(equal(" TRUE ")) expect(generate("{% if type.ProjectFooSubclass.implements.KnownProtocol %} TRUE {% endif %}")).to(equal(" TRUE ")) expect(generate("{% if type.ProjectFooSubclass.implements.AlternativeProtocol %} TRUE {% endif %}")).to(equal(" TRUE ")) } it("generates proper response for type.based") { expect(generate("{% if type.Bar.based.ProjectClass %} TRUE {% endif %}")).toNot(equal(" TRUE ")) expect(generate("{% if type.Bar.based.Decodable %} TRUE {% endif %}")).to(equal(" TRUE ")) expect(generate("{% if type.Bar.based.KnownProtocol %} TRUE {% endif %}")).to(equal(" TRUE ")) expect(generate("{% if type.ProjectFooSubclass.based.KnownProtocol %} TRUE {% endif %}")).to(equal(" TRUE ")) expect(generate("{% if type.ProjectFooSubclass.based.Foo %} TRUE {% endif %}")).to(equal(" TRUE ")) expect(generate("{% if type.ProjectFooSubclass.based.Decodable %} TRUE {% endif %}")).to(equal(" TRUE ")) expect(generate("{% if type.ProjectFooSubclass.based.AlternativeProtocol %} TRUE {% endif %}")).to(equal(" TRUE ")) } } context("given additional arguments") { it("can reflect them") { expect(generate("{{ argument.some }}")).to(equal("value")) } it("parses numbers correctly") { expect(generate("{% if argument.number > 2 %}TRUE{% endif %}")).to(equal("TRUE")) } } } } }
0
// // AlbumView.swift // SwiftUIDemo // // Created by Seth Porter on 9/13/19. // Copyright © 2019 Seth Porter. All rights reserved. // import SwiftUI struct AlbumView: View { @State var color: Color @State var image: Image var body: some View { GeometryReader { geometry in ZStack { RoundedRectangle(cornerRadius: 4) .fill(LinearGradient(gradient: Gradient(colors: [self.color.opacity(0.4), self.color]), startPoint: .topLeading, endPoint: .bottomTrailing)) .shadow(radius: 3) self.image .resizable() .foregroundColor(.white) .opacity(0.7) .shadow(color: Color.white, radius: 5, x: 2, y: 2) .imageScale(.large) .padding(geometry.size.width * 0.1) } } } } struct AlbumView_Previews: PreviewProvider { static var previews: some View { AlbumView(color: Color.red, image: Image(systemName: "moon")) } }
0
// // Location+CoreLocation.swift // RestaurantsMapScene // // Created by Grigory Entin on 21/05/2019. // Copyright © 2019 Grigory Entin. All rights reserved. // import CoreLocation extension CLLocationCoordinate2D { init(from location: Location) { self.init( latitude: location.latitude, longitude: location.longitude ) } } extension Location { init(from coordinate: CLLocationCoordinate2D) { self.init( latitude: coordinate.latitude, longitude: coordinate.longitude ) } }
0
// // Onboard.swift // OnboardingTutorial // // Created by Kanishka on 20/05/19. // Copyright © 2019 Kanishka. All rights reserved. // struct Onboard { var image: String var title: String var info : String init(image: String, title: String, info: String) { self.title = title self.image = image self.info = info } }
0
// MasterViewController.swift // // Copyright (c) 2014 Alamofire (http://alamofire.org) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Alamofire class MasterViewController: UITableViewController { @IBOutlet weak var titleImageView: UIImageView! var detailViewController: DetailViewController? = nil var objects = NSMutableArray() override func awakeFromNib() { super.awakeFromNib() self.navigationItem.titleView = self.titleImageView // if UIDevice.currentDevice().userInterfaceIdiom == .Pad { // self.clearsSelectionOnViewWillAppear = false // self.preferredContentSize = CGSize(width: 320.0, height: 600.0) // } } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers.last?.topViewController as? DetailViewController } } // MARK: - UIStoryboardSegue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let detailViewController = segue.destinationViewController.topViewController as? DetailViewController { func requestForSegue(segue: UIStoryboardSegue) -> Request? { switch segue.identifier { case "GET": return Alamofire.request(.GET, "http://httpbin.org/get") case "POST": return Alamofire.request(.POST, "http://httpbin.org/post") case "PUT": return Alamofire.request(.PUT, "http://httpbin.org/put") case "DELETE": return Alamofire.request(.DELETE, "http://httpbin.org/delete") default: return nil } } if let request = requestForSegue(segue) { detailViewController.request = request } } } }
0
// // SecretCodes.swift // ClubhouseAvatarMaker // // Created by Антон Текутов on 08.03.2021. // import Foundation struct SecretCode: Codable { let id: Int let brand: String let code: String let description: String enum CodingKeys: String, CodingKey { case id = "id" case brand = "brand" case code = "name" case description = "description" } }
0
// // BezierGenerator.swift // MaLiang // // Created by Harley.xk on 2017/11/10. // import UIKit class BezierGenerator { enum Style { case linear case quadratic // this is the only style currently supported case cubic } init() { } init(beginPoint: CGPoint) { begin(with: beginPoint) } func begin(with point: CGPoint) { points.append(point) } func pushPoint(_ point: CGPoint) -> [CGPoint] { if point == points.last { return [] } points.append(point) if points.count < style.pointCount { return [] } step += 1 let result = genericPathPoints() return result } func finish() { step = 0 points.removeAll() } private var points: [CGPoint] = [] private var style: Style = .quadratic private var step = 0 private func genericPathPoints() -> [CGPoint] { var begin: CGPoint var control: CGPoint let end = CGPoint.middle(p1: points[step], p2: points[step + 1]) var vertices: [CGPoint] = [] if step == 1 { begin = points[0] let middle1 = CGPoint.middle(p1: points[0], p2: points[1]) control = CGPoint.middle(p1: middle1, p2: points[1]) } else { begin = CGPoint.middle(p1: points[step - 1], p2: points[step]) control = points[step] } /// segements are based on distance about start and end point let dis = begin.distance(to: end) let segements = max(Int(dis / 5), 2) for i in 0 ..< segements { let t = CGFloat(i) / CGFloat(segements) let x = pow(1 - t, 2) * begin.x + 2.0 * (1 - t) * t * control.x + t * t * end.x let y = pow(1 - t, 2) * begin.y + 2.0 * (1 - t) * t * control.y + t * t * end.y vertices.append(CGPoint(x: x, y: y)) } vertices.append(end) return vertices } } extension BezierGenerator.Style { var pointCount: Int { switch self { case .quadratic: return 3 default: return Int.max } } }
0
// // FaceIDViewController.swift // SLProjectModuleComm // // Created by 孙梁 on 2021/6/30. // import UIKit import SLIKit class FaceIDViewController: BaseViewController { private let manager = SLFaceIDWithTouchIDManager() @IBOutlet weak var label: UILabel! @IBAction func click(_ sender: UIButton) { manager.evaluate(canPassword: true) { [weak self] success, error in if success { self?.label.text = "验证成功" } else { self?.label.text = error?.descText } } } } // MARK: - LifeCyle extension FaceIDViewController { override func setMasterView() { super.setMasterView() title = SLLocalText.home_faceId_TouchID.text if let error = manager.isValid() { label.text = error.descText } } }
0
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(SwiftKeychainWrapperTests.allTests), ] } #endif
0
// SDWebImageManagerHelper.swift // // Copyright (c) 2015 Andrea Bizzotto ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit var imageViewLoadCached : ((imageView: UIImageView, backgroundImageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ()) = { (imageView: UIImageView, backgroundImageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) in imageView.image = UIImage(named:imagePath) backgroundImageView.image = UIImage(named:imagePath) completion(newImage: imageView.image != nil) } var imageViewLoadFromPath: ((imageView: UIImageView, backgroundImageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ()) = { (imageView: UIImageView, backgroundImageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) in var url = NSURL(string: imagePath) imageView.sd_setImageWithURL(url, completed: { (image : UIImage?, error: NSError?, cacheType: SDImageCacheType, imageURL: NSURL?) in completion(newImage: image != nil) }) }
0
// // FileInfo.swift // Markdown // // Created by Luo Sheng on 15/11/1. // Copyright © 2015年 Pop Tap. All rights reserved. // import Foundation struct FileInfo { static let prefetchedProperties: [URLResourceKey] = [ .nameKey, .isDirectoryKey, .creationDateKey, .contentModificationDateKey, .fileSizeKey, ] private enum FileInfoError: Error { case invalidProperty } let name: String let isDirectory: Bool let creationDate: Date let modificationDate: Date let fileSize: Int init?(URL: Foundation.URL) { var nameObj: AnyObject? try? (URL as NSURL).getResourceValue(&nameObj, forKey: URLResourceKey.nameKey) var isDirectoryObj: AnyObject? try? (URL as NSURL).getResourceValue(&isDirectoryObj, forKey: URLResourceKey.isDirectoryKey) var creationDateObj: AnyObject? try? (URL as NSURL).getResourceValue(&creationDateObj, forKey: URLResourceKey.creationDateKey) var modificationDateObj: AnyObject? try? (URL as NSURL).getResourceValue(&modificationDateObj, forKey: URLResourceKey.contentModificationDateKey) var fileSizeObj: AnyObject? try? (URL as NSURL).getResourceValue(&fileSizeObj, forKey: URLResourceKey.fileSizeKey) guard let name = nameObj as? String, let isDirectory = isDirectoryObj as? Bool, let creationDate = creationDateObj as? Date, let modificationDate = modificationDateObj as? Date, let fileSize = isDirectory ? 0 : fileSizeObj as? Int else { return nil } self.name = name self.isDirectory = isDirectory self.creationDate = creationDate self.modificationDate = modificationDate self.fileSize = fileSize } } extension FileInfo: Equatable { static func == (lhs: FileInfo, rhs: FileInfo) -> Bool { lhs.name == rhs.name && lhs.isDirectory == rhs.isDirectory && lhs.creationDate == rhs.creationDate && lhs.modificationDate == rhs.modificationDate && lhs.fileSize == rhs.fileSize } } func == (lhs: FileInfo?, rhs: FileInfo?) -> Bool { switch (lhs, rhs) { case let (lhs?, rhs?): return lhs == rhs // When two optionals are both nil, we consider them not equal case _: return false } } func != (lhs: FileInfo?, rhs: FileInfo?) -> Bool { !(lhs == rhs) } func == (lhs: [FileInfo?], rhs: [FileInfo?]) -> Bool { lhs.elementsEqual(rhs, by: ==) } func != (lhs: [FileInfo?], rhs: [FileInfo?]) -> Bool { !(lhs == rhs) }
0
// // Time.swift // VideoCapture // // Created by Nathan Perkins on 11/28/15. // Copyright © 2015 GardnerLab. All rights reserved. // import Foundation import Darwin class Time { private var timeStart: UInt64 = 0 private var timeStop: UInt64 = 0 private static var timeBase: Double? private static var globalTimers = [String: Time]() private static var globalStats = [String: [Double]]() private static func getTimeBase() -> Double { if let base = self.timeBase { return base } var info = mach_timebase_info(numer: 0, denom: 0) mach_timebase_info(&info) // calculate base let base = Double(info.numer) / Double(info.denom) self.timeBase = base return base } func start() { timeStart = mach_absolute_time() } func stop() { timeStop = mach_absolute_time() } var nanoseconds: Double { return Double(timeStop - timeStart) * Time.getTimeBase() } static func start(withName key: String) { if let t = Time.globalTimers[key] { t.start() } else { let t = Time() Time.globalTimers[key] = t t.start() } } @discardableResult static func stop(withName key: String) -> Double { if let t = Time.globalTimers[key] { t.stop() return t.nanoseconds } return -1.0 } static func stopAndSave(withName key: String) { if let t = Time.globalTimers[key] { t.stop() if nil == Time.globalStats[key] { Time.globalStats[key] = [Double]() } Time.globalStats[key]!.append(t.nanoseconds) } } static func stopAndPrint(withName key: String) { if let t = Time.globalTimers[key] { t.stop() print("\(key): \(t.nanoseconds)ns") } } static func save(withName key: String, andValue value: Double) { if nil == Time.globalStats[key] { Time.globalStats[key] = [Double]() } Time.globalStats[key]!.append(value) } static func printAll() { for (k, a) in Time.globalStats { print("\(k):") a.forEach { print("\($0)") } } } }
0
import NIO import NIOHTTP1 import XCTest import KituraNet class ChannelQuiescingTests: KituraNetTest { static var allTests: [(String, (ChannelQuiescingTests) -> () throws -> Void)] { return [ ("testChannelQuiescing", testChannelQuiescing), ] } func testChannelQuiescing() { let server = HTTP.createServer() try! server.listen(on: 0) let port = server.port ?? -1 server.delegate = SleepingDelegate() let connectionClosedExpectation = expectation(description: "Server closes connections") let bootstrap = ClientBootstrap(group: MultiThreadedEventLoopGroup(numberOfThreads: 1)) .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) .channelInitializer { channel in channel.pipeline.addHTTPClientHandlers().flatMap { channel.pipeline.addHandler(HTTPHandler(connectionClosedExpectation)) } } let request = HTTPRequestHead(version: HTTPVersion.init(major: 1, minor: 1), method: .GET, uri: "/") // Make the first connection let channel1 = try! bootstrap.connect(host: "localhost", port: port).wait() _ = channel1.write(NIOAny(HTTPClientRequestPart.head(request)), promise: nil) try! channel1.writeAndFlush(NIOAny(HTTPClientRequestPart.end(nil))).wait() // Make the second connection let channel2 = try! bootstrap.connect(host: "localhost", port: port).wait() _ = channel2.write(NIOAny(HTTPClientRequestPart.head(request)), promise: nil) try! channel2.writeAndFlush(NIOAny(HTTPClientRequestPart.end(nil))).wait() // The server must close both the connections connectionClosedExpectation.expectedFulfillmentCount = 2 // Give time for the route handlers to kick in sleep(1) // Stop the server server.stop() waitForExpectations(timeout: 10) } } class SleepingDelegate: ServerDelegate { public func handle(request: ServerRequest, response: ServerResponse) { sleep(2) try! response.end() } } class HTTPHandler: ChannelInboundHandler { typealias InboundIn = HTTPClientResponsePart private let expectation: XCTestExpectation public init(_ expectation: XCTestExpectation) { self.expectation = expectation } func channelInactive(context: ChannelHandlerContext) { expectation.fulfill() } }
0
// // ReqresLogging.swift // Reqres // // Created by Jan Mísař on 02.08.16. // // import Foundation public enum LogLevel { case none case light case verbose } public protocol ReqresLogging { var logLevel: LogLevel { get set } func logVerbose(_ message: String) func logLight(_ message: String) func logError(_ message: String) }
0
// // Date+Extension.swift // iOS-Weather // // Created by Matheus D Sanada on 04/02/21. // import UIKit extension Date { public func dateFormatted() -> String { let formatter = formatterPtBr("dd/MM/yyyy") return formatter.string(from: self) } public func dateAPIFormatted() -> String { let formatter = formatterPtBr("yyyy-MM-dd") return formatter.string(from: self) } public func dateFormattedExtended() -> String { let formatter = formatterPtBr("dd 'de' MMMM 'de' yyyy, HH:mm") return formatter.string(from: self) } public func dateFormattedHour() -> String { let formatter = formatterPtBr("HH:mm") return formatter.string(from: self) } func formatterPtBr(_ pattern: String) -> DateFormatter { let formatter = DateFormatter() formatter.locale = .init(identifier: "pt-br") formatter.timeZone = .current//TimeZone(abbreviation: "UTC") formatter.dateFormat = pattern return formatter } func now() -> Date { var calendar = Calendar.current guard let timezone = TimeZone(abbreviation: "UTC") else { return .init() } calendar.timeZone = timezone let now = calendar.date(bySettingHour: 3, minute: 0, second: 0, of: .init()) return now ?? .init() } func isToday() -> Bool { return self.isSame(of: now()) } func isSameAdding(by value: Int) -> Bool { let tomorrow = Calendar.current.date(byAdding: .day, value: value, to: now())! return self.isSame(of: tomorrow) } func isSame(of date: Date) -> Bool { let order = NSCalendar.current.compare(self, to: date, toGranularity: .day) switch order { case .orderedSame: return true default: return false } } func getDayPeriod() -> UIImage { let formatter = formatterPtBr("HH") guard var hour = Int(formatter.string(from: self)) else { return UIImage(systemName: "sun")!} hour = hour - 3 if hour >= 00 && hour < 6 { return UIImage(named: "noon")! } else if hour >= 6 && hour < 12 { return UIImage(named: "morning")! } else if hour >= 12 && hour < 18 { return UIImage(named: "afternoon")! } else { return UIImage(named: "night")! } } func getPrimaryColor() -> UIColor { let formatter = formatterPtBr("HH") guard var hour = Int(formatter.string(from: self)) else { return .white } hour = hour - 3 if hour >= 00 && hour < 6 { return UIColor(named: "primaryNoon")! } else if hour >= 6 && hour < 12 { return UIColor(named: "primaryMorning")! } else if hour >= 12 && hour < 18 { return UIColor(named: "primaryAfternoon")! } else { return UIColor(named: "primaryNight")! } } func getSecondaryColor() -> UIColor { let formatter = formatterPtBr("HH") guard var hour = Int(formatter.string(from: self)) else { return .white } hour = hour - 3 if hour >= 00 && hour < 6 { return UIColor(named: "white")! } else if hour >= 6 && hour < 12 { return UIColor(named: "white")! } else if hour >= 12 && hour < 18 { return UIColor(named: "black")! } else { return UIColor(named: "white")! } } func getSecondaryAccentColor() -> UIColor { let formatter = formatterPtBr("HH") guard var hour = Int(formatter.string(from: self)) else { return .white } hour = hour - 3 if hour >= 00 && hour < 6 { return UIColor(named: "black")! } else if hour >= 6 && hour < 12 { return UIColor(named: "black")! } else if hour >= 12 && hour < 18 { return UIColor(named: "white")! } else { return UIColor(named: "black")! } } func getBackgroundColor() -> UIColor { let formatter = formatterPtBr("HH") guard var hour = Int(formatter.string(from: self)) else { return .white } hour = hour - 3 if hour >= 00 && hour < 6 { return UIColor(named: "noon")! } else if hour >= 6 && hour < 12 { return UIColor(named: "morning")! } else if hour >= 12 && hour < 18 { return UIColor(named: "afternoon")! } else { return UIColor(named: "night")! } } }