hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
f502110c017530e87b22454a498c45258a0264e1 | 1,122 | //
// ItemDetailDataSource.swift
// PracticeApp
//
// Created by Atsushi Miyake on 2018/09/08.
// Copyright © 2018年 Atsushi Miyake. All rights reserved.
//
import Foundation
import RxDataSources
import Model
enum ItemDetailSectionModel {
case detailSection
case normalSection(items: [ItemDetailSectionItem], title: String)
case folderSection(item: ItemDetailSectionItem, title: String)
}
enum ItemDetailSectionItem {
case normalItem(item: Item)
case folderItem
var item: Item? {
switch self {
case .normalItem(let item): return item
case .folderItem: return nil
}
}
}
extension ItemDetailSectionModel: SectionModelType {
typealias Item = ItemDetailSectionItem
var items: [ItemDetailSectionItem] {
switch self {
case .detailSection:
return []
case let .normalSection(items, _):
return items
case let .folderSection(item, _):
return [item]
}
}
init(original: ItemDetailSectionModel, items: [ItemDetailSectionItem]) {
self = original
}
}
| 22.897959 | 76 | 0.651515 |
4b124b0a313d96e6dbd3340d2a0eb55c3f098bf5 | 84,040 | //
// ExplanationOfBenefit.swift
// SwiftFHIR
//
// Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/ExplanationOfBenefit) on 2019-03-01.
// 2019, SMART Health IT.
//
import Foundation
/**
Explanation of Benefit resource.
This resource provides: the claim details; adjudication details from the processing of a Claim; and optionally account
balance information, for informing the subscriber of the benefits provided.
*/
open class ExplanationOfBenefit: DomainResource {
override open class var resourceType: String {
get { return "ExplanationOfBenefit" }
}
/// Details of the event.
public var accident: ExplanationOfBenefitAccident?
/// Insurer added line items.
public var addItem: [ExplanationOfBenefitAddItem]?
/// Header-level adjudication.
public var adjudication: [ExplanationOfBenefitItemAdjudication]?
/// Balance by Benefit Category.
public var benefitBalance: [ExplanationOfBenefitBenefitBalance]?
/// When the benefits are applicable.
public var benefitPeriod: Period?
/// Relevant time frame for the claim.
public var billablePeriod: Period?
/// Care Team members.
public var careTeam: [ExplanationOfBenefitCareTeam]?
/// Claim reference.
public var claim: Reference?
/// Claim response reference.
public var claimResponse: Reference?
/// Response creation date.
public var created: DateTime?
/// Pertinent diagnosis information.
public var diagnosis: [ExplanationOfBenefitDiagnosis]?
/// Disposition Message.
public var disposition: FHIRString?
/// Author of the claim.
public var enterer: Reference?
/// Servicing Facility.
public var facility: Reference?
/// Printed reference or actual form.
public var form: Attachment?
/// Printed form identifier.
public var formCode: CodeableConcept?
/// Funds reserved status.
public var fundsReserve: CodeableConcept?
/// For whom to reserve funds.
public var fundsReserveRequested: CodeableConcept?
/// Business Identifier for the resource.
public var identifier: [Identifier]?
/// Patient insurance information.
public var insurance: [ExplanationOfBenefitInsurance]?
/// Party responsible for reimbursement.
public var insurer: Reference?
/// Product or service provided.
public var item: [ExplanationOfBenefitItem]?
/// Original prescription if superceded by fulfiller.
public var originalPrescription: Reference?
/// The outcome of the claim, predetermination, or preauthorization processing.
public var outcome: ClaimProcessingCodes?
/// The recipient of the products and services.
public var patient: Reference?
/// Recipient of benefits payable.
public var payee: ExplanationOfBenefitPayee?
/// Payment Details.
public var payment: ExplanationOfBenefitPayment?
/// Preauthorization reference.
public var preAuthRef: [FHIRString]?
/// Preauthorization in-effect period.
public var preAuthRefPeriod: [Period]?
/// Precedence (primary, secondary, etc.).
public var precedence: FHIRInteger?
/// Prescription authorizing services or products.
public var prescription: Reference?
/// Desired processing urgency.
public var priority: CodeableConcept?
/// Clinical procedures performed.
public var procedure: [ExplanationOfBenefitProcedure]?
/// Note concerning adjudication.
public var processNote: [ExplanationOfBenefitProcessNote]?
/// Party responsible for the claim.
public var provider: Reference?
/// Treatment Referral.
public var referral: Reference?
/// Prior or corollary claims.
public var related: [ExplanationOfBenefitRelated]?
/// The status of the resource instance.
public var status: ExplanationOfBenefitStatus?
/// More granular claim type.
public var subType: CodeableConcept?
/// Supporting information.
public var supportingInfo: [ExplanationOfBenefitSupportingInfo]?
/// Adjudication totals.
public var total: [ExplanationOfBenefitTotal]?
/// Category or discipline.
public var type: CodeableConcept?
/// A code to indicate whether the nature of the request is: to request adjudication of products and services
/// previously rendered; or requesting authorization and adjudication for provision in the future; or requesting the
/// non-binding adjudication of the listed products and services which could be provided in the future.
public var use: Use?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(created: DateTime, insurance: [ExplanationOfBenefitInsurance], insurer: Reference, outcome: ClaimProcessingCodes, patient: Reference, provider: Reference, status: ExplanationOfBenefitStatus, type: CodeableConcept, use: Use) {
self.init()
self.created = created
self.insurance = insurance
self.insurer = insurer
self.outcome = outcome
self.patient = patient
self.provider = provider
self.status = status
self.type = type
self.use = use
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
accident = createInstance(type: ExplanationOfBenefitAccident.self, for: "accident", in: json, context: &instCtx, owner: self) ?? accident
addItem = createInstances(of: ExplanationOfBenefitAddItem.self, for: "addItem", in: json, context: &instCtx, owner: self) ?? addItem
adjudication = createInstances(of: ExplanationOfBenefitItemAdjudication.self, for: "adjudication", in: json, context: &instCtx, owner: self) ?? adjudication
benefitBalance = createInstances(of: ExplanationOfBenefitBenefitBalance.self, for: "benefitBalance", in: json, context: &instCtx, owner: self) ?? benefitBalance
benefitPeriod = createInstance(type: Period.self, for: "benefitPeriod", in: json, context: &instCtx, owner: self) ?? benefitPeriod
billablePeriod = createInstance(type: Period.self, for: "billablePeriod", in: json, context: &instCtx, owner: self) ?? billablePeriod
careTeam = createInstances(of: ExplanationOfBenefitCareTeam.self, for: "careTeam", in: json, context: &instCtx, owner: self) ?? careTeam
claim = createInstance(type: Reference.self, for: "claim", in: json, context: &instCtx, owner: self) ?? claim
claimResponse = createInstance(type: Reference.self, for: "claimResponse", in: json, context: &instCtx, owner: self) ?? claimResponse
created = createInstance(type: DateTime.self, for: "created", in: json, context: &instCtx, owner: self) ?? created
if nil == created && !instCtx.containsKey("created") {
instCtx.addError(FHIRValidationError(missing: "created"))
}
diagnosis = createInstances(of: ExplanationOfBenefitDiagnosis.self, for: "diagnosis", in: json, context: &instCtx, owner: self) ?? diagnosis
disposition = createInstance(type: FHIRString.self, for: "disposition", in: json, context: &instCtx, owner: self) ?? disposition
enterer = createInstance(type: Reference.self, for: "enterer", in: json, context: &instCtx, owner: self) ?? enterer
facility = createInstance(type: Reference.self, for: "facility", in: json, context: &instCtx, owner: self) ?? facility
form = createInstance(type: Attachment.self, for: "form", in: json, context: &instCtx, owner: self) ?? form
formCode = createInstance(type: CodeableConcept.self, for: "formCode", in: json, context: &instCtx, owner: self) ?? formCode
fundsReserve = createInstance(type: CodeableConcept.self, for: "fundsReserve", in: json, context: &instCtx, owner: self) ?? fundsReserve
fundsReserveRequested = createInstance(type: CodeableConcept.self, for: "fundsReserveRequested", in: json, context: &instCtx, owner: self) ?? fundsReserveRequested
identifier = createInstances(of: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier
insurance = createInstances(of: ExplanationOfBenefitInsurance.self, for: "insurance", in: json, context: &instCtx, owner: self) ?? insurance
if (nil == insurance || insurance!.isEmpty) && !instCtx.containsKey("insurance") {
instCtx.addError(FHIRValidationError(missing: "insurance"))
}
insurer = createInstance(type: Reference.self, for: "insurer", in: json, context: &instCtx, owner: self) ?? insurer
if nil == insurer && !instCtx.containsKey("insurer") {
instCtx.addError(FHIRValidationError(missing: "insurer"))
}
item = createInstances(of: ExplanationOfBenefitItem.self, for: "item", in: json, context: &instCtx, owner: self) ?? item
originalPrescription = createInstance(type: Reference.self, for: "originalPrescription", in: json, context: &instCtx, owner: self) ?? originalPrescription
outcome = createEnum(type: ClaimProcessingCodes.self, for: "outcome", in: json, context: &instCtx) ?? outcome
if nil == outcome && !instCtx.containsKey("outcome") {
instCtx.addError(FHIRValidationError(missing: "outcome"))
}
patient = createInstance(type: Reference.self, for: "patient", in: json, context: &instCtx, owner: self) ?? patient
if nil == patient && !instCtx.containsKey("patient") {
instCtx.addError(FHIRValidationError(missing: "patient"))
}
payee = createInstance(type: ExplanationOfBenefitPayee.self, for: "payee", in: json, context: &instCtx, owner: self) ?? payee
payment = createInstance(type: ExplanationOfBenefitPayment.self, for: "payment", in: json, context: &instCtx, owner: self) ?? payment
preAuthRef = createInstances(of: FHIRString.self, for: "preAuthRef", in: json, context: &instCtx, owner: self) ?? preAuthRef
preAuthRefPeriod = createInstances(of: Period.self, for: "preAuthRefPeriod", in: json, context: &instCtx, owner: self) ?? preAuthRefPeriod
precedence = createInstance(type: FHIRInteger.self, for: "precedence", in: json, context: &instCtx, owner: self) ?? precedence
prescription = createInstance(type: Reference.self, for: "prescription", in: json, context: &instCtx, owner: self) ?? prescription
priority = createInstance(type: CodeableConcept.self, for: "priority", in: json, context: &instCtx, owner: self) ?? priority
procedure = createInstances(of: ExplanationOfBenefitProcedure.self, for: "procedure", in: json, context: &instCtx, owner: self) ?? procedure
processNote = createInstances(of: ExplanationOfBenefitProcessNote.self, for: "processNote", in: json, context: &instCtx, owner: self) ?? processNote
provider = createInstance(type: Reference.self, for: "provider", in: json, context: &instCtx, owner: self) ?? provider
if nil == provider && !instCtx.containsKey("provider") {
instCtx.addError(FHIRValidationError(missing: "provider"))
}
referral = createInstance(type: Reference.self, for: "referral", in: json, context: &instCtx, owner: self) ?? referral
related = createInstances(of: ExplanationOfBenefitRelated.self, for: "related", in: json, context: &instCtx, owner: self) ?? related
status = createEnum(type: ExplanationOfBenefitStatus.self, for: "status", in: json, context: &instCtx) ?? status
if nil == status && !instCtx.containsKey("status") {
instCtx.addError(FHIRValidationError(missing: "status"))
}
subType = createInstance(type: CodeableConcept.self, for: "subType", in: json, context: &instCtx, owner: self) ?? subType
supportingInfo = createInstances(of: ExplanationOfBenefitSupportingInfo.self, for: "supportingInfo", in: json, context: &instCtx, owner: self) ?? supportingInfo
total = createInstances(of: ExplanationOfBenefitTotal.self, for: "total", in: json, context: &instCtx, owner: self) ?? total
type = createInstance(type: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type
if nil == type && !instCtx.containsKey("type") {
instCtx.addError(FHIRValidationError(missing: "type"))
}
use = createEnum(type: Use.self, for: "use", in: json, context: &instCtx) ?? use
if nil == use && !instCtx.containsKey("use") {
instCtx.addError(FHIRValidationError(missing: "use"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.accident?.decorate(json: &json, withKey: "accident", errors: &errors)
arrayDecorate(json: &json, withKey: "addItem", using: self.addItem, errors: &errors)
arrayDecorate(json: &json, withKey: "adjudication", using: self.adjudication, errors: &errors)
arrayDecorate(json: &json, withKey: "benefitBalance", using: self.benefitBalance, errors: &errors)
self.benefitPeriod?.decorate(json: &json, withKey: "benefitPeriod", errors: &errors)
self.billablePeriod?.decorate(json: &json, withKey: "billablePeriod", errors: &errors)
arrayDecorate(json: &json, withKey: "careTeam", using: self.careTeam, errors: &errors)
self.claim?.decorate(json: &json, withKey: "claim", errors: &errors)
self.claimResponse?.decorate(json: &json, withKey: "claimResponse", errors: &errors)
self.created?.decorate(json: &json, withKey: "created", errors: &errors)
if nil == self.created {
errors.append(FHIRValidationError(missing: "created"))
}
arrayDecorate(json: &json, withKey: "diagnosis", using: self.diagnosis, errors: &errors)
self.disposition?.decorate(json: &json, withKey: "disposition", errors: &errors)
self.enterer?.decorate(json: &json, withKey: "enterer", errors: &errors)
self.facility?.decorate(json: &json, withKey: "facility", errors: &errors)
self.form?.decorate(json: &json, withKey: "form", errors: &errors)
self.formCode?.decorate(json: &json, withKey: "formCode", errors: &errors)
self.fundsReserve?.decorate(json: &json, withKey: "fundsReserve", errors: &errors)
self.fundsReserveRequested?.decorate(json: &json, withKey: "fundsReserveRequested", errors: &errors)
arrayDecorate(json: &json, withKey: "identifier", using: self.identifier, errors: &errors)
arrayDecorate(json: &json, withKey: "insurance", using: self.insurance, errors: &errors)
if nil == insurance || self.insurance!.isEmpty {
errors.append(FHIRValidationError(missing: "insurance"))
}
self.insurer?.decorate(json: &json, withKey: "insurer", errors: &errors)
if nil == self.insurer {
errors.append(FHIRValidationError(missing: "insurer"))
}
arrayDecorate(json: &json, withKey: "item", using: self.item, errors: &errors)
self.originalPrescription?.decorate(json: &json, withKey: "originalPrescription", errors: &errors)
self.outcome?.decorate(json: &json, withKey: "outcome", errors: &errors)
if nil == self.outcome {
errors.append(FHIRValidationError(missing: "outcome"))
}
self.patient?.decorate(json: &json, withKey: "patient", errors: &errors)
if nil == self.patient {
errors.append(FHIRValidationError(missing: "patient"))
}
self.payee?.decorate(json: &json, withKey: "payee", errors: &errors)
self.payment?.decorate(json: &json, withKey: "payment", errors: &errors)
arrayDecorate(json: &json, withKey: "preAuthRef", using: self.preAuthRef, errors: &errors)
arrayDecorate(json: &json, withKey: "preAuthRefPeriod", using: self.preAuthRefPeriod, errors: &errors)
self.precedence?.decorate(json: &json, withKey: "precedence", errors: &errors)
self.prescription?.decorate(json: &json, withKey: "prescription", errors: &errors)
self.priority?.decorate(json: &json, withKey: "priority", errors: &errors)
arrayDecorate(json: &json, withKey: "procedure", using: self.procedure, errors: &errors)
arrayDecorate(json: &json, withKey: "processNote", using: self.processNote, errors: &errors)
self.provider?.decorate(json: &json, withKey: "provider", errors: &errors)
if nil == self.provider {
errors.append(FHIRValidationError(missing: "provider"))
}
self.referral?.decorate(json: &json, withKey: "referral", errors: &errors)
arrayDecorate(json: &json, withKey: "related", using: self.related, errors: &errors)
self.status?.decorate(json: &json, withKey: "status", errors: &errors)
if nil == self.status {
errors.append(FHIRValidationError(missing: "status"))
}
self.subType?.decorate(json: &json, withKey: "subType", errors: &errors)
arrayDecorate(json: &json, withKey: "supportingInfo", using: self.supportingInfo, errors: &errors)
arrayDecorate(json: &json, withKey: "total", using: self.total, errors: &errors)
self.type?.decorate(json: &json, withKey: "type", errors: &errors)
if nil == self.type {
errors.append(FHIRValidationError(missing: "type"))
}
self.use?.decorate(json: &json, withKey: "use", errors: &errors)
if nil == self.use {
errors.append(FHIRValidationError(missing: "use"))
}
}
}
/**
Details of the event.
Details of a accident which resulted in injuries which required the products and services listed in the claim.
*/
open class ExplanationOfBenefitAccident: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitAccident" }
}
/// When the incident occurred.
public var date: FHIRDate?
/// Where the event occurred.
public var locationAddress: Address?
/// Where the event occurred.
public var locationReference: Reference?
/// The nature of the accident.
public var type: CodeableConcept?
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
date = createInstance(type: FHIRDate.self, for: "date", in: json, context: &instCtx, owner: self) ?? date
locationAddress = createInstance(type: Address.self, for: "locationAddress", in: json, context: &instCtx, owner: self) ?? locationAddress
locationReference = createInstance(type: Reference.self, for: "locationReference", in: json, context: &instCtx, owner: self) ?? locationReference
type = createInstance(type: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.date?.decorate(json: &json, withKey: "date", errors: &errors)
self.locationAddress?.decorate(json: &json, withKey: "locationAddress", errors: &errors)
self.locationReference?.decorate(json: &json, withKey: "locationReference", errors: &errors)
self.type?.decorate(json: &json, withKey: "type", errors: &errors)
}
}
/**
Insurer added line items.
The first-tier service adjudications for payor added product or service lines.
*/
open class ExplanationOfBenefitAddItem: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitAddItem" }
}
/// Added items adjudication.
public var adjudication: [ExplanationOfBenefitItemAdjudication]?
/// Anatomical location.
public var bodySite: CodeableConcept?
/// Insurer added line items.
public var detail: [ExplanationOfBenefitAddItemDetail]?
/// Detail sequence number.
public var detailSequence: [FHIRInteger]?
/// Price scaling factor.
public var factor: FHIRDecimal?
/// Item sequence number.
public var itemSequence: [FHIRInteger]?
/// Place of service or where product was supplied.
public var locationAddress: Address?
/// Place of service or where product was supplied.
public var locationCodeableConcept: CodeableConcept?
/// Place of service or where product was supplied.
public var locationReference: Reference?
/// Service/Product billing modifiers.
public var modifier: [CodeableConcept]?
/// Total item cost.
public var net: Money?
/// Applicable note numbers.
public var noteNumber: [FHIRInteger]?
/// Billing, service, product, or drug code.
public var productOrService: CodeableConcept?
/// Program the product or service is provided under.
public var programCode: [CodeableConcept]?
/// Authorized providers.
public var provider: [Reference]?
/// Count of products or services.
public var quantity: Quantity?
/// Date or dates of service or product delivery.
public var servicedDate: FHIRDate?
/// Date or dates of service or product delivery.
public var servicedPeriod: Period?
/// Subdetail sequence number.
public var subDetailSequence: [FHIRInteger]?
/// Anatomical sub-location.
public var subSite: [CodeableConcept]?
/// Fee, charge or cost per item.
public var unitPrice: Money?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(productOrService: CodeableConcept) {
self.init()
self.productOrService = productOrService
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
adjudication = createInstances(of: ExplanationOfBenefitItemAdjudication.self, for: "adjudication", in: json, context: &instCtx, owner: self) ?? adjudication
bodySite = createInstance(type: CodeableConcept.self, for: "bodySite", in: json, context: &instCtx, owner: self) ?? bodySite
detail = createInstances(of: ExplanationOfBenefitAddItemDetail.self, for: "detail", in: json, context: &instCtx, owner: self) ?? detail
detailSequence = createInstances(of: FHIRInteger.self, for: "detailSequence", in: json, context: &instCtx, owner: self) ?? detailSequence
factor = createInstance(type: FHIRDecimal.self, for: "factor", in: json, context: &instCtx, owner: self) ?? factor
itemSequence = createInstances(of: FHIRInteger.self, for: "itemSequence", in: json, context: &instCtx, owner: self) ?? itemSequence
locationAddress = createInstance(type: Address.self, for: "locationAddress", in: json, context: &instCtx, owner: self) ?? locationAddress
locationCodeableConcept = createInstance(type: CodeableConcept.self, for: "locationCodeableConcept", in: json, context: &instCtx, owner: self) ?? locationCodeableConcept
locationReference = createInstance(type: Reference.self, for: "locationReference", in: json, context: &instCtx, owner: self) ?? locationReference
modifier = createInstances(of: CodeableConcept.self, for: "modifier", in: json, context: &instCtx, owner: self) ?? modifier
net = createInstance(type: Money.self, for: "net", in: json, context: &instCtx, owner: self) ?? net
noteNumber = createInstances(of: FHIRInteger.self, for: "noteNumber", in: json, context: &instCtx, owner: self) ?? noteNumber
productOrService = createInstance(type: CodeableConcept.self, for: "productOrService", in: json, context: &instCtx, owner: self) ?? productOrService
if nil == productOrService && !instCtx.containsKey("productOrService") {
instCtx.addError(FHIRValidationError(missing: "productOrService"))
}
programCode = createInstances(of: CodeableConcept.self, for: "programCode", in: json, context: &instCtx, owner: self) ?? programCode
provider = createInstances(of: Reference.self, for: "provider", in: json, context: &instCtx, owner: self) ?? provider
quantity = createInstance(type: Quantity.self, for: "quantity", in: json, context: &instCtx, owner: self) ?? quantity
servicedDate = createInstance(type: FHIRDate.self, for: "servicedDate", in: json, context: &instCtx, owner: self) ?? servicedDate
servicedPeriod = createInstance(type: Period.self, for: "servicedPeriod", in: json, context: &instCtx, owner: self) ?? servicedPeriod
subDetailSequence = createInstances(of: FHIRInteger.self, for: "subDetailSequence", in: json, context: &instCtx, owner: self) ?? subDetailSequence
subSite = createInstances(of: CodeableConcept.self, for: "subSite", in: json, context: &instCtx, owner: self) ?? subSite
unitPrice = createInstance(type: Money.self, for: "unitPrice", in: json, context: &instCtx, owner: self) ?? unitPrice
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
arrayDecorate(json: &json, withKey: "adjudication", using: self.adjudication, errors: &errors)
self.bodySite?.decorate(json: &json, withKey: "bodySite", errors: &errors)
arrayDecorate(json: &json, withKey: "detail", using: self.detail, errors: &errors)
arrayDecorate(json: &json, withKey: "detailSequence", using: self.detailSequence, errors: &errors)
self.factor?.decorate(json: &json, withKey: "factor", errors: &errors)
arrayDecorate(json: &json, withKey: "itemSequence", using: self.itemSequence, errors: &errors)
self.locationAddress?.decorate(json: &json, withKey: "locationAddress", errors: &errors)
self.locationCodeableConcept?.decorate(json: &json, withKey: "locationCodeableConcept", errors: &errors)
self.locationReference?.decorate(json: &json, withKey: "locationReference", errors: &errors)
arrayDecorate(json: &json, withKey: "modifier", using: self.modifier, errors: &errors)
self.net?.decorate(json: &json, withKey: "net", errors: &errors)
arrayDecorate(json: &json, withKey: "noteNumber", using: self.noteNumber, errors: &errors)
self.productOrService?.decorate(json: &json, withKey: "productOrService", errors: &errors)
if nil == self.productOrService {
errors.append(FHIRValidationError(missing: "productOrService"))
}
arrayDecorate(json: &json, withKey: "programCode", using: self.programCode, errors: &errors)
arrayDecorate(json: &json, withKey: "provider", using: self.provider, errors: &errors)
self.quantity?.decorate(json: &json, withKey: "quantity", errors: &errors)
self.servicedDate?.decorate(json: &json, withKey: "servicedDate", errors: &errors)
self.servicedPeriod?.decorate(json: &json, withKey: "servicedPeriod", errors: &errors)
arrayDecorate(json: &json, withKey: "subDetailSequence", using: self.subDetailSequence, errors: &errors)
arrayDecorate(json: &json, withKey: "subSite", using: self.subSite, errors: &errors)
self.unitPrice?.decorate(json: &json, withKey: "unitPrice", errors: &errors)
}
}
/**
Insurer added line items.
The second-tier service adjudications for payor added services.
*/
open class ExplanationOfBenefitAddItemDetail: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitAddItemDetail" }
}
/// Added items adjudication.
public var adjudication: [ExplanationOfBenefitItemAdjudication]?
/// Price scaling factor.
public var factor: FHIRDecimal?
/// Service/Product billing modifiers.
public var modifier: [CodeableConcept]?
/// Total item cost.
public var net: Money?
/// Applicable note numbers.
public var noteNumber: [FHIRInteger]?
/// Billing, service, product, or drug code.
public var productOrService: CodeableConcept?
/// Count of products or services.
public var quantity: Quantity?
/// Insurer added line items.
public var subDetail: [ExplanationOfBenefitAddItemDetailSubDetail]?
/// Fee, charge or cost per item.
public var unitPrice: Money?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(productOrService: CodeableConcept) {
self.init()
self.productOrService = productOrService
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
adjudication = createInstances(of: ExplanationOfBenefitItemAdjudication.self, for: "adjudication", in: json, context: &instCtx, owner: self) ?? adjudication
factor = createInstance(type: FHIRDecimal.self, for: "factor", in: json, context: &instCtx, owner: self) ?? factor
modifier = createInstances(of: CodeableConcept.self, for: "modifier", in: json, context: &instCtx, owner: self) ?? modifier
net = createInstance(type: Money.self, for: "net", in: json, context: &instCtx, owner: self) ?? net
noteNumber = createInstances(of: FHIRInteger.self, for: "noteNumber", in: json, context: &instCtx, owner: self) ?? noteNumber
productOrService = createInstance(type: CodeableConcept.self, for: "productOrService", in: json, context: &instCtx, owner: self) ?? productOrService
if nil == productOrService && !instCtx.containsKey("productOrService") {
instCtx.addError(FHIRValidationError(missing: "productOrService"))
}
quantity = createInstance(type: Quantity.self, for: "quantity", in: json, context: &instCtx, owner: self) ?? quantity
subDetail = createInstances(of: ExplanationOfBenefitAddItemDetailSubDetail.self, for: "subDetail", in: json, context: &instCtx, owner: self) ?? subDetail
unitPrice = createInstance(type: Money.self, for: "unitPrice", in: json, context: &instCtx, owner: self) ?? unitPrice
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
arrayDecorate(json: &json, withKey: "adjudication", using: self.adjudication, errors: &errors)
self.factor?.decorate(json: &json, withKey: "factor", errors: &errors)
arrayDecorate(json: &json, withKey: "modifier", using: self.modifier, errors: &errors)
self.net?.decorate(json: &json, withKey: "net", errors: &errors)
arrayDecorate(json: &json, withKey: "noteNumber", using: self.noteNumber, errors: &errors)
self.productOrService?.decorate(json: &json, withKey: "productOrService", errors: &errors)
if nil == self.productOrService {
errors.append(FHIRValidationError(missing: "productOrService"))
}
self.quantity?.decorate(json: &json, withKey: "quantity", errors: &errors)
arrayDecorate(json: &json, withKey: "subDetail", using: self.subDetail, errors: &errors)
self.unitPrice?.decorate(json: &json, withKey: "unitPrice", errors: &errors)
}
}
/**
Insurer added line items.
The third-tier service adjudications for payor added services.
*/
open class ExplanationOfBenefitAddItemDetailSubDetail: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitAddItemDetailSubDetail" }
}
/// Added items adjudication.
public var adjudication: [ExplanationOfBenefitItemAdjudication]?
/// Price scaling factor.
public var factor: FHIRDecimal?
/// Service/Product billing modifiers.
public var modifier: [CodeableConcept]?
/// Total item cost.
public var net: Money?
/// Applicable note numbers.
public var noteNumber: [FHIRInteger]?
/// Billing, service, product, or drug code.
public var productOrService: CodeableConcept?
/// Count of products or services.
public var quantity: Quantity?
/// Fee, charge or cost per item.
public var unitPrice: Money?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(productOrService: CodeableConcept) {
self.init()
self.productOrService = productOrService
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
adjudication = createInstances(of: ExplanationOfBenefitItemAdjudication.self, for: "adjudication", in: json, context: &instCtx, owner: self) ?? adjudication
factor = createInstance(type: FHIRDecimal.self, for: "factor", in: json, context: &instCtx, owner: self) ?? factor
modifier = createInstances(of: CodeableConcept.self, for: "modifier", in: json, context: &instCtx, owner: self) ?? modifier
net = createInstance(type: Money.self, for: "net", in: json, context: &instCtx, owner: self) ?? net
noteNumber = createInstances(of: FHIRInteger.self, for: "noteNumber", in: json, context: &instCtx, owner: self) ?? noteNumber
productOrService = createInstance(type: CodeableConcept.self, for: "productOrService", in: json, context: &instCtx, owner: self) ?? productOrService
if nil == productOrService && !instCtx.containsKey("productOrService") {
instCtx.addError(FHIRValidationError(missing: "productOrService"))
}
quantity = createInstance(type: Quantity.self, for: "quantity", in: json, context: &instCtx, owner: self) ?? quantity
unitPrice = createInstance(type: Money.self, for: "unitPrice", in: json, context: &instCtx, owner: self) ?? unitPrice
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
arrayDecorate(json: &json, withKey: "adjudication", using: self.adjudication, errors: &errors)
self.factor?.decorate(json: &json, withKey: "factor", errors: &errors)
arrayDecorate(json: &json, withKey: "modifier", using: self.modifier, errors: &errors)
self.net?.decorate(json: &json, withKey: "net", errors: &errors)
arrayDecorate(json: &json, withKey: "noteNumber", using: self.noteNumber, errors: &errors)
self.productOrService?.decorate(json: &json, withKey: "productOrService", errors: &errors)
if nil == self.productOrService {
errors.append(FHIRValidationError(missing: "productOrService"))
}
self.quantity?.decorate(json: &json, withKey: "quantity", errors: &errors)
self.unitPrice?.decorate(json: &json, withKey: "unitPrice", errors: &errors)
}
}
/**
Balance by Benefit Category.
*/
open class ExplanationOfBenefitBenefitBalance: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitBenefitBalance" }
}
/// Benefit classification.
public var category: CodeableConcept?
/// Description of the benefit or services covered.
public var description_fhir: FHIRString?
/// Excluded from the plan.
public var excluded: FHIRBool?
/// Benefit Summary.
public var financial: [ExplanationOfBenefitBenefitBalanceFinancial]?
/// Short name for the benefit.
public var name: FHIRString?
/// In or out of network.
public var network: CodeableConcept?
/// Annual or lifetime.
public var term: CodeableConcept?
/// Individual or family.
public var unit: CodeableConcept?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(category: CodeableConcept) {
self.init()
self.category = category
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
category = createInstance(type: CodeableConcept.self, for: "category", in: json, context: &instCtx, owner: self) ?? category
if nil == category && !instCtx.containsKey("category") {
instCtx.addError(FHIRValidationError(missing: "category"))
}
description_fhir = createInstance(type: FHIRString.self, for: "description", in: json, context: &instCtx, owner: self) ?? description_fhir
excluded = createInstance(type: FHIRBool.self, for: "excluded", in: json, context: &instCtx, owner: self) ?? excluded
financial = createInstances(of: ExplanationOfBenefitBenefitBalanceFinancial.self, for: "financial", in: json, context: &instCtx, owner: self) ?? financial
name = createInstance(type: FHIRString.self, for: "name", in: json, context: &instCtx, owner: self) ?? name
network = createInstance(type: CodeableConcept.self, for: "network", in: json, context: &instCtx, owner: self) ?? network
term = createInstance(type: CodeableConcept.self, for: "term", in: json, context: &instCtx, owner: self) ?? term
unit = createInstance(type: CodeableConcept.self, for: "unit", in: json, context: &instCtx, owner: self) ?? unit
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.category?.decorate(json: &json, withKey: "category", errors: &errors)
if nil == self.category {
errors.append(FHIRValidationError(missing: "category"))
}
self.description_fhir?.decorate(json: &json, withKey: "description", errors: &errors)
self.excluded?.decorate(json: &json, withKey: "excluded", errors: &errors)
arrayDecorate(json: &json, withKey: "financial", using: self.financial, errors: &errors)
self.name?.decorate(json: &json, withKey: "name", errors: &errors)
self.network?.decorate(json: &json, withKey: "network", errors: &errors)
self.term?.decorate(json: &json, withKey: "term", errors: &errors)
self.unit?.decorate(json: &json, withKey: "unit", errors: &errors)
}
}
/**
Benefit Summary.
Benefits Used to date.
*/
open class ExplanationOfBenefitBenefitBalanceFinancial: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitBenefitBalanceFinancial" }
}
/// Benefits allowed.
public var allowedMoney: Money?
/// Benefits allowed.
public var allowedString: FHIRString?
/// Benefits allowed.
public var allowedUnsignedInt: FHIRInteger?
/// Benefit classification.
public var type: CodeableConcept?
/// Benefits used.
public var usedMoney: Money?
/// Benefits used.
public var usedUnsignedInt: FHIRInteger?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(type: CodeableConcept) {
self.init()
self.type = type
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
allowedMoney = createInstance(type: Money.self, for: "allowedMoney", in: json, context: &instCtx, owner: self) ?? allowedMoney
allowedString = createInstance(type: FHIRString.self, for: "allowedString", in: json, context: &instCtx, owner: self) ?? allowedString
allowedUnsignedInt = createInstance(type: FHIRInteger.self, for: "allowedUnsignedInt", in: json, context: &instCtx, owner: self) ?? allowedUnsignedInt
type = createInstance(type: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type
if nil == type && !instCtx.containsKey("type") {
instCtx.addError(FHIRValidationError(missing: "type"))
}
usedMoney = createInstance(type: Money.self, for: "usedMoney", in: json, context: &instCtx, owner: self) ?? usedMoney
usedUnsignedInt = createInstance(type: FHIRInteger.self, for: "usedUnsignedInt", in: json, context: &instCtx, owner: self) ?? usedUnsignedInt
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.allowedMoney?.decorate(json: &json, withKey: "allowedMoney", errors: &errors)
self.allowedString?.decorate(json: &json, withKey: "allowedString", errors: &errors)
self.allowedUnsignedInt?.decorate(json: &json, withKey: "allowedUnsignedInt", errors: &errors)
self.type?.decorate(json: &json, withKey: "type", errors: &errors)
if nil == self.type {
errors.append(FHIRValidationError(missing: "type"))
}
self.usedMoney?.decorate(json: &json, withKey: "usedMoney", errors: &errors)
self.usedUnsignedInt?.decorate(json: &json, withKey: "usedUnsignedInt", errors: &errors)
}
}
/**
Care Team members.
The members of the team who provided the products and services.
*/
open class ExplanationOfBenefitCareTeam: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitCareTeam" }
}
/// Practitioner or organization.
public var provider: Reference?
/// Practitioner credential or specialization.
public var qualification: CodeableConcept?
/// Indicator of the lead practitioner.
public var responsible: FHIRBool?
/// Function within the team.
public var role: CodeableConcept?
/// Order of care team.
public var sequence: FHIRInteger?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(provider: Reference, sequence: FHIRInteger) {
self.init()
self.provider = provider
self.sequence = sequence
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
provider = createInstance(type: Reference.self, for: "provider", in: json, context: &instCtx, owner: self) ?? provider
if nil == provider && !instCtx.containsKey("provider") {
instCtx.addError(FHIRValidationError(missing: "provider"))
}
qualification = createInstance(type: CodeableConcept.self, for: "qualification", in: json, context: &instCtx, owner: self) ?? qualification
responsible = createInstance(type: FHIRBool.self, for: "responsible", in: json, context: &instCtx, owner: self) ?? responsible
role = createInstance(type: CodeableConcept.self, for: "role", in: json, context: &instCtx, owner: self) ?? role
sequence = createInstance(type: FHIRInteger.self, for: "sequence", in: json, context: &instCtx, owner: self) ?? sequence
if nil == sequence && !instCtx.containsKey("sequence") {
instCtx.addError(FHIRValidationError(missing: "sequence"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.provider?.decorate(json: &json, withKey: "provider", errors: &errors)
if nil == self.provider {
errors.append(FHIRValidationError(missing: "provider"))
}
self.qualification?.decorate(json: &json, withKey: "qualification", errors: &errors)
self.responsible?.decorate(json: &json, withKey: "responsible", errors: &errors)
self.role?.decorate(json: &json, withKey: "role", errors: &errors)
self.sequence?.decorate(json: &json, withKey: "sequence", errors: &errors)
if nil == self.sequence {
errors.append(FHIRValidationError(missing: "sequence"))
}
}
}
/**
Pertinent diagnosis information.
Information about diagnoses relevant to the claim items.
*/
open class ExplanationOfBenefitDiagnosis: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitDiagnosis" }
}
/// Nature of illness or problem.
public var diagnosisCodeableConcept: CodeableConcept?
/// Nature of illness or problem.
public var diagnosisReference: Reference?
/// Present on admission.
public var onAdmission: CodeableConcept?
/// Package billing code.
public var packageCode: CodeableConcept?
/// Diagnosis instance identifier.
public var sequence: FHIRInteger?
/// Timing or nature of the diagnosis.
public var type: [CodeableConcept]?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(diagnosis: Any, sequence: FHIRInteger) {
self.init()
if let value = diagnosis as? CodeableConcept {
self.diagnosisCodeableConcept = value
}
else if let value = diagnosis as? Reference {
self.diagnosisReference = value
}
else {
fhir_warn("Type “\(Swift.type(of: diagnosis))” for property “\(diagnosis)” is invalid, ignoring")
}
self.sequence = sequence
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
diagnosisCodeableConcept = createInstance(type: CodeableConcept.self, for: "diagnosisCodeableConcept", in: json, context: &instCtx, owner: self) ?? diagnosisCodeableConcept
diagnosisReference = createInstance(type: Reference.self, for: "diagnosisReference", in: json, context: &instCtx, owner: self) ?? diagnosisReference
onAdmission = createInstance(type: CodeableConcept.self, for: "onAdmission", in: json, context: &instCtx, owner: self) ?? onAdmission
packageCode = createInstance(type: CodeableConcept.self, for: "packageCode", in: json, context: &instCtx, owner: self) ?? packageCode
sequence = createInstance(type: FHIRInteger.self, for: "sequence", in: json, context: &instCtx, owner: self) ?? sequence
if nil == sequence && !instCtx.containsKey("sequence") {
instCtx.addError(FHIRValidationError(missing: "sequence"))
}
type = createInstances(of: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type
// check if nonoptional expanded properties (i.e. at least one "answer" for "answer[x]") are present
if nil == self.diagnosisCodeableConcept && nil == self.diagnosisReference {
instCtx.addError(FHIRValidationError(missing: "diagnosis[x]"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.diagnosisCodeableConcept?.decorate(json: &json, withKey: "diagnosisCodeableConcept", errors: &errors)
self.diagnosisReference?.decorate(json: &json, withKey: "diagnosisReference", errors: &errors)
self.onAdmission?.decorate(json: &json, withKey: "onAdmission", errors: &errors)
self.packageCode?.decorate(json: &json, withKey: "packageCode", errors: &errors)
self.sequence?.decorate(json: &json, withKey: "sequence", errors: &errors)
if nil == self.sequence {
errors.append(FHIRValidationError(missing: "sequence"))
}
arrayDecorate(json: &json, withKey: "type", using: self.type, errors: &errors)
// check if nonoptional expanded properties (i.e. at least one "value" for "value[x]") are present
if nil == self.diagnosisCodeableConcept && nil == self.diagnosisReference {
errors.append(FHIRValidationError(missing: "diagnosis[x]"))
}
}
}
/**
Patient insurance information.
Financial instruments for reimbursement for the health care products and services specified on the claim.
*/
open class ExplanationOfBenefitInsurance: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitInsurance" }
}
/// Insurance information.
public var coverage: Reference?
/// Coverage to be used for adjudication.
public var focal: FHIRBool?
/// Prior authorization reference number.
public var preAuthRef: [FHIRString]?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(coverage: Reference, focal: FHIRBool) {
self.init()
self.coverage = coverage
self.focal = focal
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
coverage = createInstance(type: Reference.self, for: "coverage", in: json, context: &instCtx, owner: self) ?? coverage
if nil == coverage && !instCtx.containsKey("coverage") {
instCtx.addError(FHIRValidationError(missing: "coverage"))
}
focal = createInstance(type: FHIRBool.self, for: "focal", in: json, context: &instCtx, owner: self) ?? focal
if nil == focal && !instCtx.containsKey("focal") {
instCtx.addError(FHIRValidationError(missing: "focal"))
}
preAuthRef = createInstances(of: FHIRString.self, for: "preAuthRef", in: json, context: &instCtx, owner: self) ?? preAuthRef
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.coverage?.decorate(json: &json, withKey: "coverage", errors: &errors)
if nil == self.coverage {
errors.append(FHIRValidationError(missing: "coverage"))
}
self.focal?.decorate(json: &json, withKey: "focal", errors: &errors)
if nil == self.focal {
errors.append(FHIRValidationError(missing: "focal"))
}
arrayDecorate(json: &json, withKey: "preAuthRef", using: self.preAuthRef, errors: &errors)
}
}
/**
Product or service provided.
A claim line. Either a simple (a product or service) or a 'group' of details which can also be a simple items or groups
of sub-details.
*/
open class ExplanationOfBenefitItem: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitItem" }
}
/// Adjudication details.
public var adjudication: [ExplanationOfBenefitItemAdjudication]?
/// Anatomical location.
public var bodySite: CodeableConcept?
/// Applicable care team members.
public var careTeamSequence: [FHIRInteger]?
/// Benefit classification.
public var category: CodeableConcept?
/// Additional items.
public var detail: [ExplanationOfBenefitItemDetail]?
/// Applicable diagnoses.
public var diagnosisSequence: [FHIRInteger]?
/// Encounters related to this billed item.
public var encounter: [Reference]?
/// Price scaling factor.
public var factor: FHIRDecimal?
/// Applicable exception and supporting information.
public var informationSequence: [FHIRInteger]?
/// Place of service or where product was supplied.
public var locationAddress: Address?
/// Place of service or where product was supplied.
public var locationCodeableConcept: CodeableConcept?
/// Place of service or where product was supplied.
public var locationReference: Reference?
/// Product or service billing modifiers.
public var modifier: [CodeableConcept]?
/// Total item cost.
public var net: Money?
/// Applicable note numbers.
public var noteNumber: [FHIRInteger]?
/// Applicable procedures.
public var procedureSequence: [FHIRInteger]?
/// Billing, service, product, or drug code.
public var productOrService: CodeableConcept?
/// Program the product or service is provided under.
public var programCode: [CodeableConcept]?
/// Count of products or services.
public var quantity: Quantity?
/// Revenue or cost center code.
public var revenue: CodeableConcept?
/// Item instance identifier.
public var sequence: FHIRInteger?
/// Date or dates of service or product delivery.
public var servicedDate: FHIRDate?
/// Date or dates of service or product delivery.
public var servicedPeriod: Period?
/// Anatomical sub-location.
public var subSite: [CodeableConcept]?
/// Unique device identifier.
public var udi: [Reference]?
/// Fee, charge or cost per item.
public var unitPrice: Money?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(productOrService: CodeableConcept, sequence: FHIRInteger) {
self.init()
self.productOrService = productOrService
self.sequence = sequence
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
adjudication = createInstances(of: ExplanationOfBenefitItemAdjudication.self, for: "adjudication", in: json, context: &instCtx, owner: self) ?? adjudication
bodySite = createInstance(type: CodeableConcept.self, for: "bodySite", in: json, context: &instCtx, owner: self) ?? bodySite
careTeamSequence = createInstances(of: FHIRInteger.self, for: "careTeamSequence", in: json, context: &instCtx, owner: self) ?? careTeamSequence
category = createInstance(type: CodeableConcept.self, for: "category", in: json, context: &instCtx, owner: self) ?? category
detail = createInstances(of: ExplanationOfBenefitItemDetail.self, for: "detail", in: json, context: &instCtx, owner: self) ?? detail
diagnosisSequence = createInstances(of: FHIRInteger.self, for: "diagnosisSequence", in: json, context: &instCtx, owner: self) ?? diagnosisSequence
encounter = createInstances(of: Reference.self, for: "encounter", in: json, context: &instCtx, owner: self) ?? encounter
factor = createInstance(type: FHIRDecimal.self, for: "factor", in: json, context: &instCtx, owner: self) ?? factor
informationSequence = createInstances(of: FHIRInteger.self, for: "informationSequence", in: json, context: &instCtx, owner: self) ?? informationSequence
locationAddress = createInstance(type: Address.self, for: "locationAddress", in: json, context: &instCtx, owner: self) ?? locationAddress
locationCodeableConcept = createInstance(type: CodeableConcept.self, for: "locationCodeableConcept", in: json, context: &instCtx, owner: self) ?? locationCodeableConcept
locationReference = createInstance(type: Reference.self, for: "locationReference", in: json, context: &instCtx, owner: self) ?? locationReference
modifier = createInstances(of: CodeableConcept.self, for: "modifier", in: json, context: &instCtx, owner: self) ?? modifier
net = createInstance(type: Money.self, for: "net", in: json, context: &instCtx, owner: self) ?? net
noteNumber = createInstances(of: FHIRInteger.self, for: "noteNumber", in: json, context: &instCtx, owner: self) ?? noteNumber
procedureSequence = createInstances(of: FHIRInteger.self, for: "procedureSequence", in: json, context: &instCtx, owner: self) ?? procedureSequence
productOrService = createInstance(type: CodeableConcept.self, for: "productOrService", in: json, context: &instCtx, owner: self) ?? productOrService
if nil == productOrService && !instCtx.containsKey("productOrService") {
instCtx.addError(FHIRValidationError(missing: "productOrService"))
}
programCode = createInstances(of: CodeableConcept.self, for: "programCode", in: json, context: &instCtx, owner: self) ?? programCode
quantity = createInstance(type: Quantity.self, for: "quantity", in: json, context: &instCtx, owner: self) ?? quantity
revenue = createInstance(type: CodeableConcept.self, for: "revenue", in: json, context: &instCtx, owner: self) ?? revenue
sequence = createInstance(type: FHIRInteger.self, for: "sequence", in: json, context: &instCtx, owner: self) ?? sequence
if nil == sequence && !instCtx.containsKey("sequence") {
instCtx.addError(FHIRValidationError(missing: "sequence"))
}
servicedDate = createInstance(type: FHIRDate.self, for: "servicedDate", in: json, context: &instCtx, owner: self) ?? servicedDate
servicedPeriod = createInstance(type: Period.self, for: "servicedPeriod", in: json, context: &instCtx, owner: self) ?? servicedPeriod
subSite = createInstances(of: CodeableConcept.self, for: "subSite", in: json, context: &instCtx, owner: self) ?? subSite
udi = createInstances(of: Reference.self, for: "udi", in: json, context: &instCtx, owner: self) ?? udi
unitPrice = createInstance(type: Money.self, for: "unitPrice", in: json, context: &instCtx, owner: self) ?? unitPrice
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
arrayDecorate(json: &json, withKey: "adjudication", using: self.adjudication, errors: &errors)
self.bodySite?.decorate(json: &json, withKey: "bodySite", errors: &errors)
arrayDecorate(json: &json, withKey: "careTeamSequence", using: self.careTeamSequence, errors: &errors)
self.category?.decorate(json: &json, withKey: "category", errors: &errors)
arrayDecorate(json: &json, withKey: "detail", using: self.detail, errors: &errors)
arrayDecorate(json: &json, withKey: "diagnosisSequence", using: self.diagnosisSequence, errors: &errors)
arrayDecorate(json: &json, withKey: "encounter", using: self.encounter, errors: &errors)
self.factor?.decorate(json: &json, withKey: "factor", errors: &errors)
arrayDecorate(json: &json, withKey: "informationSequence", using: self.informationSequence, errors: &errors)
self.locationAddress?.decorate(json: &json, withKey: "locationAddress", errors: &errors)
self.locationCodeableConcept?.decorate(json: &json, withKey: "locationCodeableConcept", errors: &errors)
self.locationReference?.decorate(json: &json, withKey: "locationReference", errors: &errors)
arrayDecorate(json: &json, withKey: "modifier", using: self.modifier, errors: &errors)
self.net?.decorate(json: &json, withKey: "net", errors: &errors)
arrayDecorate(json: &json, withKey: "noteNumber", using: self.noteNumber, errors: &errors)
arrayDecorate(json: &json, withKey: "procedureSequence", using: self.procedureSequence, errors: &errors)
self.productOrService?.decorate(json: &json, withKey: "productOrService", errors: &errors)
if nil == self.productOrService {
errors.append(FHIRValidationError(missing: "productOrService"))
}
arrayDecorate(json: &json, withKey: "programCode", using: self.programCode, errors: &errors)
self.quantity?.decorate(json: &json, withKey: "quantity", errors: &errors)
self.revenue?.decorate(json: &json, withKey: "revenue", errors: &errors)
self.sequence?.decorate(json: &json, withKey: "sequence", errors: &errors)
if nil == self.sequence {
errors.append(FHIRValidationError(missing: "sequence"))
}
self.servicedDate?.decorate(json: &json, withKey: "servicedDate", errors: &errors)
self.servicedPeriod?.decorate(json: &json, withKey: "servicedPeriod", errors: &errors)
arrayDecorate(json: &json, withKey: "subSite", using: self.subSite, errors: &errors)
arrayDecorate(json: &json, withKey: "udi", using: self.udi, errors: &errors)
self.unitPrice?.decorate(json: &json, withKey: "unitPrice", errors: &errors)
}
}
/**
Adjudication details.
If this item is a group then the values here are a summary of the adjudication of the detail items. If this item is a
simple product or service then this is the result of the adjudication of this item.
*/
open class ExplanationOfBenefitItemAdjudication: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitItemAdjudication" }
}
/// Monetary amount.
public var amount: Money?
/// Type of adjudication information.
public var category: CodeableConcept?
/// Explanation of adjudication outcome.
public var reason: CodeableConcept?
/// Non-monitary value.
public var value: FHIRDecimal?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(category: CodeableConcept) {
self.init()
self.category = category
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
amount = createInstance(type: Money.self, for: "amount", in: json, context: &instCtx, owner: self) ?? amount
category = createInstance(type: CodeableConcept.self, for: "category", in: json, context: &instCtx, owner: self) ?? category
if nil == category && !instCtx.containsKey("category") {
instCtx.addError(FHIRValidationError(missing: "category"))
}
reason = createInstance(type: CodeableConcept.self, for: "reason", in: json, context: &instCtx, owner: self) ?? reason
value = createInstance(type: FHIRDecimal.self, for: "value", in: json, context: &instCtx, owner: self) ?? value
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.amount?.decorate(json: &json, withKey: "amount", errors: &errors)
self.category?.decorate(json: &json, withKey: "category", errors: &errors)
if nil == self.category {
errors.append(FHIRValidationError(missing: "category"))
}
self.reason?.decorate(json: &json, withKey: "reason", errors: &errors)
self.value?.decorate(json: &json, withKey: "value", errors: &errors)
}
}
/**
Additional items.
Second-tier of goods and services.
*/
open class ExplanationOfBenefitItemDetail: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitItemDetail" }
}
/// Detail level adjudication details.
public var adjudication: [ExplanationOfBenefitItemAdjudication]?
/// Benefit classification.
public var category: CodeableConcept?
/// Price scaling factor.
public var factor: FHIRDecimal?
/// Service/Product billing modifiers.
public var modifier: [CodeableConcept]?
/// Total item cost.
public var net: Money?
/// Applicable note numbers.
public var noteNumber: [FHIRInteger]?
/// Billing, service, product, or drug code.
public var productOrService: CodeableConcept?
/// Program the product or service is provided under.
public var programCode: [CodeableConcept]?
/// Count of products or services.
public var quantity: Quantity?
/// Revenue or cost center code.
public var revenue: CodeableConcept?
/// Product or service provided.
public var sequence: FHIRInteger?
/// Additional items.
public var subDetail: [ExplanationOfBenefitItemDetailSubDetail]?
/// Unique device identifier.
public var udi: [Reference]?
/// Fee, charge or cost per item.
public var unitPrice: Money?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(productOrService: CodeableConcept, sequence: FHIRInteger) {
self.init()
self.productOrService = productOrService
self.sequence = sequence
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
adjudication = createInstances(of: ExplanationOfBenefitItemAdjudication.self, for: "adjudication", in: json, context: &instCtx, owner: self) ?? adjudication
category = createInstance(type: CodeableConcept.self, for: "category", in: json, context: &instCtx, owner: self) ?? category
factor = createInstance(type: FHIRDecimal.self, for: "factor", in: json, context: &instCtx, owner: self) ?? factor
modifier = createInstances(of: CodeableConcept.self, for: "modifier", in: json, context: &instCtx, owner: self) ?? modifier
net = createInstance(type: Money.self, for: "net", in: json, context: &instCtx, owner: self) ?? net
noteNumber = createInstances(of: FHIRInteger.self, for: "noteNumber", in: json, context: &instCtx, owner: self) ?? noteNumber
productOrService = createInstance(type: CodeableConcept.self, for: "productOrService", in: json, context: &instCtx, owner: self) ?? productOrService
if nil == productOrService && !instCtx.containsKey("productOrService") {
instCtx.addError(FHIRValidationError(missing: "productOrService"))
}
programCode = createInstances(of: CodeableConcept.self, for: "programCode", in: json, context: &instCtx, owner: self) ?? programCode
quantity = createInstance(type: Quantity.self, for: "quantity", in: json, context: &instCtx, owner: self) ?? quantity
revenue = createInstance(type: CodeableConcept.self, for: "revenue", in: json, context: &instCtx, owner: self) ?? revenue
sequence = createInstance(type: FHIRInteger.self, for: "sequence", in: json, context: &instCtx, owner: self) ?? sequence
if nil == sequence && !instCtx.containsKey("sequence") {
instCtx.addError(FHIRValidationError(missing: "sequence"))
}
subDetail = createInstances(of: ExplanationOfBenefitItemDetailSubDetail.self, for: "subDetail", in: json, context: &instCtx, owner: self) ?? subDetail
udi = createInstances(of: Reference.self, for: "udi", in: json, context: &instCtx, owner: self) ?? udi
unitPrice = createInstance(type: Money.self, for: "unitPrice", in: json, context: &instCtx, owner: self) ?? unitPrice
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
arrayDecorate(json: &json, withKey: "adjudication", using: self.adjudication, errors: &errors)
self.category?.decorate(json: &json, withKey: "category", errors: &errors)
self.factor?.decorate(json: &json, withKey: "factor", errors: &errors)
arrayDecorate(json: &json, withKey: "modifier", using: self.modifier, errors: &errors)
self.net?.decorate(json: &json, withKey: "net", errors: &errors)
arrayDecorate(json: &json, withKey: "noteNumber", using: self.noteNumber, errors: &errors)
self.productOrService?.decorate(json: &json, withKey: "productOrService", errors: &errors)
if nil == self.productOrService {
errors.append(FHIRValidationError(missing: "productOrService"))
}
arrayDecorate(json: &json, withKey: "programCode", using: self.programCode, errors: &errors)
self.quantity?.decorate(json: &json, withKey: "quantity", errors: &errors)
self.revenue?.decorate(json: &json, withKey: "revenue", errors: &errors)
self.sequence?.decorate(json: &json, withKey: "sequence", errors: &errors)
if nil == self.sequence {
errors.append(FHIRValidationError(missing: "sequence"))
}
arrayDecorate(json: &json, withKey: "subDetail", using: self.subDetail, errors: &errors)
arrayDecorate(json: &json, withKey: "udi", using: self.udi, errors: &errors)
self.unitPrice?.decorate(json: &json, withKey: "unitPrice", errors: &errors)
}
}
/**
Additional items.
Third-tier of goods and services.
*/
open class ExplanationOfBenefitItemDetailSubDetail: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitItemDetailSubDetail" }
}
/// Subdetail level adjudication details.
public var adjudication: [ExplanationOfBenefitItemAdjudication]?
/// Benefit classification.
public var category: CodeableConcept?
/// Price scaling factor.
public var factor: FHIRDecimal?
/// Service/Product billing modifiers.
public var modifier: [CodeableConcept]?
/// Total item cost.
public var net: Money?
/// Applicable note numbers.
public var noteNumber: [FHIRInteger]?
/// Billing, service, product, or drug code.
public var productOrService: CodeableConcept?
/// Program the product or service is provided under.
public var programCode: [CodeableConcept]?
/// Count of products or services.
public var quantity: Quantity?
/// Revenue or cost center code.
public var revenue: CodeableConcept?
/// Product or service provided.
public var sequence: FHIRInteger?
/// Unique device identifier.
public var udi: [Reference]?
/// Fee, charge or cost per item.
public var unitPrice: Money?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(productOrService: CodeableConcept, sequence: FHIRInteger) {
self.init()
self.productOrService = productOrService
self.sequence = sequence
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
adjudication = createInstances(of: ExplanationOfBenefitItemAdjudication.self, for: "adjudication", in: json, context: &instCtx, owner: self) ?? adjudication
category = createInstance(type: CodeableConcept.self, for: "category", in: json, context: &instCtx, owner: self) ?? category
factor = createInstance(type: FHIRDecimal.self, for: "factor", in: json, context: &instCtx, owner: self) ?? factor
modifier = createInstances(of: CodeableConcept.self, for: "modifier", in: json, context: &instCtx, owner: self) ?? modifier
net = createInstance(type: Money.self, for: "net", in: json, context: &instCtx, owner: self) ?? net
noteNumber = createInstances(of: FHIRInteger.self, for: "noteNumber", in: json, context: &instCtx, owner: self) ?? noteNumber
productOrService = createInstance(type: CodeableConcept.self, for: "productOrService", in: json, context: &instCtx, owner: self) ?? productOrService
if nil == productOrService && !instCtx.containsKey("productOrService") {
instCtx.addError(FHIRValidationError(missing: "productOrService"))
}
programCode = createInstances(of: CodeableConcept.self, for: "programCode", in: json, context: &instCtx, owner: self) ?? programCode
quantity = createInstance(type: Quantity.self, for: "quantity", in: json, context: &instCtx, owner: self) ?? quantity
revenue = createInstance(type: CodeableConcept.self, for: "revenue", in: json, context: &instCtx, owner: self) ?? revenue
sequence = createInstance(type: FHIRInteger.self, for: "sequence", in: json, context: &instCtx, owner: self) ?? sequence
if nil == sequence && !instCtx.containsKey("sequence") {
instCtx.addError(FHIRValidationError(missing: "sequence"))
}
udi = createInstances(of: Reference.self, for: "udi", in: json, context: &instCtx, owner: self) ?? udi
unitPrice = createInstance(type: Money.self, for: "unitPrice", in: json, context: &instCtx, owner: self) ?? unitPrice
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
arrayDecorate(json: &json, withKey: "adjudication", using: self.adjudication, errors: &errors)
self.category?.decorate(json: &json, withKey: "category", errors: &errors)
self.factor?.decorate(json: &json, withKey: "factor", errors: &errors)
arrayDecorate(json: &json, withKey: "modifier", using: self.modifier, errors: &errors)
self.net?.decorate(json: &json, withKey: "net", errors: &errors)
arrayDecorate(json: &json, withKey: "noteNumber", using: self.noteNumber, errors: &errors)
self.productOrService?.decorate(json: &json, withKey: "productOrService", errors: &errors)
if nil == self.productOrService {
errors.append(FHIRValidationError(missing: "productOrService"))
}
arrayDecorate(json: &json, withKey: "programCode", using: self.programCode, errors: &errors)
self.quantity?.decorate(json: &json, withKey: "quantity", errors: &errors)
self.revenue?.decorate(json: &json, withKey: "revenue", errors: &errors)
self.sequence?.decorate(json: &json, withKey: "sequence", errors: &errors)
if nil == self.sequence {
errors.append(FHIRValidationError(missing: "sequence"))
}
arrayDecorate(json: &json, withKey: "udi", using: self.udi, errors: &errors)
self.unitPrice?.decorate(json: &json, withKey: "unitPrice", errors: &errors)
}
}
/**
Recipient of benefits payable.
The party to be reimbursed for cost of the products and services according to the terms of the policy.
*/
open class ExplanationOfBenefitPayee: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitPayee" }
}
/// Recipient reference.
public var party: Reference?
/// Category of recipient.
public var type: CodeableConcept?
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
party = createInstance(type: Reference.self, for: "party", in: json, context: &instCtx, owner: self) ?? party
type = createInstance(type: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.party?.decorate(json: &json, withKey: "party", errors: &errors)
self.type?.decorate(json: &json, withKey: "type", errors: &errors)
}
}
/**
Payment Details.
Payment details for the adjudication of the claim.
*/
open class ExplanationOfBenefitPayment: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitPayment" }
}
/// Payment adjustment for non-claim issues.
public var adjustment: Money?
/// Explanation for the variance.
public var adjustmentReason: CodeableConcept?
/// Payable amount after adjustment.
public var amount: Money?
/// Expected date of payment.
public var date: FHIRDate?
/// Business identifier for the payment.
public var identifier: Identifier?
/// Partial or complete payment.
public var type: CodeableConcept?
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
adjustment = createInstance(type: Money.self, for: "adjustment", in: json, context: &instCtx, owner: self) ?? adjustment
adjustmentReason = createInstance(type: CodeableConcept.self, for: "adjustmentReason", in: json, context: &instCtx, owner: self) ?? adjustmentReason
amount = createInstance(type: Money.self, for: "amount", in: json, context: &instCtx, owner: self) ?? amount
date = createInstance(type: FHIRDate.self, for: "date", in: json, context: &instCtx, owner: self) ?? date
identifier = createInstance(type: Identifier.self, for: "identifier", in: json, context: &instCtx, owner: self) ?? identifier
type = createInstance(type: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.adjustment?.decorate(json: &json, withKey: "adjustment", errors: &errors)
self.adjustmentReason?.decorate(json: &json, withKey: "adjustmentReason", errors: &errors)
self.amount?.decorate(json: &json, withKey: "amount", errors: &errors)
self.date?.decorate(json: &json, withKey: "date", errors: &errors)
self.identifier?.decorate(json: &json, withKey: "identifier", errors: &errors)
self.type?.decorate(json: &json, withKey: "type", errors: &errors)
}
}
/**
Clinical procedures performed.
Procedures performed on the patient relevant to the billing items with the claim.
*/
open class ExplanationOfBenefitProcedure: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitProcedure" }
}
/// When the procedure was performed.
public var date: DateTime?
/// Specific clinical procedure.
public var procedureCodeableConcept: CodeableConcept?
/// Specific clinical procedure.
public var procedureReference: Reference?
/// Procedure instance identifier.
public var sequence: FHIRInteger?
/// Category of Procedure.
public var type: [CodeableConcept]?
/// Unique device identifier.
public var udi: [Reference]?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(procedure: Any, sequence: FHIRInteger) {
self.init()
if let value = procedure as? CodeableConcept {
self.procedureCodeableConcept = value
}
else if let value = procedure as? Reference {
self.procedureReference = value
}
else {
fhir_warn("Type “\(Swift.type(of: procedure))” for property “\(procedure)” is invalid, ignoring")
}
self.sequence = sequence
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
date = createInstance(type: DateTime.self, for: "date", in: json, context: &instCtx, owner: self) ?? date
procedureCodeableConcept = createInstance(type: CodeableConcept.self, for: "procedureCodeableConcept", in: json, context: &instCtx, owner: self) ?? procedureCodeableConcept
procedureReference = createInstance(type: Reference.self, for: "procedureReference", in: json, context: &instCtx, owner: self) ?? procedureReference
sequence = createInstance(type: FHIRInteger.self, for: "sequence", in: json, context: &instCtx, owner: self) ?? sequence
if nil == sequence && !instCtx.containsKey("sequence") {
instCtx.addError(FHIRValidationError(missing: "sequence"))
}
type = createInstances(of: CodeableConcept.self, for: "type", in: json, context: &instCtx, owner: self) ?? type
udi = createInstances(of: Reference.self, for: "udi", in: json, context: &instCtx, owner: self) ?? udi
// check if nonoptional expanded properties (i.e. at least one "answer" for "answer[x]") are present
if nil == self.procedureCodeableConcept && nil == self.procedureReference {
instCtx.addError(FHIRValidationError(missing: "procedure[x]"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.date?.decorate(json: &json, withKey: "date", errors: &errors)
self.procedureCodeableConcept?.decorate(json: &json, withKey: "procedureCodeableConcept", errors: &errors)
self.procedureReference?.decorate(json: &json, withKey: "procedureReference", errors: &errors)
self.sequence?.decorate(json: &json, withKey: "sequence", errors: &errors)
if nil == self.sequence {
errors.append(FHIRValidationError(missing: "sequence"))
}
arrayDecorate(json: &json, withKey: "type", using: self.type, errors: &errors)
arrayDecorate(json: &json, withKey: "udi", using: self.udi, errors: &errors)
// check if nonoptional expanded properties (i.e. at least one "value" for "value[x]") are present
if nil == self.procedureCodeableConcept && nil == self.procedureReference {
errors.append(FHIRValidationError(missing: "procedure[x]"))
}
}
}
/**
Note concerning adjudication.
A note that describes or explains adjudication results in a human readable form.
*/
open class ExplanationOfBenefitProcessNote: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitProcessNote" }
}
/// Language of the text.
public var language: CodeableConcept?
/// Note instance identifier.
public var number: FHIRInteger?
/// Note explanatory text.
public var text: FHIRString?
/// The business purpose of the note text.
public var type: NoteType?
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
language = createInstance(type: CodeableConcept.self, for: "language", in: json, context: &instCtx, owner: self) ?? language
number = createInstance(type: FHIRInteger.self, for: "number", in: json, context: &instCtx, owner: self) ?? number
text = createInstance(type: FHIRString.self, for: "text", in: json, context: &instCtx, owner: self) ?? text
type = createEnum(type: NoteType.self, for: "type", in: json, context: &instCtx) ?? type
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.language?.decorate(json: &json, withKey: "language", errors: &errors)
self.number?.decorate(json: &json, withKey: "number", errors: &errors)
self.text?.decorate(json: &json, withKey: "text", errors: &errors)
self.type?.decorate(json: &json, withKey: "type", errors: &errors)
}
}
/**
Prior or corollary claims.
Other claims which are related to this claim such as prior submissions or claims for related services or for the same
event.
*/
open class ExplanationOfBenefitRelated: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitRelated" }
}
/// Reference to the related claim.
public var claim: Reference?
/// File or case reference.
public var reference: Identifier?
/// How the reference claim is related.
public var relationship: CodeableConcept?
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
claim = createInstance(type: Reference.self, for: "claim", in: json, context: &instCtx, owner: self) ?? claim
reference = createInstance(type: Identifier.self, for: "reference", in: json, context: &instCtx, owner: self) ?? reference
relationship = createInstance(type: CodeableConcept.self, for: "relationship", in: json, context: &instCtx, owner: self) ?? relationship
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.claim?.decorate(json: &json, withKey: "claim", errors: &errors)
self.reference?.decorate(json: &json, withKey: "reference", errors: &errors)
self.relationship?.decorate(json: &json, withKey: "relationship", errors: &errors)
}
}
/**
Supporting information.
Additional information codes regarding exceptions, special considerations, the condition, situation, prior or concurrent
issues.
*/
open class ExplanationOfBenefitSupportingInfo: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitSupportingInfo" }
}
/// Classification of the supplied information.
public var category: CodeableConcept?
/// Type of information.
public var code: CodeableConcept?
/// Explanation for the information.
public var reason: Coding?
/// Information instance identifier.
public var sequence: FHIRInteger?
/// When it occurred.
public var timingDate: FHIRDate?
/// When it occurred.
public var timingPeriod: Period?
/// Data to be provided.
public var valueAttachment: Attachment?
/// Data to be provided.
public var valueBoolean: FHIRBool?
/// Data to be provided.
public var valueQuantity: Quantity?
/// Data to be provided.
public var valueReference: Reference?
/// Data to be provided.
public var valueString: FHIRString?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(category: CodeableConcept, sequence: FHIRInteger) {
self.init()
self.category = category
self.sequence = sequence
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
category = createInstance(type: CodeableConcept.self, for: "category", in: json, context: &instCtx, owner: self) ?? category
if nil == category && !instCtx.containsKey("category") {
instCtx.addError(FHIRValidationError(missing: "category"))
}
code = createInstance(type: CodeableConcept.self, for: "code", in: json, context: &instCtx, owner: self) ?? code
reason = createInstance(type: Coding.self, for: "reason", in: json, context: &instCtx, owner: self) ?? reason
sequence = createInstance(type: FHIRInteger.self, for: "sequence", in: json, context: &instCtx, owner: self) ?? sequence
if nil == sequence && !instCtx.containsKey("sequence") {
instCtx.addError(FHIRValidationError(missing: "sequence"))
}
timingDate = createInstance(type: FHIRDate.self, for: "timingDate", in: json, context: &instCtx, owner: self) ?? timingDate
timingPeriod = createInstance(type: Period.self, for: "timingPeriod", in: json, context: &instCtx, owner: self) ?? timingPeriod
valueAttachment = createInstance(type: Attachment.self, for: "valueAttachment", in: json, context: &instCtx, owner: self) ?? valueAttachment
valueBoolean = createInstance(type: FHIRBool.self, for: "valueBoolean", in: json, context: &instCtx, owner: self) ?? valueBoolean
valueQuantity = createInstance(type: Quantity.self, for: "valueQuantity", in: json, context: &instCtx, owner: self) ?? valueQuantity
valueReference = createInstance(type: Reference.self, for: "valueReference", in: json, context: &instCtx, owner: self) ?? valueReference
valueString = createInstance(type: FHIRString.self, for: "valueString", in: json, context: &instCtx, owner: self) ?? valueString
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.category?.decorate(json: &json, withKey: "category", errors: &errors)
if nil == self.category {
errors.append(FHIRValidationError(missing: "category"))
}
self.code?.decorate(json: &json, withKey: "code", errors: &errors)
self.reason?.decorate(json: &json, withKey: "reason", errors: &errors)
self.sequence?.decorate(json: &json, withKey: "sequence", errors: &errors)
if nil == self.sequence {
errors.append(FHIRValidationError(missing: "sequence"))
}
self.timingDate?.decorate(json: &json, withKey: "timingDate", errors: &errors)
self.timingPeriod?.decorate(json: &json, withKey: "timingPeriod", errors: &errors)
self.valueAttachment?.decorate(json: &json, withKey: "valueAttachment", errors: &errors)
self.valueBoolean?.decorate(json: &json, withKey: "valueBoolean", errors: &errors)
self.valueQuantity?.decorate(json: &json, withKey: "valueQuantity", errors: &errors)
self.valueReference?.decorate(json: &json, withKey: "valueReference", errors: &errors)
self.valueString?.decorate(json: &json, withKey: "valueString", errors: &errors)
}
}
/**
Adjudication totals.
Categorized monetary totals for the adjudication.
*/
open class ExplanationOfBenefitTotal: BackboneElement {
override open class var resourceType: String {
get { return "ExplanationOfBenefitTotal" }
}
/// Financial total for the category.
public var amount: Money?
/// Type of adjudication information.
public var category: CodeableConcept?
/** Convenience initializer, taking all required properties as arguments. */
public convenience init(amount: Money, category: CodeableConcept) {
self.init()
self.amount = amount
self.category = category
}
override open func populate(from json: FHIRJSON, context instCtx: inout FHIRInstantiationContext) {
super.populate(from: json, context: &instCtx)
amount = createInstance(type: Money.self, for: "amount", in: json, context: &instCtx, owner: self) ?? amount
if nil == amount && !instCtx.containsKey("amount") {
instCtx.addError(FHIRValidationError(missing: "amount"))
}
category = createInstance(type: CodeableConcept.self, for: "category", in: json, context: &instCtx, owner: self) ?? category
if nil == category && !instCtx.containsKey("category") {
instCtx.addError(FHIRValidationError(missing: "category"))
}
}
override open func decorate(json: inout FHIRJSON, errors: inout [FHIRValidationError]) {
super.decorate(json: &json, errors: &errors)
self.amount?.decorate(json: &json, withKey: "amount", errors: &errors)
if nil == self.amount {
errors.append(FHIRValidationError(missing: "amount"))
}
self.category?.decorate(json: &json, withKey: "category", errors: &errors)
if nil == self.category {
errors.append(FHIRValidationError(missing: "category"))
}
}
}
| 44.893162 | 250 | 0.736257 |
5b947ca83af7d591e390ca1ff154df2e302c8128 | 788 | //
// RxActionSheetDelegateProxy.swift
// RxCocoa
//
// Created by Carlos García on 8/7/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
class RxActionSheetDelegateProxy : DelegateProxy
, UIActionSheetDelegate
, DelegateProxyType {
class func currentDelegateFor(object: AnyObject) -> AnyObject? {
let actionSheet: UIActionSheet = castOrFatalError(object)
return actionSheet.delegate
}
class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let actionSheet: UIActionSheet = castOrFatalError(object)
actionSheet.delegate = castOptionalOrFatalError(delegate)
}
}
| 28.142857 | 85 | 0.668782 |
099753811bbe554a7883674e157e068c68ca1dfa | 435 | //
// UIWindow + Extensions.swift
// ChainsKit
//
// Created by TING YEN KUO on 2018/12/27.
//
import UIKit
extension UIWindow {
@discardableResult
public func rootViewController(_ rootVC: UIViewController) -> Self {
self.rootViewController = rootVC
return self
}
@discardableResult
public func makeKeyAndVisibleWindow() -> Self {
self.makeKeyAndVisible()
return self
}
}
| 18.125 | 72 | 0.652874 |
acfab6f3c61160dfb378b23e730305aacd692442 | 68 | //
// File.swift
// TrackingioModuleExample
//
import Foundation
| 9.714286 | 27 | 0.705882 |
76ac7ddaff8bbac9cb5fe996b743575e5a0d6448 | 5,963 | //
// ViewController.swift
// NFCTagReadWrite
//
// Created by Takuto Nakamura on 2019/07/19.
// Copyright © 2019 Takuto Nakamura. All rights reserved.
//
import UIKit
import CoreNFC
enum State {
case standBy
case read
case write
}
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var writeBtn: UIButton!
@IBOutlet weak var readBtn: UIButton!
var session: NFCNDEFReaderSession?
var message: NFCNDEFMessage?
var state: State = .standBy
var text: String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func tapScreen(_ sender: Any) {
textField.resignFirstResponder()
}
@IBAction func write(_ sender: Any) {
textField.resignFirstResponder()
if textField.text == nil || textField.text!.isEmpty { return }
text = textField.text!
startSession(state: .write)
}
@IBAction func read(_ sender: Any) {
startSession(state: .read)
}
func startSession(state: State) {
self.state = state
guard NFCNDEFReaderSession.readingAvailable else {
Swift.print("NFCはつかえないよ.")
return
}
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
session?.alertMessage = "NFCタグをiPhone上部に近づけてください."
session?.begin()
}
func stopSession(alert: String = "", error: String = "") {
session?.alertMessage = alert
if error.isEmpty {
session?.invalidate()
} else {
session?.invalidate(errorMessage: error)
}
self.state = .standBy
}
func tagRemovalDetect(_ tag: NFCNDEFTag) {
session?.connect(to: tag) { (error: Error?) in
if error != nil || !tag.isAvailable {
self.session?.restartPolling()
return
}
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + .milliseconds(500), execute: {
self.tagRemovalDetect(tag)
})
}
}
func updateMessage(_ message: NFCNDEFMessage) -> Bool {
if message.records.isEmpty { return false }
var results = [String]()
for record in message.records {
if let type = String(data: record.type, encoding: .utf8) {
if type == "T" { //データ形式がテキストならば
let res = record.wellKnownTypeTextPayload()
if let text = res.0 {
results.append("text: \(text)")
}
} else if type == "U" { //データ形式がURLならば
let res = record.wellKnownTypeURIPayload()
if let url = res {
results.append("url: \(url)")
}
}
}
}
stopSession(alert: "[" + results.joined(separator: ", ") + "]")
return true
}
}
extension ViewController: NFCNDEFReaderSessionDelegate {
func readerSessionDidBecomeActive(_ session: NFCNDEFReaderSession) {
//
}
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
Swift.print(error.localizedDescription)
}
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
// not called
}
func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCNDEFTag]) {
if tags.count > 1 {
session.alertMessage = "読み込ませるNFCタグは1枚にしてください."
tagRemovalDetect(tags.first!)
return
}
let tag = tags.first!
session.connect(to: tag) { (error) in
if error != nil {
session.restartPolling()
return
}
}
tag.queryNDEFStatus { (status, capacity, error) in
if status == .notSupported {
self.stopSession(error: "このNFCタグは対応していないみたい.")
return
}
if self.state == .write {
if status == .readOnly {
self.stopSession(error: "このNFCタグには書き込みできないぞ")
return
}
if let payload = NFCNDEFPayload.wellKnownTypeTextPayload(string: self.text, locale: Locale(identifier: "en")) {
let urlPayload = NFCNDEFPayload.wellKnownTypeURIPayload(string: "https://kyome.io/")!
self.message = NFCNDEFMessage(records: [payload, urlPayload])
if self.message!.length > capacity {
self.stopSession(error: "容量オーバーで書き込めないぞ!\n容量は\(capacity)bytesらしいぞ.")
return
}
tag.writeNDEF(self.message!) { (error) in
if error != nil {
// self.printTimestamp()
self.stopSession(error: error!.localizedDescription)
} else {
self.stopSession(alert: "書き込み成功\(^o^)/")
}
}
}
} else if self.state == .read {
tag.readNDEF { (message, error) in
if error != nil || message == nil {
self.stopSession(error: error!.localizedDescription)
return
}
if !self.updateMessage(message!) {
self.stopSession(error: "このNFCタグは対応していないみたい.")
}
}
}
}
}
func printTimestamp() {
let df = DateFormatter()
df.timeStyle = .long
df.dateStyle = .long
df.locale = Locale.current
let now = Date()
Swift.print("Timestamp: ", df.string(from: now))
}
}
| 32.584699 | 127 | 0.523562 |
e9c98368fb3a3da81a1378b2acc597e7303999f8 | 2,650 | //
// SwipeBackContextTests.swift
// SwipeTransitionTests
//
// Created by Tatsuya Tanaka on 20171230.
// Copyright © 2017年 tattn. All rights reserved.
//
import XCTest
@testable import SwipeTransition
class SwipeBackContextTestsTests: XCTestCase {
private var context: SwipeBackContext!
private var viewController: UIViewController!
private var navigationController: UINavigationController!
private var panGestureRecognizer: TestablePanGestureRecognizer!
override func setUp() {
super.setUp()
viewController = UIViewController()
navigationController = UINavigationController(rootViewController: UIViewController())
panGestureRecognizer = TestablePanGestureRecognizer()
context = SwipeBackContext(target: navigationController)
}
func testAllowsTransitionStart() {
XCTAssertFalse(context.allowsTransitionStart)
navigationController.pushViewController(viewController, animated: false)
XCTAssertTrue(context.allowsTransitionStart)
context.isEnabled = false
XCTAssertFalse(context.allowsTransitionStart)
context.isEnabled = true
XCTAssertTrue(context.allowsTransitionStart)
}
func testStartTransition() {
navigationController.pushViewController(viewController, animated: false)
XCTAssertNil(context.interactiveTransition)
context.startTransition()
XCTAssertNotNil(context.interactiveTransition)
}
func testUpdateTransition() {
navigationController.pushViewController(viewController, animated: false)
context.startTransition()
XCTAssertTrue(context.interactiveTransition?.percentComplete == 0)
panGestureRecognizer.perfomTouch(location: nil, translation: CGPoint(x: 50, y: 0), state: .changed)
context.updateTransition(recognizer: panGestureRecognizer)
// XCTAssertTrue(context.interactiveTransition?.percentComplete != 0) // 🤔
}
func testFinishTransition() {
navigationController.pushViewController(viewController, animated: false)
context.startTransition()
XCTAssertNotNil(context.interactiveTransition)
context.finishTransition()
XCTAssertNil(context.interactiveTransition)
XCTAssertFalse(context.transitioning)
}
func testCancelTransition() {
navigationController.pushViewController(viewController, animated: false)
context.startTransition()
XCTAssertNotNil(context.interactiveTransition)
context.cancelTransition()
XCTAssertNil(context.interactiveTransition)
XCTAssertFalse(context.transitioning)
}
}
| 37.323944 | 107 | 0.739623 |
72e5972f695d7381872477ab92598e1d39191cf0 | 636 | //
// Copyright (c) Vatsal Manot
//
import Swift
import SwiftUI
extension NavigationLink where Label == Text {
/// Creates an instance that presents `destination`, with a Text label generated from a title string.
public init(_ title: LocalizedStringKey, @ViewBuilder destination: () -> Destination) {
self.init(title, destination: destination())
}
/// Creates an instance that presents `destination`, with a Text label generated from a title string.
public init<S: StringProtocol>(_ title: S, @ViewBuilder destination: () -> Destination) {
self.init(title, destination: destination())
}
}
| 33.473684 | 105 | 0.694969 |
7650e360a6011f0e75f3f1c3e1dea789dbfd5c27 | 2,166 | //
// ErrorVC.swift
// Organizer
//
// Created by Petimezas, Chris, Vodafone on 23/2/22.
//
import RxSwift
class ErrorVC: BaseVC {
// MARK: - Vars
private(set) var viewModel: ErrorViewModel
private let disposeBag = DisposeBag()
// MARK: - Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var mainTitle: UILabel!
@IBOutlet weak var subtitle: UILabel!
@IBOutlet weak var mainButton: GradientButton!
// MARK: - Inits
init(_ viewModel: ErrorViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setupBindables() {
viewModel.output
.data
.map { $0.title }
.bind(to: mainTitle.rx.text)
.disposed(by: disposeBag)
viewModel.output
.data
.map { $0.description }
.bind(to: subtitle.rx.text)
.disposed(by: disposeBag)
viewModel.output
.data
.map { $0.image }
.bind(to: imageView.rx.image)
.disposed(by: disposeBag)
viewModel.output
.data
.map { $0.buttonTitle }
.bind(to: mainButton.rx.title())
.disposed(by: disposeBag)
viewModel.output
.data
.map { $0.buttonColors }
.subscribe(onNext: { colors in
self.mainButton.applyGradient(colors: colors)
})
.disposed(by: disposeBag)
}
override func setupRxEvents() {
mainButton.rx
.tap
.subscribe(onNext: {
self.viewModel.delegate?.buttonTapped()
})
.disposed(by: disposeBag)
NotificationCenter.default
.rx.notification(UIApplication.willEnterForegroundNotification, object: nil)
.subscribe(onNext: { _ in
self.mainButton.titleLabel?.flash(numberOfFlashes: .infinity)
})
.disposed(by: disposeBag)
}
}
| 26.414634 | 88 | 0.555863 |
3a08412faa5f630bc46e2f8cd254a04f5217fc70 | 2,190 | //
// Khala
//
// Copyright (c) 2018 linhay - https://github.com/linhay
//
// 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
import Foundation
/// Packaging method
public class PseudoMethod: NSObject {
/// Function name
public let selector: Selector
/// type encoding
public let typeEncoding: String
let paramsTypes: [ObjectType]
let returnType: ObjectType
public init(method: Method) {
self.selector = method_getName(method)
if let typeEncoding = method_getTypeEncoding(method) {
self.typeEncoding = String(cString: typeEncoding)
}else{
self.typeEncoding = ""
}
/// 返回值类型
let tempReturnType = method_copyReturnType(method)
self.returnType = ObjectType(char: tempReturnType)
free(tempReturnType)
/// 获取参数类型
let arguments = method_getNumberOfArguments(method)
self.paramsTypes = (0..<arguments).map { (index) -> ObjectType in
guard let argumentType = method_copyArgumentType(method, index) else {
return ObjectType.unknown
}
let type = ObjectType(char: argumentType)
free(argumentType)
return type
}
super.init()
}
}
| 34.21875 | 82 | 0.713242 |
ef64a537d874d58a6a85728505ed8cb3125f9c4d | 12,193 | import UIKit
@IBDesignable
open class Button: UIButton {
//----------------------------------- UIColor -----------------------------------//
/// Sets a background color using setBackgroundImage by creating an image with the specifed color
///
/// - Parameters:
/// - color: Color of the background
/// - for: Which state should this background color apply to
public func set(color: UIColor?, for state: UIControl.State) {
if let color = color {
let image = UIImage.imageWithColor(color: color)
self.setBackgroundImage(image, for: state)
} else {
self.setBackgroundImage(nil, for: state)
}
}
/// Border with on the layer
@IBInspectable
public var borderWidth: CGFloat {
get { return self.layer.borderWidth }
set { self.layer.borderWidth = newValue }
}
/// Border color on the layer
@IBInspectable
public var borderColor: UIColor? {
get { return UIColor(cgColor: self.layer.borderColor!) }
set { self.layer.borderColor = newValue?.cgColor }
}
//----------------------------------- UIActivityIndicator -----------------------------------//
fileprivate var activityIndicator = UIActivityIndicatorView(style: .white)
/// ActivityIndicatorStyle for the button when its busy
public var activityIndicatorStyle: UIActivityIndicatorView.Style {
get { return self.activityIndicator.style }
set { self.activityIndicator.style = newValue }
}
fileprivate var normalTitle: String?
fileprivate var highlightedTitle: String?
fileprivate var disabledTitle: String?
fileprivate var selectedTitle: String?
fileprivate var normalImage: UIImage?
fileprivate var highlightedImage: UIImage?
fileprivate var disabledImage: UIImage?
fileprivate var selectedImage: UIImage?
/// Hides the text and shows an UIActivityIndicatorView spinning when true
open var isBusy: Bool = false {
didSet {
self.isUserInteractionEnabled = !isBusy
self.activityIndicator.tintColor = self.titleLabel?.textColor ?? self.tintColor
self.isBusy ? self.activityIndicator.startAnimating() : self.activityIndicator.stopAnimating()
if self.isBusy {
self.normalTitle = self.title(for: .normal)
self.highlightedTitle = self.title(for: .highlighted)
self.disabledTitle = self.title(for: .disabled)
self.selectedTitle = self.title(for: .selected)
self.normalImage = self.image(for: .normal)
self.highlightedImage = self.image(for: .highlighted)
self.disabledImage = self.image(for: .disabled)
self.selectedImage = self.image(for: .selected)
super.setTitle("", for: UIControl.State())
super.setImage(nil, for: UIControl.State())
} else {
self.setTitle(self.normalTitle, for: .normal)
self.setTitle(self.highlightedTitle, for: .highlighted)
self.setTitle(self.disabledTitle, for: .disabled)
self.setTitle(self.selectedTitle, for: .selected)
self.setImage(self.normalImage, for: .normal)
self.setImage(self.highlightedImage, for: .highlighted)
self.setImage(self.disabledImage, for: .disabled)
self.setImage(self.selectedImage, for: .selected)
}
}
}
open override func setTitle(_ title: String?, for state: State) {
super.setTitle(title, for: state)
switch state {
case .normal: self.normalTitle = title
case .highlighted: self.highlightedTitle = title
case .disabled: self.disabledTitle = title
case .selected: self.selectedTitle = title
default:break
}
}
open override func setImage(_ image: UIImage?, for state: State) {
super.setImage(image, for: state)
switch state {
case .normal: self.normalImage = image
case .highlighted: self.highlightedImage = image
case .disabled: self.disabledImage = image
case .selected: self.selectedImage = image
default:break
}
}
fileprivate func configureBusy() {
self.activityIndicator.color = self.titleLabel?.textColor
}
//----------------------------------- DidTapButton -----------------------------------//
public typealias DidTapButton = (Button) -> Void
/// Closure for reacting to .touchUpInside events
public var didTouchUpInside: DidTapButton? {
didSet {
if didTouchUpInside != nil {
self.addTarget(self, action: #selector(didTouchUpInside(sender:)), for: .touchUpInside)
} else {
self.removeTarget(self, action: #selector(didTouchUpInside(sender:)), for: .touchUpInside)
}
}
}
@objc
fileprivate func didTouchUpInside(sender: UIButton) {
if let handler = didTouchUpInside {
handler(self)
}
}
//----------------------------------- init -----------------------------------//
override public init(frame: CGRect) {
super.init(frame: frame)
self.configureView()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.configureView()
}
fileprivate func configureView() {
self.adjustsImageWhenHighlighted = false
self.adjustsImageWhenDisabled = false
self.activityIndicator.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.activityIndicator)
self.activityIndicator.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.activityIndicator.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
// ----------------------------- Rounded -----------------------------//
/// Corner radius with on the layer
@IBInspectable
open var cornerRadius: CGFloat {
set { self.layer.cornerRadius = newValue }
get { return self.layer.cornerRadius }
}
fileprivate func configureRadius() {
// self.clipsToBounds = self.layer.cornerRadius > 0
}
/// Should the upper left corner be rounded
@IBInspectable
open var cornerUL: Bool = false { //UpperLeft
didSet { self.updateCorners() }
}
/// Should the upper right corner be rounded
@IBInspectable
open var cornerUR: Bool = false { //UpperRight
didSet { self.updateCorners() }
}
/// Should the lower left corner be rounded
@IBInspectable
open var cornerLL: Bool = false { //LowerLeft
didSet { self.updateCorners() }
}
/// Should the lower right corner be rounded
@IBInspectable
open var cornerLR: Bool = false { //LowerRight
didSet { self.updateCorners() }
}
fileprivate func updateCorners() {
var corners: CACornerMask = CACornerMask(rawValue: 0)
if self.cornerUL { corners.insert(.layerMinXMinYCorner) }
if self.cornerUR { corners.insert(.layerMaxXMinYCorner) }
if self.cornerLL { corners.insert(.layerMinXMaxYCorner) }
if self.cornerLR { corners.insert(.layerMaxXMaxYCorner) }
self.layer.maskedCorners = corners
}
// ----------------------------- Shadow -----------------------------//
/// Applies shadow the view
@IBInspectable
open var hasShadow: Bool = false
/// Color of shadow, default .black
@IBInspectable
open var sketchColor: UIColor = .black
/// Alpha of shadow as defined in Sketch
@IBInspectable
open var sketchAlpha: Float = 0.5
/// X of shadow as defined in Sketch
@IBInspectable
open var sketchX: CGFloat = 0
/// Y of shadow as defined in Sketch
@IBInspectable
open var sketchY: CGFloat = 0
/// Blur of shadow as defined in Sketch
@IBInspectable
open var sketchBlur: CGFloat = 0
/// Spread of shadow as defined in Sketch
@IBInspectable
open var sketchSpread: CGFloat = 0
fileprivate func configureShadow() {
if !self.hasShadow { return }
self.layer.shadowColor = self.sketchColor.cgColor
self.layer.shadowOpacity = self.sketchAlpha
self.layer.shadowOffset = CGSize(width: self.sketchX, height: self.sketchY)
self.layer.shadowRadius = self.sketchBlur / 2.0
if self.sketchSpread == 0 {
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).cgPath
} else {
let dx = -self.sketchSpread
let rect = bounds.insetBy(dx: dx, dy: dx)
self.layer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: self.layer.cornerRadius).cgPath
}
}
// ----------------------------- Font -----------------------------//
/// Font for normal state
@IBInspectable
public var normalFont: UIFont?
/// Font for highlighted state
@IBInspectable
public var highlightedFont: UIFont?
/// Font for disabled state
@IBInspectable
public var disabledFont: UIFont?
/// Font for selected state
@IBInspectable
public var selectedFont: UIFont?
public func setFont(_ font: UIFont?, for state: UIControl.State) {
switch state {
case .normal:self.normalFont = font
case .highlighted: self.highlightedFont = font
case .disabled: self.disabledFont = font
case .selected: self.selectedFont = font
default:
break
}
}
fileprivate func configureFont() {
switch self.state {
case .normal: self.titleLabel?.font = self.normalFont ?? self.titleLabel?.font
case .highlighted: self.titleLabel?.font = self.highlightedFont ?? self.titleLabel?.font
case .disabled: self.titleLabel?.font = self.disabledFont ?? self.titleLabel?.font
case .selected: self.titleLabel?.font = self.selectedFont ?? self.titleLabel?.font
default:
break
}
}
// ----------------------------- Gradient -----------------------------//
fileprivate var gradientLayer = CAGradientLayer()
/// Start color if we want a button with a gradient background
@IBInspectable open var startColor: UIColor?
/// End color if we want a button with a gradient background
@IBInspectable open var endColor: UIColor?
/// Start point if we want a button with a gradient background
@IBInspectable open var startPoint: CGPoint = CGPoint(x: 0.5, y: 0)
/// End point if we want a button with a gradient background
@IBInspectable open var endPoint: CGPoint = CGPoint(x: 0.5, y: 1)
fileprivate func configureGradient() {
if let start = self.startColor, let end = self.endColor {
self.gradientLayer.frame = self.bounds
self.gradientLayer.colors = [start.cgColor, end.cgColor]
self.gradientLayer.startPoint = startPoint
self.gradientLayer.endPoint = endPoint
self.layer.insertSublayer(self.gradientLayer, at: 0)
} else {
self.gradientLayer.removeFromSuperlayer()
}
}
// ----------------------------- LifeCycle -----------------------------//
override open func layoutSubviews() {
super.layoutSubviews()
self.configureGradient()
self.configureFont()
self.configureRadius()
self.configureShadow()
self.configureBusy()
}
open override func awakeFromNib() {
super.awakeFromNib()
self.normalTitle = self.title(for: .normal)
self.highlightedTitle = self.title(for: .highlighted)
self.disabledTitle = self.title(for: .disabled)
self.selectedTitle = self.title(for: .selected)
self.normalImage = self.image(for: .normal)
self.highlightedImage = self.image(for: .highlighted)
self.disabledImage = self.image(for: .disabled)
self.selectedImage = self.image(for: .selected)
}
}
| 34.837143 | 120 | 0.605265 |
2169e5bc93669586a41188c2548e5c45b67aa642 | 7,175 | //
// XMLFeedParser.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// 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
#if canImport(FoundationXML)
import FoundationXML
#endif
/// The actual engine behind the `FeedKit` framework. `XMLFeedParser` handles
/// the parsing of RSS and Atom feeds. It is an `XMLParserDelegate` of
/// itself.
class XMLFeedParser: NSObject, XMLParserDelegate, FeedParserProtocol {
/// The Feed Type currently being parsed. The Initial value of this variable
/// is unknown until a recognizable element that matches a feed type is
/// found.
var feedType: XMLFeedType?
/// The RSS feed model.
var rssFeed: RSSFeed?
/// The Atom feed model.
var atomFeed: AtomFeed?
/// The XML Parser.
let xmlParser: XMLParser
/// An XML Feed Parser, for rss and atom feeds.
///
/// - Parameter data: A `Data` object containing an XML feed.
required init(data: Data) {
xmlParser = XMLParser(data: data)
super.init()
xmlParser.delegate = self
}
/// An XML Feed Parser, for rss and atom feeds.
///
/// - Parameter stream: An `InputStream` object containing an XML feed.
init(stream: InputStream) {
xmlParser = XMLParser(stream: stream)
super.init()
xmlParser.delegate = self
}
/// The current path along the XML's DOM elements. Path components are
/// updated to reflect the current XML element being parsed.
/// e.g. "/rss/channel/title" means it's currently parsing the channels
/// `<title>` element.
fileprivate var currentXMLDOMPath = URL(string: "/")!
/// A parsing error, if any.
var parsingError: Error?
var parseComplete = false
/// Starts parsing the feed.
func parse() -> Result<Feed, ParserError> {
_ = xmlParser.parse()
if let error = parsingError {
return .failure(.internalError(reason: error.localizedDescription))
}
guard let feedType = feedType else {
return .failure(.feedNotFound)
}
switch feedType {
case .atom:
guard let atomFeed = atomFeed else {
return .failure(.internalError(reason: "Unable to initialize atom feed model"))
}
return .success(.atom(atomFeed))
case .rdf, .rss:
guard let rssFeed = rssFeed else {
return .failure(.internalError(reason: "Unable to initialize rss feed model"))
}
return .success(.rss(rssFeed))
}
}
/// Redirects characters found between XML elements to their proper model
/// mappers based on the `currentXMLDOMPath`.
///
/// - Parameter string: The characters to map.
fileprivate func map(_ string: String) {
guard let feedType = self.feedType else { return }
switch feedType {
case .atom:
if let path = AtomPath(rawValue: currentXMLDOMPath.absoluteString) {
atomFeed?.map(string, for: path)
}
case .rdf:
if let path = RDFPath(rawValue: currentXMLDOMPath.absoluteString) {
rssFeed?.map(string, for: path)
}
case .rss:
if let path = RSSPath(rawValue: currentXMLDOMPath.absoluteString) {
rssFeed?.map(string, for: path)
}
}
}
}
// MARK: - XMLParser delegate
extension XMLFeedParser {
func parser(
_: XMLParser,
didStartElement elementName: String,
namespaceURI _: String?,
qualifiedName _: String?,
attributes attributeDict: [String: String]
) {
// Update the current path along the XML's DOM elements by appending the new component with `elementName`.
currentXMLDOMPath = currentXMLDOMPath.appendingPathComponent(elementName)
// Get the feed type from the element, if it hasn't been done yet.
guard let feedType = self.feedType else {
self.feedType = XMLFeedType(rawValue: elementName)
return
}
switch feedType {
case .atom:
if atomFeed == nil {
atomFeed = AtomFeed()
}
if let path = AtomPath(rawValue: currentXMLDOMPath.absoluteString) {
atomFeed?.map(attributeDict, for: path)
}
case .rdf:
if rssFeed == nil {
rssFeed = RSSFeed()
}
if let path = RDFPath(rawValue: currentXMLDOMPath.absoluteString) {
rssFeed?.map(attributeDict, for: path)
}
case .rss:
if rssFeed == nil {
rssFeed = RSSFeed()
}
if let path = RSSPath(rawValue: currentXMLDOMPath.absoluteString) {
rssFeed?.map(attributeDict, for: path)
}
}
}
func parser(
_: XMLParser,
didEndElement _: String,
namespaceURI _: String?,
qualifiedName _: String?
) {
// Update the current path along the XML's DOM elements by deleting last component.
currentXMLDOMPath = currentXMLDOMPath.deletingLastPathComponent()
if currentXMLDOMPath.absoluteString == "/" {
parseComplete = true
xmlParser.abortParsing()
}
}
func parser(_: XMLParser, foundCDATA CDATABlock: Data) {
guard let string = String(data: CDATABlock, encoding: .utf8) else {
xmlParser.abortParsing()
parsingError = ParserError.feedCDATABlockEncodingError(path: currentXMLDOMPath.absoluteString)
return
}
map(string)
}
func parser(_: XMLParser, foundCharacters string: String) {
map(string)
}
func parser(_: XMLParser, parseErrorOccurred parseError: Error) {
// Ignore errors that occur after a feed is successfully parsed. Some
// real-world feeds contain junk such as "[]" after the XML segment;
// just ignore this stuff.
guard !parseComplete, parsingError == nil else { return }
parsingError = parseError
}
}
| 34.330144 | 114 | 0.624111 |
eb1902a5965618abdb07d87c20101a57ec4d4b69 | 1,160 | //
// SplashScreenCoordinator.swift
// CodeGenTemplate
//
// Created by Akkharawat Chayapiwat on 10/5/18.
// Copyright © 2018 Akkharawat Chayapiwat. All rights reserved.
//
import Foundation
class SplashScreenCoordinator: Coordinator, AutoCoordinatorType {
func start(parent: Coordinator) {
let config = SplashScreenViewModelConfig()
let nibName = String(describing: SplashScreenViewController.self)
let bundle = Bundle(for: SplashScreenViewController.self)
let vc = SplashScreenViewController(nibName: nibName, bundle: bundle)
let viewModel = SplashScreenViewModel(dependencies: self.dependency, coordinator: self, config: config)
vc.viewModel = viewModel
self.navigationController?.setViewControllers([vc], animated: true)
parent.replaceAllCoordinator(childCoordinator: self)
}
func navigateToHome() {
let homeCoordinator = HomeScreenCoordinator.init(navigationController: self.navigationController,
dependency: self.dependency)
homeCoordinator.start(parent: self)
}
}
| 35.151515 | 111 | 0.684483 |
fea0782bbe2b4f2acb6ad84974fa0e3c32a532ce | 1,288 | //
// ResultData.swift
// sofastcar
//
// Created by Woobin Cheon on 2020/09/08.
// Copyright © 2020 김광수. All rights reserved.
//
import Foundation
//{
// "id": 240,
// "name": "복정역 공영주차장",
// "address": "서울 송파구 장지동 561-55",
// "region": "SEOUL",
// "latitude": 37.469361,
// "longitude": 127.1259747,
// "sub_info": "복정역",
// "detail_info": "지상 1층",
// "type": "지상",
// "operating_time": "24시간"
//}
struct SocarZoneData: Decodable {
let id: Int
let name: String
let address: String
let region: String
let lat: Double
let lng: Double
let image: String?
let subInfo: String
let detailInfo: String
let type: String
let operTime: String
enum CodingKeys: String, CodingKey {
case lat = "latitude"
case lng = "longitude"
case subInfo = "sub_info"
case detailInfo = "detail_info"
case operTime = "operating_time"
case id
case name
case address
case region
case image
case type
}
}
extension SocarZoneData {
static func selectZoneByID(_ socarZoneID: Int) -> Resource<SocarZoneData> {
let socarZoneUrl = URL(string: "https://sofastcar.moorekwon.xyz/carzones/\(socarZoneID)")!
return Resource(url: socarZoneUrl)
}
}
| 21.466667 | 94 | 0.606366 |
0152d3445ec7dd04574b11a7d06ce8feeed04748 | 3,366 | import UIKit
public protocol PlaceholderDesignable: class {
var placeholderThemeColor: String? { get set }
var placeholderTxt: String? { get set }
}
extension PlaceholderDesignable where Self: BaseUITextField {
public var placeholderTxt: String? { get { return "" } set {} }
internal func configurePlaceholderColor() {
if placeholderThemeColor == nil {
placeholderThemeColor = "black";
}
let placeholderColor:UIColor? = UIColor.color(forKey: placeholderThemeColor);
let text = placeholder ?? placeholderTxt
if let placeholderColor = placeholderColor, let placeholder = text {
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: placeholderColor])
}
}
}
extension PlaceholderDesignable where Self: BaseUITextView {
internal func configure(placeholderLabel: UILabel, placeholderLabelConstraints: inout [NSLayoutConstraint]) {
if placeholderThemeColor == nil {
placeholderThemeColor = "black";
}
let placeholderColor:UIColor? = UIColor.color(forKey: placeholderThemeColor);
placeholderLabel.font = font
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
placeholderLabel.text = placeholderTxt
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = .clear
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholderLabel)
update(placeholderLabel, using: &placeholderLabelConstraints)
}
internal func update(_ placeholderLabel: UILabel, using constraints: inout [NSLayoutConstraint]) {
var format = "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]-(\(textContainerInset.left + textContainer.lineFragmentPadding))-|"
var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: ["placeholder": placeholderLabel])
format = "V:|-(\(textContainerInset.top))-[placeholder]"
newConstraints += NSLayoutConstraint.constraints(withVisualFormat: format,
options: [], metrics: nil,
views: ["placeholder": placeholderLabel])
let constant = -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0)
newConstraints.append(NSLayoutConstraint(item: placeholderLabel,
attribute: .width,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: 1.0,
constant: constant))
removeConstraints(constraints)
addConstraints(newConstraints)
constraints = newConstraints
}
}
| 43.714286 | 172 | 0.585859 |
38603cc0fe47542aa594af367c5059dd136d9fd6 | 1,524 |
class LinkedList<T: Equatable> {
let data: T
var next :LinkedList<T>?
var first :LinkedList<T>?
var last :LinkedList<T>?
init(data: T) {
self.data = data
}
func insert(data :T) {
if first == nil {
first = LinkedList<T>(data: data)
last = first
last?.next = nil
} else {
last?.next = LinkedList<T>(data: data)
last = last?.next
}
}
func remove(data: T) {
guard first != nil, last != nil else{
return
}
var temp = first
while (temp != last?.next) {
if temp?.next?.data == data {
temp?.next = temp?.next?.next
return
}
temp = temp?.next
}
}
func printList() {
print("Printing list")
var temp = first
while (temp != last?.next) {
print("\(temp!.data)")
temp = temp?.next
}
}
}
extension LinkedList: Equatable {
public static func ==(lhs: LinkedList, rhs: LinkedList) -> Bool {
return lhs.data == rhs.data
}
}
var deepList = LinkedList<Int>(data: 10)
deepList.insert(data: 1)
deepList.insert(data: 2)
deepList.insert(data: 3)
deepList.insert(data: 4)
deepList.printList()
deepList.remove(data: 5)
deepList.printList()
deepList.remove(data: 3)
deepList.printList()
deepList.insert(data: 5)
deepList.printList()
| 15.71134 | 69 | 0.498688 |
46ca939203324dbd1336fac3c2283560d3611a32 | 158 | //
// File.swift
// Boar
//
// Created by Peter Ovchinnikov on 3/19/18.
// Copyright © 2018 Peter Ovchinnikov. All rights reserved.
//
import Foundation
| 15.8 | 60 | 0.677215 |
1cd877b22e767b088cac779b2c74df79a412289e | 776 | //
// Colors.swift
// Monty Hall App
//
// Created by Diogo Infante on 02/11/21.
//
import UIKit
/// UIColor Extensions
extension UIColor {
/// Initializes a UIColor from the absolute color values instead of normalized
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat = 1) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: alpha)
}
/// App colors
static var mYellow: UIColor { return UIColor(r: 249, g: 219, b: 87) }
static var mGray: UIColor { return UIColor(r: 94, g: 94, b: 94) }
static var mDarkGray: UIColor { return UIColor(r: 33, g: 33, b: 33) }
static var mIce: UIColor { return UIColor(r: 242, g: 237, b: 228) }
static var mPallete1: UIColor { return UIColor(r: 248, g: 214, b: 151) }
}
| 33.73913 | 82 | 0.637887 |
dd95e01d28592eea0359785fd488b4e765f6836f | 286 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
// Distributed under the terms of the MIT license
class a<b , d
{
typealias e = a<c<h> , d>
}
struct c<d where d = e
| 26 | 87 | 0.723776 |
694b1e5f6220944529ecff5443dd7e82824cec4e | 1,641 | //
// Disposables.swift
// Rx
//
// Created by Mohsen Ramezanpoor on 01/08/2016.
// Copyright © 2016 Mohsen Ramezanpoor. All rights reserved.
//
import Foundation
/**
A collection of utility methods for common disposable operations.
*/
public struct Disposables {
private init() {}
}
public extension Disposables {
private static let noOp: Disposable = NopDisposable()
/**
Creates a disposable that does nothing on disposal.
*/
static func create() -> Disposable {
return noOp
}
/**
Creates a disposable with the given disposables.
*/
static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable {
return CompositeDisposable(disposable1, disposable2, disposable3)
}
/**
Creates a disposable with the given disposables.
*/
static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable {
var disposables = disposables
disposables.append(disposable1)
disposables.append(disposable2)
disposables.append(disposable3)
return CompositeDisposable(disposables: disposables)
}
/**
Creates a disposable with the given disposables.
*/
static func create(_ disposables: [Disposable]) -> Cancelable {
switch disposables.count {
case 2:
return Disposables.create(disposables[0], disposables[1])
default:
return CompositeDisposable(disposables: disposables)
}
}
}
| 26.467742 | 150 | 0.654479 |
67093573f6f2290fb88bfe8514794bc330ddc85a | 3,265 | //
// MMPageViewController.swift
// MMUIKit
//
// Created by Mingle on 2022/2/27.
//
import UIKit
open class MMPageViewController: UIViewController, MMLoopViewDelegate {
public var categoryView: MMPageCategoryView? {
didSet {
oldValue?.removeFromSuperview()
if categoryView != nil {
view.addSubview(categoryView!)
categoryView?.clickItem = { [weak self] (_, index) in
guard let `self` = self else { return }
self.index = index
}
}
}
}
public var index: Int {
set {
scrollView.index = newValue
}
get {
return scrollView.index
}
}
public var didScrollToIndex: ((MMPageViewController, Int) -> Void)?
private lazy var scrollView: MMLoopView = {
let view = MMLoopView()
view.loopEnable = false
view.delegate = self
view.backgroundColor = .clear
view.register(_MMPageSubCell.self, forCellWithReuseIdentifier: "cell")
return view
} ()
public var subViewControllers = [UIViewController]() {
didSet {
oldValue.forEach { vc in
vc.removeFromParentViewController()
}
subViewControllers.forEach { vc in
self.addChildViewController(vc)
}
if scrollView.superview != nil {
scrollView.reloadData()
}
}
}
open override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.addSubview(scrollView)
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
categoryView?.frame = CGRect(x: 0, y: 0, width: view.mWidth, height: categoryView?.mHeight ?? 0)
if #available(iOS 11.0, *) {
if categoryView != nil && self.view.safeAreaInsets.top > 0 {
categoryView?.mTop = self.view.safeAreaInsets.top
}
}
scrollView.frame = CGRect(x: 0, y: categoryView?.mBottom ?? 0, width: view.mWidth, height: view.mHeight - (categoryView?.mBottom ?? 0))
}
public func numberOfLoopView(_ loopView: MMLoopView) -> Int {
return subViewControllers.count
}
public func cellForIndexOfLoopView(_ loopView: MMLoopView, _ index: Int) -> UICollectionViewCell {
let cell = loopView.dequeueReusableCell(withReuseIdentifier: "cell", for: index) as! _MMPageSubCell
cell.container = subViewControllers[index].view
return cell
}
public func didScrollToIndexOfLoopView(_ loopView: MMLoopView, _ index: Int) {
categoryView?.index = index
didScrollToIndex?(self, index)
}
}
private class _MMPageSubCell: UICollectionViewCell {
var container: UIView? {
didSet {
oldValue?.removeFromSuperview()
guard let view = container else { return }
contentView.addSubview(view)
view.frame = contentView.bounds
}
}
override func layoutSubviews() {
super.layoutSubviews()
container?.frame = contentView.bounds
}
}
| 29.681818 | 143 | 0.584992 |
f905914d71edebf55de4ceac95babb37a88d1669 | 1,768 | //
// RemoteImage.swift
// SwiftUI_SwiftPackageManager
//
// Created by Alex Logan on 28/03/2022.
//
import SwiftUI
/// A basic, iOS 13 compatible, remote image loader.
struct RemoteImage: View {
@StateObject var imageLoader = RemoteImageLoader()
var url: URL?
var body: some View {
Group {
switch imageLoader.imageState {
case .idle:
Rectangle().foregroundColor(.clear)
.onAppear {
imageLoader.url = url
imageLoader.loadImage()
}
case .loaded(let uiImage):
Image(uiImage: uiImage)
.resizable()
}
}
}
}
enum RemoteImageState: Equatable {
case idle, loaded(UIImage)
}
class RemoteImageLoader: ObservableObject {
@Published var imageState: RemoteImageState = .idle
var dataTask: URLSessionDataTask?
var url: URL? {
willSet {
if newValue != url {
dataTask?.cancel()
updateImageState(to: .idle)
}
}
}
func loadImage() {
guard imageState == .idle, let url = url else {
return
}
dataTask = URLSession.shared.dataTask(with: url) { data, _, _ in
guard let data = data else {
return
}
if let image = UIImage(data: data) {
self.updateImageState(to: .loaded(image))
}
}
dataTask?.resume()
}
private func updateImageState(to state: RemoteImageState) {
DispatchQueue.main.async {
withAnimation {
self.imageState = state
}
}
}
}
| 23.891892 | 72 | 0.506222 |
695c8f7ddb7322260ef131329cebde578a90fb88 | 6,632 | import Foundation
import UIKit
import Display
import SwiftSignalKit
import Postbox
import TelegramCore
import SyncCore
import TelegramPresentationData
import TelegramUIPreferences
import ItemListUI
import PresentationDataUtils
import AccountContext
private enum PeerType {
case contact
case otherPrivate
case group
case channel
}
private final class SaveIncomingMediaControllerArguments {
let toggle: (PeerType) -> Void
init(toggle: @escaping (PeerType) -> Void) {
self.toggle = toggle
}
}
enum SaveIncomingMediaSection: ItemListSectionId {
case peers
}
private enum SaveIncomingMediaEntry: ItemListNodeEntry {
case header(PresentationTheme, String)
case contacts(PresentationTheme, String, Bool)
case otherPrivate(PresentationTheme, String, Bool)
case groups(PresentationTheme, String, Bool)
case channels(PresentationTheme, String, Bool)
var section: ItemListSectionId {
return SaveIncomingMediaSection.peers.rawValue
}
var stableId: Int32 {
switch self {
case .header:
return 0
case .contacts:
return 1
case .otherPrivate:
return 2
case .groups:
return 3
case .channels:
return 4
}
}
static func <(lhs: SaveIncomingMediaEntry, rhs: SaveIncomingMediaEntry) -> Bool {
return lhs.stableId < rhs.stableId
}
func item(presentationData: ItemListPresentationData, arguments: Any) -> ListViewItem {
let arguments = arguments as! SaveIncomingMediaControllerArguments
switch self {
case let .header(theme, text):
return ItemListSectionHeaderItem(presentationData: presentationData, text: text, sectionId: self.section)
case let .contacts(theme, text, value):
return ItemListSwitchItem(presentationData: presentationData, title: text, value: value, enableInteractiveChanges: true, enabled: true, sectionId: self.section, style: .blocks, updated: { value in
arguments.toggle(.contact)
})
case let .otherPrivate(theme, text, value):
return ItemListSwitchItem(presentationData: presentationData, title: text, value: value, enableInteractiveChanges: true, enabled: true, sectionId: self.section, style: .blocks, updated: { value in
arguments.toggle(.otherPrivate)
})
case let .groups(theme, text, value):
return ItemListSwitchItem(presentationData: presentationData, title: text, value: value, enableInteractiveChanges: true, enabled: true, sectionId: self.section, style: .blocks, updated: { value in
arguments.toggle(.group)
})
case let .channels(theme, text, value):
return ItemListSwitchItem(presentationData: presentationData, title: text, value: value, enableInteractiveChanges: true, enabled: true, sectionId: self.section, style: .blocks, updated: { value in
arguments.toggle(.channel)
})
}
}
}
private func saveIncomingMediaControllerEntries(presentationData: PresentationData, settings: MediaAutoDownloadSettings) -> [SaveIncomingMediaEntry] {
var entries: [SaveIncomingMediaEntry] = []
entries.append(.header(presentationData.theme, presentationData.strings.SaveIncomingPhotosSettings_From))
entries.append(.contacts(presentationData.theme, presentationData.strings.AutoDownloadSettings_Contacts, settings.saveDownloadedPhotos.contacts))
entries.append(.otherPrivate(presentationData.theme, presentationData.strings.AutoDownloadSettings_PrivateChats, settings.saveDownloadedPhotos.otherPrivate))
entries.append(.groups(presentationData.theme, presentationData.strings.AutoDownloadSettings_GroupChats, settings.saveDownloadedPhotos.groups))
entries.append(.channels(presentationData.theme, presentationData.strings.AutoDownloadSettings_Channels, settings.saveDownloadedPhotos.channels))
return entries
}
func saveIncomingMediaController(context: AccountContext) -> ViewController {
let arguments = SaveIncomingMediaControllerArguments(toggle: { type in
let _ = updateMediaDownloadSettingsInteractively(accountManager: context.sharedContext.accountManager, { settings in
var settings = settings
switch type {
case .contact:
settings.saveDownloadedPhotos.contacts = !settings.saveDownloadedPhotos.contacts
case .otherPrivate:
settings.saveDownloadedPhotos.otherPrivate = !settings.saveDownloadedPhotos.otherPrivate
case .group:
settings.saveDownloadedPhotos.groups = !settings.saveDownloadedPhotos.groups
case .channel:
settings.saveDownloadedPhotos.channels = !settings.saveDownloadedPhotos.channels
}
return settings
}).start()
})
let signal = combineLatest(queue: .mainQueue(), context.sharedContext.presentationData, context.sharedContext.accountManager.sharedData(keys: [ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings]))
|> deliverOnMainQueue
|> map { presentationData, sharedData -> (ItemListControllerState, (ItemListNodeState, Any)) in
let automaticMediaDownloadSettings: MediaAutoDownloadSettings
if let value = sharedData.entries[ApplicationSpecificSharedDataKeys.automaticMediaDownloadSettings] as? MediaAutoDownloadSettings {
automaticMediaDownloadSettings = value
} else {
automaticMediaDownloadSettings = MediaAutoDownloadSettings.defaultSettings
}
let controllerState = ItemListControllerState(presentationData: ItemListPresentationData(presentationData), title: .text(presentationData.strings.SaveIncomingPhotosSettings_Title), leftNavigationButton: nil, rightNavigationButton: nil, backNavigationButton: ItemListBackButton(title: presentationData.strings.Common_Back), animateChanges: false)
let listState = ItemListNodeState(presentationData: ItemListPresentationData(presentationData), entries: saveIncomingMediaControllerEntries(presentationData: presentationData, settings: automaticMediaDownloadSettings), style: .blocks, emptyStateItem: nil, animateChanges: false)
return (controllerState, (listState, arguments))
}
let controller = ItemListController(context: context, state: signal)
return controller
}
| 48.057971 | 353 | 0.711852 |
fee9be81a92262a778f4070ceba7c30996b46ac0 | 12,814 | /*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
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 AST
public struct LexicalParentAssignment {
private let _assignmentVisitor = AssignmentVisitor()
public init() {}
public func assign(_ collection: ASTUnitCollection) {
return collection.forEach(assign)
}
private func assign(_ unit: ASTUnit) {
do {
_ = try _assignmentVisitor.traverse(unit.translationUnit)
unit.translationUnit.assignedLexicalParent()
} catch {}
}
}
private class AssignmentVisitor : ASTVisitor {
func visit(_ topLevelDecl: TopLevelDeclaration) throws -> Bool {
for stmt in topLevelDecl.statements {
stmt.setLexicalParent(topLevelDecl)
}
return true
}
func visit(_ codeBlock: CodeBlock) throws -> Bool {
for stmt in codeBlock.statements {
stmt.setLexicalParent(codeBlock)
}
return true
}
func visit(_ decl: ClassDeclaration) throws -> Bool {
for member in decl.members {
switch member {
case .declaration(let d):
d.setLexicalParent(decl)
case .compilerControl(let s):
s.setLexicalParent(decl)
}
}
return true
}
func visit(_ decl: ConstantDeclaration) throws -> Bool {
for pttrnInit in decl.initializerList {
pttrnInit.initializerExpression?.setLexicalParent(decl)
}
return true
}
func visit(_ decl: DeinitializerDeclaration) throws -> Bool {
decl.body.setLexicalParent(decl)
return true
}
func visit(_ decl: EnumDeclaration) throws -> Bool {
for member in decl.members {
switch member {
case .declaration(let d):
d.setLexicalParent(decl)
case .compilerControl(let s):
s.setLexicalParent(decl)
default:
continue
}
}
return true
}
func visit(_ decl: ExtensionDeclaration) throws -> Bool {
for member in decl.members {
switch member {
case .declaration(let d):
d.setLexicalParent(decl)
case .compilerControl(let s):
s.setLexicalParent(decl)
}
}
return true
}
func visit(_ decl: FunctionDeclaration) throws -> Bool {
decl.body?.setLexicalParent(decl)
for param in decl.signature.parameterList {
param.defaultArgumentClause?.setLexicalParent(decl)
}
return true
}
func visit(_ decl: InitializerDeclaration) throws -> Bool {
decl.body.setLexicalParent(decl)
for param in decl.parameterList {
param.defaultArgumentClause?.setLexicalParent(decl)
}
return true
}
func visit(_ decl: StructDeclaration) throws -> Bool {
for member in decl.members {
switch member {
case .declaration(let d):
d.setLexicalParent(decl)
case .compilerControl(let s):
s.setLexicalParent(decl)
}
}
return true
}
func visit(_ decl: SubscriptDeclaration) throws -> Bool {
if case .codeBlock(let codeBlock) = decl.body {
codeBlock.setLexicalParent(decl)
}
for param in decl.parameterList {
param.defaultArgumentClause?.setLexicalParent(decl)
}
return true
}
func visit(_ decl: VariableDeclaration) throws -> Bool {
switch decl.body {
case .initializerList(let initList):
for pttrnInit in initList {
pttrnInit.initializerExpression?.setLexicalParent(decl)
}
case .codeBlock(_, _, let codeBlock):
codeBlock.setLexicalParent(decl)
default:
break
}
return true
}
func visit(_ stmt: DeferStatement) throws -> Bool {
stmt.codeBlock.setLexicalParent(stmt)
return true
}
func visit(_ stmt: DoStatement) throws -> Bool {
stmt.codeBlock.setLexicalParent(stmt)
for catchClause in stmt.catchClauses {
catchClause.codeBlock.setLexicalParent(stmt)
catchClause.whereExpression?.setLexicalParent(stmt)
}
return true
}
func visit(_ stmt: ForInStatement) throws -> Bool {
stmt.codeBlock.setLexicalParent(stmt)
stmt.collection.setLexicalParent(stmt)
stmt.item.whereClause?.setLexicalParent(stmt)
return true
}
func visit(_ stmt: GuardStatement) throws -> Bool {
stmt.codeBlock.setLexicalParent(stmt)
for condition in stmt.conditionList {
switch condition {
case .expression(let expr):
expr.setLexicalParent(stmt)
case .case(_, let expr):
expr.setLexicalParent(stmt)
case .let(_, let expr):
expr.setLexicalParent(stmt)
case .var(_, let expr):
expr.setLexicalParent(stmt)
default:
continue
}
}
return true
}
func visit(_ stmt: IfStatement) throws -> Bool {
stmt.codeBlock.setLexicalParent(stmt)
for condition in stmt.conditionList {
switch condition {
case .expression(let expr):
expr.setLexicalParent(stmt)
case .case(_, let expr):
expr.setLexicalParent(stmt)
case .let(_, let expr):
expr.setLexicalParent(stmt)
case .var(_, let expr):
expr.setLexicalParent(stmt)
default:
continue
}
}
switch stmt.elseClause {
case .else(let codeBlock)?:
codeBlock.setLexicalParent(stmt)
case .elseif(let elseIfStmt)?:
elseIfStmt.setLexicalParent(stmt)
default:
break
}
return true
}
func visit(_ stmt: LabeledStatement) throws -> Bool {
stmt.statement.setLexicalParent(stmt)
return true
}
func visit(_ stmt: RepeatWhileStatement) throws -> Bool {
stmt.codeBlock.setLexicalParent(stmt)
stmt.conditionExpression.setLexicalParent(stmt)
return true
}
func visit(_ stmt: ReturnStatement) throws -> Bool {
stmt.expression?.setLexicalParent(stmt)
return true
}
func visit(_ stmt: SwitchStatement) throws -> Bool {
stmt.expression.setLexicalParent(stmt)
for c in stmt.cases {
switch c {
case let .case(items, stmts):
for i in items {
i.whereExpression?.setLexicalParent(stmt)
}
for s in stmts {
s.setLexicalParent(stmt)
}
case .default(let stmts):
for s in stmts {
s.setLexicalParent(stmt)
}
}
}
return true
}
func visit(_ stmt: ThrowStatement) throws -> Bool {
stmt.expression.setLexicalParent(stmt)
return true
}
func visit(_ stmt: WhileStatement) throws -> Bool {
stmt.codeBlock.setLexicalParent(stmt)
for condition in stmt.conditionList {
switch condition {
case .expression(let expr):
expr.setLexicalParent(stmt)
case .case(_, let expr):
expr.setLexicalParent(stmt)
case .let(_, let expr):
expr.setLexicalParent(stmt)
case .var(_, let expr):
expr.setLexicalParent(stmt)
default:
continue
}
}
return true
}
func visit(_ expr: AssignmentOperatorExpression) throws -> Bool {
expr.leftExpression.setLexicalParent(expr)
expr.rightExpression.setLexicalParent(expr)
return true
}
func visit(_ expr: BinaryOperatorExpression) throws -> Bool {
expr.leftExpression.setLexicalParent(expr)
expr.rightExpression.setLexicalParent(expr)
return true
}
func visit(_ expr: ClosureExpression) throws -> Bool {
for stmt in expr.statements ?? [] {
stmt.setLexicalParent(expr)
}
return true
}
func visit(_ expr: ExplicitMemberExpression) throws -> Bool {
switch expr.kind {
case .tuple(let e, _):
e.setLexicalParent(expr)
case .namedType(let e, _):
e.setLexicalParent(expr)
case .generic(let e, _, _):
e.setLexicalParent(expr)
case .argument(let e, _, _):
e.setLexicalParent(expr)
}
return true
}
func visit(_ expr: ForcedValueExpression) throws -> Bool {
expr.postfixExpression.setLexicalParent(expr)
return true
}
func visit(_ expr: FunctionCallExpression) throws -> Bool {
expr.postfixExpression.setLexicalParent(expr)
for arg in expr.argumentClause ?? [] {
switch arg {
case .expression(let e):
e.setLexicalParent(expr)
case .namedExpression(_, let e):
e.setLexicalParent(expr)
case .memoryReference(let e):
e.setLexicalParent(expr)
case .namedMemoryReference(_, let e):
e.setLexicalParent(expr)
default:
continue
}
}
expr.trailingClosure?.setLexicalParent(expr)
return true
}
func visit(_ expr: InitializerExpression) throws -> Bool {
expr.postfixExpression.setLexicalParent(expr)
return true
}
func visit(_ expr: KeyPathStringExpression) throws -> Bool {
expr.expression.setLexicalParent(expr)
return true
}
func visit(_ expr: LiteralExpression) throws -> Bool {
switch expr.kind {
case .interpolatedString(let es, _):
for e in es {
e.setLexicalParent(expr)
}
case .array(let es):
for e in es {
e.setLexicalParent(expr)
}
case .dictionary(let d):
for entry in d {
entry.key.setLexicalParent(expr)
entry.value.setLexicalParent(expr)
}
default:
break
}
return true
}
func visit(_ expr: OptionalChainingExpression) throws -> Bool {
expr.postfixExpression.setLexicalParent(expr)
return true
}
func visit(_ expr: ParenthesizedExpression) throws -> Bool {
expr.expression.setLexicalParent(expr)
return true
}
func visit(_ expr: PostfixOperatorExpression) throws -> Bool {
expr.postfixExpression.setLexicalParent(expr)
return true
}
func visit(_ expr: PostfixSelfExpression) throws -> Bool {
expr.postfixExpression.setLexicalParent(expr)
return true
}
func visit(_ expr: PrefixOperatorExpression) throws -> Bool {
expr.postfixExpression.setLexicalParent(expr)
return true
}
func visit(_ expr: SelectorExpression) throws -> Bool {
switch expr.kind {
case .selector(let e):
e.setLexicalParent(expr)
case .getter(let e):
e.setLexicalParent(expr)
case .setter(let e):
e.setLexicalParent(expr)
default:
break
}
return true
}
func visit(_ expr: SelfExpression) throws -> Bool {
if case .subscript(let args) = expr.kind {
for arg in args {
arg.expression.setLexicalParent(expr)
}
}
return true
}
func visit(_ expr: SequenceExpression) throws -> Bool {
for element in expr.elements {
switch element {
case .expression(let e):
e.setLexicalParent(expr)
case .ternaryConditionalOperator(let e):
e.setLexicalParent(expr)
default:
continue
}
}
return true
}
func visit(_ expr: SubscriptExpression) throws -> Bool {
expr.postfixExpression.setLexicalParent(expr)
for arg in expr.arguments {
arg.expression.setLexicalParent(expr)
}
return true
}
func visit(_ expr: SuperclassExpression) throws -> Bool {
if case .subscript(let args) = expr.kind {
for arg in args {
arg.expression.setLexicalParent(expr)
}
}
return true
}
func visit(_ expr: TernaryConditionalOperatorExpression) throws -> Bool {
expr.conditionExpression.setLexicalParent(expr)
expr.trueExpression.setLexicalParent(expr)
expr.falseExpression.setLexicalParent(expr)
return true
}
func visit(_ expr: TryOperatorExpression) throws -> Bool {
switch expr.kind {
case .try(let e):
e.setLexicalParent(expr)
case .forced(let e):
e.setLexicalParent(expr)
case .optional(let e):
e.setLexicalParent(expr)
}
return true
}
func visit(_ expr: TupleExpression) throws -> Bool {
for element in expr.elementList {
element.expression.setLexicalParent(expr)
}
return true
}
func visit(_ expr: TypeCastingOperatorExpression) throws -> Bool {
switch expr.kind {
case .check(let e, _):
e.setLexicalParent(expr)
case .cast(let e, _):
e.setLexicalParent(expr)
case .conditionalCast(let e, _):
e.setLexicalParent(expr)
case .forcedCast(let e, _):
e.setLexicalParent(expr)
}
return true
}
}
fileprivate extension Statement {
fileprivate func setLexicalParent(_ parentNode: ASTNode) {
if let node = self as? ASTNode {
node.setLexicalParent(parentNode)
}
}
}
| 24.086466 | 76 | 0.657952 |
4b5c74276c44fdad324e172e88b72e71a69b8515 | 2,288 | //
// SceneDelegate.swift
// lenddoDemo
//
// Created by iOS dev on 31/03/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.169811 | 147 | 0.712413 |
fca6679fdbe1180b6e4bf724770f7a0a9417a1c4 | 2,199 | //
// AppDelegate.swift
// RetroCalculator
//
// Created by Noi-Ariella Baht Israel on 3/27/17.
// Copyright © 2017 Plant A Seed of Code. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.787234 | 285 | 0.755798 |
48aad1d5e4c9dc201ed73dad0fa58dbfb802ec3a | 1,027 | //
// PopcornNavigationBar.swift
// SwiftDemoProject
//
//
// Copyright © 2019 Thuy Vu. All rights reserved.
//
import UIKit
class PopcornNavigationBar: UIView {
@IBOutlet weak var backBtn: UIButton!
@IBOutlet weak var settingsBtn: UIButton!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let view = Bundle.main.loadNibNamed("PopcornNavigationBar", owner: self, options: nil)?[0] as! UIView
self.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor),
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor),
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor)
])
}
func hideBackBtn() {
backBtn.isHidden = true
}
func hideSettingsBtn() {
settingsBtn.isHidden = true
}
}
| 27.026316 | 105 | 0.736125 |
e20da4416d7d53214a074c6e4c2e7b4c1dfa0cad | 1,493 | //
// DetailViewController.swift
// Taasky
//
// Created by Audrey M Tam on 18/03/2015.
// Copyright (c) 2015 Ray Wenderlich. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var backgroundImageView: UIImageView!
var hamburgerView: HamburgerView?
override func viewDidLoad() {
super.viewDidLoad()
navigationController!.navigationBar.clipsToBounds = true
// load hamburger view
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(hamburgerViewTapped))
hamburgerView = HamburgerView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
hamburgerView!.addGestureRecognizer(tapGestureRecognizer)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: hamburgerView!)
}
var menuItem: NSDictionary? {
didSet {
if let newMenuItem = menuItem {
view.backgroundColor = UIColor(colorArray: newMenuItem["colors"] as! NSArray)
backgroundImageView?.image = UIImage(named: newMenuItem["bigImage"] as! String)
}
}
}
@objc func hamburgerViewTapped() {
let navigationController = parent as! UINavigationController
let containerViewController = navigationController.parent as! ContainerViewController
containerViewController.hideOrShowMenu(show: !containerViewController.showingMenu, animated: true)
}
}
| 33.931818 | 111 | 0.685867 |
ff1a259acb421c4e5bb69084c9999ec52d7b4567 | 5,037 | //
// NotificationTableViewCell.swift
// CNodeJS-Swift
//
// Created by H on 2018/7/26.
// Copyright © 2018年 H. All rights reserved.
//
import UIKit
import SnapKit
import Kingfisher
class NotificationTableViewCell: UITableViewCell {
var avatar: UIImageView = {
var image = UIImageView()
image.layer.masksToBounds = true
image.layer.cornerRadius = 4
return image
}()
var usernameLabel: UILabel = {
var label = UILabel()
label.font = UIFont.systemFont(ofSize: 13)
return label
}()
var timeLabel: UILabel = {
var label = UILabel()
label.font = UIFont.systemFont(ofSize: 13)
return label
}()
var statusLabel: UILabel = {
var label = UILabel()
label.font = UIFont.systemFont(ofSize: 13)
return label
}()
var descLabel: UILabel = {
var label = UILabel()
label.font = UIFont.systemFont(ofSize: 13)
label.numberOfLines = 0
return label
}()
var titleLabel: UILabelPadding = {
var label = UILabelPadding(withInsets: 7,7,7,7)
label.font = UIFont.systemFont(ofSize: 15)
label.numberOfLines = 0
return label
}()
// 装上面定义的那些元素的容器
var contentPanel = UIView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
let selectedBackgroundView = UIView()
self.selectedBackgroundView = selectedBackgroundView
self.contentView.addSubview(self.contentPanel)
self.contentPanel.addSubview(avatar)
self.contentPanel.addSubview(usernameLabel)
self.contentPanel.addSubview(timeLabel)
self.contentPanel.addSubview(statusLabel)
self.contentPanel.addSubview(descLabel)
self.contentPanel.addSubview(titleLabel)
self.themeChangedHandler = {[weak self] (style) -> Void in
self?.usernameLabel.textColor = AppColor.colors.usernameColor
self?.timeLabel.textColor = AppColor.colors.timeColor
self?.statusLabel.textColor = AppColor.colors.usernameColor
self?.descLabel.textColor = AppColor.colors.timeColor
self?.titleLabel.backgroundColor = AppColor.colors.backgroundColor
self?.titleLabel.textColor = AppColor.colors.titleColor
self?.contentPanel.backgroundColor = AppColor.colors.cellBackgroundColor
self?.backgroundColor = AppColor.colors.backgroundColor
selectedBackgroundView.backgroundColor = AppColor.colors.backgroundColor
}
contentPanel.snp.makeConstraints { (make) in
make.top.left.right.equalTo(self.contentView)
make.bottom.equalTo(self.contentView.snp.bottom).offset(-8)
}
avatar.snp.makeConstraints { (make) in
make.top.left.equalTo(16)
make.width.height.equalTo(32)
}
usernameLabel.snp.makeConstraints { (make) in
make.left.equalTo(avatar.snp.right).offset(10)
make.top.equalTo(avatar.snp.top)
}
timeLabel.snp.makeConstraints { (make) in
make.bottom.equalTo(avatar.snp.bottom)
make.left.equalTo(usernameLabel.snp.left)
}
statusLabel.snp.makeConstraints { (make) in
make.top.equalTo(usernameLabel.snp.top)
make.right.equalTo(-16)
}
descLabel.snp.makeConstraints { (make) in
make.left.equalTo(avatar.snp.left)
make.top.equalTo(avatar.snp.bottom).offset(10)
make.right.equalTo(statusLabel.snp.right)
}
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(descLabel.snp.bottom).offset(10)
make.left.equalTo(avatar.snp.left)
make.right.equalTo(statusLabel.snp.right)
make.bottom.equalTo(-16)
}
}
func bind(_ message: Message) {
avatar.kf.setImage(with: URL(string: message.author.avatar_url!))
usernameLabel.text = message.author.loginname
timeLabel.text = message.reply.create_at?.getElapsedInterval()
if message.has_read {
statusLabel.textColor = AppColor.colors.usernameColor
} else {
statusLabel.textColor = AppColor.colors.tabColor
}
statusLabel.text = message.has_read ? NSLocalizedString("read", comment: "") : NSLocalizedString("unread", comment: "")
switch message.type {
case "at":
descLabel.text = "\(message.author.loginname!)\(NSLocalizedString("note_at_msg", comment: ""))"
case "reply":
descLabel.text = "\(message.author.loginname!)\(NSLocalizedString("note_reply_msg", comment: ""))"
default:
print("")
}
titleLabel.text = message.topic.title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 36.5 | 127 | 0.627358 |
4b564bc11406e8efdb79739ff7b1226862efbb04 | 8,348 | //
// ImageOverlay.swift
// ImageOverlay
//
// Created by Toshihiro Suzuki on 2017/11/09.
// Copyright © 2017 toshi0383. All rights reserved.
//
import AVFoundation
import UIKit
extension UIImageView: NameSpaceCompatible { }
// private struct AssociatedKeys {
// static var overlayContentView = "ImageOverlay.overlayContentView"
// }
extension NameSpace where Base: UIImageView {
/// Clear overlays from this UIImageView
///
/// On tvOS 10 or earlier, this nil-outs `UIImageView.image` property.
/// On tvOS 11, this removes added subviews from `UIImageView.overlayContentView`.
/// Pass somewhat placeholder image to `addOverlay` API if you need to clear-out current image.
///
/// - parameter doNotNilOutOnTVOS10orEarlier: only has effect on tvOS10 or earlier.
/// Useful when you set placeholder image via `addOverlay` to reset current image.
/// This way the behavior is consistent across OS versions.
///
/// - NOTE: DO NOT set nil-out `UIImageView.image`!
/// `overlayContentView` won't work if you do.
/// I believe it's an Apple's bug.
public func clearOverlays(doNotNilOutOnTVOS10orEarlier: Bool = false) {
if #available(tvOS 11.0, *) {
if let childOverlayView = base._childOverlayView {
childOverlayView.removeFromSuperview()
base._childOverlayView = nil
}
// IMPORTANT: Do not nil-out
// base.image = nil
} else {
if !doNotNilOutOnTVOS10orEarlier {
base.image = nil
}
}
}
/// Add overlays to this UIImageView
///
/// - parameter image: non-nil UIImage pass placeholder image when you want to clear the image.
/// - parameter overlays: array of OverlayProtocol objects
/// - parameter imagePackagingQueue: [optional] specify any queue where you want the image rendering taken place.
/// Dare to use this though. Packaging in background sometimes causes layers not correctly rendered.
///
/// - tvOS11
/// On tvOS11, things are little complicated.
/// An overlay can be defined as "image" (`needsRendering = true`), "view", or "layer".
/// Note that there isn't a way to keep correct order between "image" and "view".
/// Images are rendered into single image. We can keep order between views and layers.
///
/// - tvOS10 or earlier
/// On tvOS10, every overlays are rendered as "image", regardless of `needsRendering` definition.
public func addOverlays(with image: UIImage, overlays: [OverlayProtocol], imagePackagingQueue: DispatchQueue? = nil) {
let size = base.bounds.size
if #available(tvOS 11.0, *) {
// Get overlays defined as "image" (needsRendering), not UIView or CALayer.
let layersAsImage = overlays
.filter { $0.needsRendering }
.flatMap { $0.layers }
layersAsImage.forEach { $0.sublayers?.forEach { s in s.applySuperLayersBoundsOriginRecursively() } }
let overlaysAsOverlays = overlays.filter { !$0.needsRendering }
if layersAsImage.isEmpty {
// If all overlays are defined as UIView or CALayer,
// just use `contentOverlayView` in ordinary manner.
base.addOverlays(overlays: overlaysAsOverlays, image: image)
} else {
// - Convert image overlays to images
// - Pass view/layer overlays to base.addOverlays
if let queue = imagePackagingQueue {
queue.async {
guard let packaged = image.packaged(layers: layersAsImage, size: size) else {
return
}
DispatchQueue.main.async {
self.base.addOverlays(overlays: overlaysAsOverlays, image: packaged)
}
}
} else {
guard let packaged = image.packaged(layers: layersAsImage, size: size) else {
return
}
self.base.addOverlays(overlays: overlaysAsOverlays, image: packaged)
}
}
} else {
let layers: [CALayer] = overlays.flatMap { $0.layers }
layers.forEach { $0.sublayers?.forEach { s in s.applySuperLayersBoundsOriginRecursively() } }
// NOTE: packaged(layers:size) don't have to be on main thread,
// but it sometimes causes issues like CATextLayer not rendered.
// So we're not dispatching on background by default.
if let queue = imagePackagingQueue {
queue.async {
guard let packaged = image.packaged(layers: layers, size: size) else {
return
}
DispatchQueue.main.async {
self.base.image = packaged
}
}
} else {
guard let packaged = image.packaged(layers: layers, size: size) else {
return
}
self.base.image = packaged
}
}
}
// Disabling this for now.
// public var overlayContentView: UIView? {
// set {
// objc_setAssociatedObject(self, &AssociatedKeys.overlayContentView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// if base.image == nil, newValue != nil {
// assertionFailure("Set image before setting overlayContentView")
// }
// if let image = base.image, let view = newValue {
// addOverlays(with: image, overlays: [AnyViewAsOverlay(view: view)])
// }
// }
// get {
// return objc_getAssociatedObject(self, &AssociatedKeys.overlayContentView) as? UIView
// }
// }
}
extension UIImageView {
private struct AssociatedKeys {
static var _childOverlayView = "ImageOverlay.UIImageView._childOverlayView"
}
var _childOverlayView: UIView? {
set {
objc_setAssociatedObject(self, &AssociatedKeys._childOverlayView, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
get {
return objc_getAssociatedObject(self, &AssociatedKeys._childOverlayView) as? UIView
}
}
@available(tvOS 11.0, *)
func addOverlays(overlays: [OverlayProtocol], image: UIImage) {
let v = self.overlayContentView
self.image = image
if let existing = _childOverlayView {
// Can happen even when clearOverlays is called on prepareForReuse.
// Because addOverlays can be called asynchronously.
existing.removeFromSuperview()
}
let child = UIView(frame: v.bounds)
for overlay in overlays {
if let viewOverlay = overlay as? OverlayViewProtocol {
if !viewOverlay.needsRendering {
child.addSubview(viewOverlay.view)
}
} else {
if !overlay.needsRendering {
let layers = overlay.layers
layers.forEach {
$0.frame = $0.bounds
$0.sublayers?.forEach { s in s.applySuperLayersBoundsOriginRecursively() }
}
layers.forEach {
child.layer.addSublayer($0)
}
}
}
}
v.addSubview(child)
_childOverlayView = child
}
}
extension UIImage {
func packaged(layers: [CALayer], size _size: CGSize) -> UIImage? {
let scaledSize = _size.scaled(2)
let rect = AVMakeRect(aspectRatio: self.size, insideRect: CGRect(origin: .zero, size: scaledSize))
UIGraphicsBeginImageContextWithOptions(scaledSize, false, UIScreen.main.scale)
if let context = UIGraphicsGetCurrentContext() {
self.draw(in: rect)
for layer in layers {
layer.render(in: context)
}
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| 35.372881 | 127 | 0.574389 |
efcc284cf66ac52bbafa7fe6d7bbdaf6bb998e5e | 251 | //
// main.swift
// Sileo
//
// Created by CoolStar on 8/29/19.
// Copyright © 2019 Sileo Team. All rights reserved.
//
import Foundation
UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(SileoAppDelegate.self))
| 20.916667 | 106 | 0.741036 |
89b38e117ac12cfc096633ce7d5a82d4fbc34553 | 18,086 | //
// TabBarViewController.swift
// loafwallet
//
// Created by Kerry Washington on 11/17/19.
// Copyright © 2019 Litecoin Foundation. All rights reserved.
import UIKit
import Foundation
class TabBarViewController: UIViewController, Subscriber, Trackable, UITabBarDelegate {
let kInitialChildViewControllerIndex = 0 // TransactionsViewController
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var tabBar: UITabBar!
@IBOutlet weak var settingsButton: UIButton!
@IBOutlet weak var walletBalanceLabel: UILabel!
var primaryBalanceLabel: UpdatingLabel?
var secondaryBalanceLabel: UpdatingLabel?
private let largeFontSize: CGFloat = 24.0
private let smallFontSize: CGFloat = 12.0
private var hasInitialized = false
private var didLoginLitecoinCardAccount = false
private let dateFormatter = DateFormatter()
private let equalsLabel = UILabel(font: .barlowMedium(size: 12), color: .whiteTint)
private var regularConstraints: [NSLayoutConstraint] = []
private var swappedConstraints: [NSLayoutConstraint] = []
private let currencyTapView = UIView()
private let storyboardNames:[String] = ["Transactions","Send","Card","Receive","Buy"]
var storyboardIDs:[String] = ["TransactionsViewController","SendLTCViewController","CardViewController","ReceiveLTCViewController","BuyTableViewController"]
var viewControllers:[UIViewController] = []
var activeController:UIViewController? = nil
var updateTimer: Timer?
var store: Store?
var walletManager: WalletManager?
var exchangeRate: Rate? {
didSet { setBalances() }
}
private var balance: UInt64 = 0 {
didSet { setBalances() }
}
var isLtcSwapped: Bool? {
didSet { setBalances() }
}
@IBAction func showSettingsAction(_ sender: Any) {
guard let store = self.store else {
NSLog("ERROR: Store not set")
return
}
store.perform(action: RootModalActions.Present(modal: .menu))
}
override func viewDidLoad() {
super.viewDidLoad()
setupModels()
setupViews()
configurePriceLabels()
addSubscriptions()
dateFormatter.setLocalizedDateFormatFromTemplate("MMM d, h:mm a")
for (index, storyboardID) in self.storyboardIDs.enumerated() {
let controller = UIStoryboard.init(name: storyboardNames[index], bundle: nil).instantiateViewController(withIdentifier: storyboardID)
viewControllers.append(controller)
}
self.updateTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { timer in
self.setBalances()
}
guard let array = self.tabBar.items else {
NSLog("ERROR: no items found")
return
}
self.tabBar.selectedItem = array[kInitialChildViewControllerIndex]
}
deinit {
self.updateTimer = nil
}
private func setupModels() {
guard let store = self.store else { return }
isLtcSwapped = store.state.isLtcSwapped
if let rate = store.state.currentRate {
exchangeRate = rate
let placeholderAmount = Amount(amount: 0, rate: rate, maxDigits: store.state.maxDigits)
secondaryBalanceLabel = UpdatingLabel(formatter: placeholderAmount.localFormat)
primaryBalanceLabel = UpdatingLabel(formatter: placeholderAmount.ltcFormat)
} else {
secondaryBalanceLabel = UpdatingLabel(formatter: NumberFormatter())
primaryBalanceLabel = UpdatingLabel(formatter: NumberFormatter())
}
}
private func setupViews() {
walletBalanceLabel.text = S.ManageWallet.balance + ":"
if #available(iOS 11.0, *),
let backgroundColor = UIColor(named: "mainColor") {
headerView.backgroundColor = backgroundColor
tabBar.barTintColor = backgroundColor
containerView.backgroundColor = backgroundColor
self.view.backgroundColor = backgroundColor
} else {
headerView.backgroundColor = .liteWalletBlue
tabBar.barTintColor = .liteWalletBlue
containerView.backgroundColor = .liteWalletBlue
self.view.backgroundColor = .liteWalletBlue
}
}
private func configurePriceLabels() {
//TODO: Debug the reizing of label...very important
guard let primaryLabel = self.primaryBalanceLabel ,
let secondaryLabel = self.secondaryBalanceLabel else {
NSLog("ERROR: Price labels not initialized")
return
}
let priceLabelArray = [primaryBalanceLabel,secondaryBalanceLabel,equalsLabel]
priceLabelArray.enumerated().forEach { (index, view) in
view?.backgroundColor = .clear
view?.textColor = .white
}
primaryLabel.font = UIFont.barlowSemiBold(size: largeFontSize)
secondaryLabel.font = UIFont.barlowSemiBold(size: largeFontSize)
equalsLabel.text = "="
headerView.addSubview(primaryLabel)
headerView.addSubview(secondaryLabel)
headerView.addSubview(equalsLabel)
headerView.addSubview(currencyTapView)
secondaryLabel.constrain([
secondaryLabel.constraint(.firstBaseline, toView: primaryLabel, constant: 0.0) ])
equalsLabel.translatesAutoresizingMaskIntoConstraints = false
primaryLabel.translatesAutoresizingMaskIntoConstraints = false
regularConstraints = [
primaryLabel.firstBaselineAnchor.constraint(equalTo: headerView.bottomAnchor, constant: -12),
primaryLabel.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: C.padding[1]*1.25),
equalsLabel.firstBaselineAnchor.constraint(equalTo: primaryLabel.firstBaselineAnchor, constant: 0),
equalsLabel.leadingAnchor.constraint(equalTo: primaryLabel.trailingAnchor, constant: C.padding[1]/2.0),
secondaryLabel.leadingAnchor.constraint(equalTo: equalsLabel.trailingAnchor, constant: C.padding[1]/2.0),
]
swappedConstraints = [
secondaryLabel.firstBaselineAnchor.constraint(equalTo: headerView.bottomAnchor, constant: -12),
secondaryLabel.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: C.padding[1]*1.25),
equalsLabel.firstBaselineAnchor.constraint(equalTo: secondaryLabel.firstBaselineAnchor, constant: 0),
equalsLabel.leadingAnchor.constraint(equalTo: secondaryLabel.trailingAnchor, constant: C.padding[1]/2.0),
primaryLabel.leadingAnchor.constraint(equalTo: equalsLabel.trailingAnchor, constant: C.padding[1]/2.0),
]
if let isLTCSwapped = self.isLtcSwapped {
NSLayoutConstraint.activate(isLTCSwapped ? self.swappedConstraints : self.regularConstraints)
}
currencyTapView.constrain([
currencyTapView.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: 0),
currencyTapView.trailingAnchor.constraint(equalTo: self.settingsButton.leadingAnchor, constant: -C.padding[5]),
currencyTapView.topAnchor.constraint(equalTo: primaryLabel.topAnchor, constant: 0),
currencyTapView.bottomAnchor.constraint(equalTo: primaryLabel.bottomAnchor, constant: C.padding[1]) ])
let gr = UITapGestureRecognizer(target: self, action: #selector(currencySwitchTapped))
currencyTapView.addGestureRecognizer(gr)
}
//MARK: - Adding Subscriptions
private func addSubscriptions() {
guard let store = self.store else {
NSLog("ERROR - Store not passed")
return
}
guard let primaryLabel = self.primaryBalanceLabel ,
let secondaryLabel = self.secondaryBalanceLabel else {
NSLog("ERROR: Price labels not initialized")
return
}
store.subscribe(self, selector: { $0.walletState.syncProgress != $1.walletState.syncProgress },
callback: { _ in
self.tabBar.selectedItem = self.tabBar.items?.first
})
store.lazySubscribe(self,
selector: { $0.isLtcSwapped != $1.isLtcSwapped },
callback: { self.isLtcSwapped = $0.isLtcSwapped })
store.lazySubscribe(self,
selector: { $0.currentRate != $1.currentRate},
callback: {
if let rate = $0.currentRate {
let placeholderAmount = Amount(amount: 0, rate: rate, maxDigits: $0.maxDigits)
secondaryLabel.formatter = placeholderAmount.localFormat
primaryLabel.formatter = placeholderAmount.ltcFormat
}
self.exchangeRate = $0.currentRate
})
store.lazySubscribe(self,
selector: { $0.maxDigits != $1.maxDigits},
callback: {
if let rate = $0.currentRate {
let placeholderAmount = Amount(amount: 0, rate: rate, maxDigits: $0.maxDigits)
secondaryLabel.formatter = placeholderAmount.localFormat
primaryLabel.formatter = placeholderAmount.ltcFormat
self.setBalances()
}
})
store.subscribe(self,
selector: {$0.walletState.balance != $1.walletState.balance },
callback: { state in
if let balance = state.walletState.balance {
self.balance = balance
self.setBalances()
} })
}
/// This is called when the price changes
private func setBalances() {
guard let rate = exchangeRate, let store = self.store, let isLTCSwapped = self.isLtcSwapped else {
NSLog("ERROR: Rate, Store not initialized")
return
}
guard let primaryLabel = self.primaryBalanceLabel,
let secondaryLabel = self.secondaryBalanceLabel else {
NSLog("ERROR: Price labels not initialized")
return
}
let amount = Amount(amount: balance, rate: rate, maxDigits: store.state.maxDigits)
if !hasInitialized {
let amount = Amount(amount: balance, rate: exchangeRate!, maxDigits: store.state.maxDigits)
NSLayoutConstraint.deactivate(isLTCSwapped ? self.regularConstraints : self.swappedConstraints)
NSLayoutConstraint.activate(isLTCSwapped ? self.swappedConstraints : self.regularConstraints)
primaryLabel.setValue(amount.amountForLtcFormat)
secondaryLabel.setValue(amount.localAmount)
if isLTCSwapped {
primaryLabel.transform = transform(forView: primaryLabel)
} else {
secondaryLabel.transform = transform(forView: secondaryLabel)
}
hasInitialized = true
} else {
if primaryLabel.isHidden {
primaryLabel.isHidden = false
}
if secondaryLabel.isHidden {
secondaryLabel.isHidden = false
}
}
primaryLabel.setValue(amount.amountForLtcFormat)
secondaryLabel.setValue(amount.localAmount)
if !isLTCSwapped {
primaryLabel.transform = .identity
secondaryLabel.transform = transform(forView: secondaryLabel)
} else {
secondaryLabel.transform = .identity
primaryLabel.transform = transform(forView: primaryLabel)
}
}
/// Transform LTC and Fiat Balances
/// - Parameter forView: Views
/// - Returns: the inverse transform
private func transform(forView: UIView) -> CGAffineTransform {
forView.transform = .identity
let scaleFactor: CGFloat = smallFontSize/largeFontSize
let deltaX = forView.frame.width * (1-scaleFactor)
let deltaY = forView.frame.height * (1-scaleFactor)
let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
return scale.translatedBy(x: -deltaX, y: deltaY/2.0)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let array = self.tabBar.items else {
NSLog("ERROR: no items found")
return
}
array.forEach { item in
switch item.tag {
case 0: item.title = S.History.barItemTitle
case 1: item.title = S.Send.barItemTitle
case 2: item.title = S.LitecoinCard.barItemTitle
case 3: item.title = S.Receive.barItemTitle
case 4: item.title = S.BuyCenter.barItemTitle
default:
item.title = "NO-TITLE"
NSLog("ERROR: UITabbar item count is wrong")
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.displayContentController(contentController: viewControllers[kInitialChildViewControllerIndex])
}
func displayContentController(contentController:UIViewController) {
//MARK: - Tab View Controllers Configuration
switch NSStringFromClass(contentController.classForCoder) {
case "loafwallet.TransactionsViewController":
guard let transactionVC = contentController as? TransactionsViewController else {
return
}
transactionVC.store = self.store
transactionVC.walletManager = self.walletManager
transactionVC.isLtcSwapped = self.store?.state.isLtcSwapped
case "loafwallet.CardViewController":
guard let cardVC = contentController as? CardViewController else {
return
}
cardVC.parentFrame = self.containerView.frame
cardVC.store = self.store
cardVC.walletManager = self.walletManager
case "loafwallet.BuyTableViewController":
guard let buyVC = contentController as? BuyTableViewController else {
return
}
buyVC.store = self.store
buyVC.walletManager = self.walletManager
case "loafwallet.SendLTCViewController":
guard let sendVC = contentController as? SendLTCViewController else {
return
}
sendVC.store = self.store
case "loafwallet.ReceiveLTCViewController":
guard let receiveVC = contentController as? ReceiveLTCViewController else {
return
}
receiveVC.store = self.store
default:
fatalError("Tab viewController not set")
}
self.exchangeRate = TransactionManager.sharedInstance.rate
self.addChildViewController(contentController)
contentController.view.frame = self.containerView.frame
self.view.addSubview(contentController.view)
contentController.didMove(toParentViewController: self)
self.activeController = contentController
}
func hideContentController(contentController:UIViewController) {
contentController.willMove(toParentViewController: nil)
contentController.view .removeFromSuperview()
contentController.removeFromParentViewController()
}
func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if let tempActiveController = activeController {
self.hideContentController(contentController: tempActiveController)
}
//DEV: This happens because it relies on the tab in the storyboard tag
self.displayContentController(contentController: viewControllers[item.tag])
}
}
extension TabBarViewController {
@objc private func currencySwitchTapped() {
self.view.layoutIfNeeded()
guard let store = self.store else { return }
guard let isLTCSwapped = self.isLtcSwapped else { return }
guard let primaryLabel = self.primaryBalanceLabel,
let secondaryLabel = self.secondaryBalanceLabel else {
NSLog("ERROR: Price labels not initialized")
return
}
UIView.spring(0.7, animations: {
primaryLabel.transform = primaryLabel.transform.isIdentity ? self.transform(forView: primaryLabel) : .identity
secondaryLabel.transform = secondaryLabel.transform.isIdentity ? self.transform(forView: secondaryLabel) : .identity
NSLayoutConstraint.deactivate(!isLTCSwapped ? self.regularConstraints : self.swappedConstraints)
NSLayoutConstraint.activate(!isLTCSwapped ? self.swappedConstraints : self.regularConstraints)
self.view.layoutIfNeeded()
LWAnalytics.logEventWithParameters(itemName: ._20200207_DTHB)
}) { _ in }
store.perform(action: CurrencyChange.toggle())
}
}
| 42.95962 | 160 | 0.607597 |
4aa52b0c32ef42767c307aa8ea9fc6824474a38c | 5,340 | //
// Rewrites.swift
// ResponsivePublishPlugin
//
// Created by Cordt Zermin on 20.03.21.
//
import Foundation
import Publish
import SwiftGD
fileprivate func fileSpecificRewrites(for rewrites: [ImageRewrite], and urls: [ImageRewrite.ImageUrl]) -> [ImageRewrite] {
return rewrites.reduce([ImageRewrite]()) { current, rewrite in
var withoutPrefix = rewrite
withoutPrefix.source.path = Path(String(withoutPrefix.source.path.string.dropFirst("Resources/".count)))
var counter: Int = 1
let additionalRewrites: [ImageRewrite] = urls.compactMap { imageUrl in
if let pathPrefix = imageUrl.contains(other: withoutPrefix.source) {
var updatedRewrite = withoutPrefix
// Original file path as found in the stylesheet file
updatedRewrite.source.path = Path("\(pathPrefix.string)\(updatedRewrite.source.path.string)")
// Target file path with original relative path + path to reduced asset
updatedRewrite.target.path = Path("\(pathPrefix.string)\(updatedRewrite.target.path.string)")
updatedRewrite.variableNameSuffix = "path-\(counter)"
counter += 1
return updatedRewrite
}
else {
return nil
}
}
return current + additionalRewrites
}
}
func rewrite(stylesheet: String, with rewrites: [ImageRewrite]) -> String {
let urls = imageUrlsFrom(stylesheet: stylesheet)
let specificRewrites = fileSpecificRewrites(for: rewrites, and: urls)
guard !specificRewrites.isEmpty else {
return stylesheet
}
// Create css-variable declarations for the different size classes
var declaration: String = ""
var indentation: String = ""
func declarations(from rewrites: [ImageRewrite], for sizeClass: SizeClass, with indentation: String) -> String {
rewrites
.filter { $0.targetSizeClass == sizeClass }
.sorted(by: { $0.variableName < $1.variableName })
.reduce("") { current, rewrite in
current +
"\(indentation)\(rewrite.variableName): url('\(rewrite.target.filePath)');\n"
}
}
SizeClass.allCases.forEach { sizeClass in
switch sizeClass {
case .extraSmall:
declaration += ":root {\n"
indentation = "\t"
case .small:
declaration += "@media screen and (min-width: \(sizeClass.minWidth)px) {\n\t:root {\n"
indentation = "\t\t"
case .normal:
declaration += "@media screen and (min-width: \(sizeClass.minWidth)px) {\n\t:root {\n"
indentation = "\t\t"
case .large:
declaration += "@media screen and (min-width: \(sizeClass.minWidth)px) {\n\t:root {\n"
indentation = "\t\t"
}
declaration += declarations(
from: specificRewrites,
for: sizeClass,
with: indentation
)
switch sizeClass {
case .extraSmall: declaration += "}\n\n"
case .small: declaration += "\t}\n}\n\n"
case .normal: declaration += "\t}\n}\n\n"
case .large: declaration += "\t}\n}\n\n"
}
}
var updated: String = stylesheet
// Replace the actual image url with the variable
specificRewrites.forEach { rewrite in
updated = updated.replacingOccurrences(of: "url('\(rewrite.source.filePath)')", with: "var(\(rewrite.variableName))")
updated = updated.replacingOccurrences(of: "url(\"\(rewrite.source.filePath)\")", with: "var(\(rewrite.variableName))")
updated = updated.replacingOccurrences(of: "url(\(rewrite.source.filePath))", with: "var(\(rewrite.variableName))")
}
// Prepend the variable declarations
return declaration + updated
}
func rewrite(html: String, with rewrites: [ImageRewrite]) -> String {
let urls = imageUrlsFrom(html: html)
let specificRewrites = fileSpecificRewrites(for: rewrites, and: urls)
let groupedRewrites = Dictionary(grouping: specificRewrites) { $0.source.filePath }
struct ImageTagAttribute {
/// The original source of the image is used to replace the src tag in the images in the html
let originalSource: String
let sourceSet: String
}
// Create image tag attributes for the different size classes
func replacements(from rewrites: [String: [ImageRewrite]]) -> [ImageTagAttribute] {
groupedRewrites.map { source, rewrites in
let srcset = rewrites.reduce("") {
$0 + "\($1.target.filePath) \($1.targetSizeClass.upperBound)w, "
}
.dropLast(2)
return ImageTagAttribute(
originalSource: source,
sourceSet: "srcset=\"\(srcset)\""
)
}
}
var updated: String = html
// Replace the src-attribute of the images with the srcset
replacements(from: groupedRewrites).forEach { srcset in
updated = updated.replacingOccurrences(
of: "src=\"\(srcset.originalSource)\"",
with: srcset.sourceSet + " src=\"\(srcset.originalSource)\""
)
}
return updated
}
| 37.605634 | 127 | 0.598876 |
c137972e9a77353603cd93cd82b486788a90eb68 | 38 | import keras
print(keras.__version__)
| 12.666667 | 24 | 0.842105 |
16e6a4b2b6518f425df56fba4845c5a007b2bd59 | 5,753 | //
// ResponseFutureTests.swift
// NetworkKitTests
//
// Created by Jacob Sikorski on 2019-04-13.
// Copyright © 2019 Jacob Sikorski. All rights reserved.
//
import XCTest
@testable import NetworkKit
@testable import Example
class ResponseFutureTests: XCTestCase {
typealias EnrichedPost = (post: Post, markdown: NSAttributedString?)
func testFutureResponse() {
// Given
let post = Post(id: 123, userId: 123, title: "Some post", body: "Lorem ipsum ...")
let url = URL(string: "https://jsonplaceholder.typicode.com")!
let dispatcher = MockDispatcher(baseUrl: url, mockStatusCode: .ok)
let request = BasicRequest(method: .get, path: "/posts/1")
do {
try dispatcher.setMockData(post)
} catch {
XCTFail("Should not fail serialization")
}
// When
var calledCompletion = false
let successExpectation = self.expectation(description: "Success response triggered")
let completionExpectation = self.expectation(description: "Completion triggered")
// Then
dispatcher.future(from: request).then({ response -> Post in
// Handles any responses and transforms them to another type
// This includes negative responses such as 4xx and 5xx
// The error object is available if we get an
// undesirable status code such as a 4xx or 5xx
if let error = response.error {
// Throwing an error in any callback will trigger the `error` callback.
// This allows us to pool all our errors in one place.
throw error
}
XCTAssertFalse(calledCompletion)
return try response.decode(Post.self)
}).replace({ post -> ResponseFuture<EnrichedPost> in
// Perform some operation operation that itself requires a future
// such as something heavy like markdown parsing.
XCTAssertFalse(calledCompletion)
return self.enrich(post: post)
}).join({ enrichedPost -> ResponseFuture<User> in
// Joins a future with another one
XCTAssertFalse(calledCompletion)
return self.fetchUser(forId: post.userId)
}).response({ enrichedPost, user in
// The final response callback includes all the transformations and
// Joins we had previously performed.
XCTAssertFalse(calledCompletion)
successExpectation.fulfill()
}).error({ error in
XCTFail("Should not trigger the failure")
}).completion({
calledCompletion = true
completionExpectation.fulfill()
}).send()
waitForExpectations(timeout: 5, handler: nil)
}
private func enrich(post: Post) -> ResponseFuture<EnrichedPost> {
return ResponseFuture<EnrichedPost>() { future in
future.succeed(with: (post, nil))
}
}
private func fetchUser(forId id: Int) -> ResponseFuture<User> {
let request = BasicRequest(method: .get, path: "/users/\(id)")
let user = User(id: id, name: "Jim Halpert")
let dispatcher = try! MockDispatcher.makeDispatcher(with: user, status: .ok)
do {
try dispatcher.setMockData(user)
} catch {
XCTFail("Should not fail serialization")
}
return dispatcher.future(from: request).then({ response -> User in
return try response.decode(User.self)
})
}
func testFuture() {
let expectation = self.expectation(description: "Success response triggered")
let request = BasicRequest(method: .get, path: "/posts")
let post = Post(id: 123, userId: 123, title: "Some post", body: "Lorem ipsum ...")
let dispatcher = try! MockDispatcher.makeDispatcher(with: [post], status: .ok)
do {
try dispatcher.setMockData([post])
} catch {
XCTFail("Should not fail serialization")
}
let response = try! dispatcher.response(from: request)
makeFuture(from: response).response({ posts in
expectation.fulfill()
}).send()
waitForExpectations(timeout: 5, handler: nil)
}
private func makeFuture(from response: Response<Data?>) -> ResponseFuture<[Post]> {
// Promises can wrap callbacks so they are executed when start()
// is triggered.
return ResponseFuture<[Post]>(action: { future in
// This is an example of how a future is executed and
// fulfilled.
// You should always syncronize
DispatchQueue.global(qos: .userInitiated).async {
// lets make an expensive operation on a background thread.
// The below is just an example of how you can parse on a seperate thread.
do {
// Do an expensive operation here ....
let posts = try response.decode([Post].self)
DispatchQueue.main.async {
// We should syncronyze the result back to the main thread.
future.succeed(with: posts)
}
} catch {
// We can handle any errors as well.
DispatchQueue.main.async {
// We should syncronize the error to the main thread.
future.fail(with: error)
}
}
}
})
}
}
| 38.099338 | 92 | 0.567009 |
f5e10bbd18bc3f0cebc0e74ff55d461b5333acde | 236 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func i(v: A.a
class A {
func a
protocol a {
func a
typealias e : a
| 21.454545 | 87 | 0.741525 |
8a5e7b8b277140c234d1f50a179e09edecafb128 | 5,061 | //
// Provider.swift
// Strafen
//
// Created by Steven on 24.07.20.
//
import WidgetKit
import SwiftUI
/// Timeline Provider of Strafen Widget
struct Provider: TimelineProvider {
/// Time interval between two timeline requests
///
/// 3600sec = 1h
let timeIntervalToUpdate: TimeInterval = 3600
/// Time interval between two timeline requests if no connection
///
/// 300sec = 5min
let timeIntervalToUpdateNoconnection: TimeInterval = 300
/// Creates a snapshot of the widget
func snapshot(with context: Context, completion: @escaping (WidgetEntry) -> ()) {
completion(WidgetEntry(date: Date(), widgetEntryType: .success(person: .default, fineList: .random), style: .plain))
}
/// Creates a timeline of the widget
func timeline(with context: Context, completion: @escaping (Timeline<WidgetEntry>) -> ()) {
// Check if person is logged in
WidgetUrls.shared.reloadSettings()
if let person = WidgetUrls.shared.person, let style = WidgetUrls.shared.style {
// Enter dispatch group to fetch person- / reason- and finelist
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
dispatchGroup.enter()
// Get lists
var reasonList: [WidgetReason]?
var fineList: [WidgetFine]?
// Fetch reason list
WidgetListFetcher.shared.fetch(of: person.clubId) { (fetchedList: [WidgetReason]?) in
reasonList = fetchedList
dispatchGroup.leave()
}
// Fetch fine list
WidgetListFetcher.shared.fetch(of: person.clubId) { (fetchedList: [WidgetFine]?) in
// Filter list only for person
fineList = fetchedList?.filter { $0.personId == person.id }
dispatchGroup.leave()
}
// Check if all lists aren't nil
dispatchGroup.notify(queue: .main) {
if let reasonList = reasonList, let fineList = fineList {
// Map fine list to get data from template
let fineNoTemplateList = fineList.map { fine -> WidgetFineNoTemplate in
let fineReason = fine.fineReason.fineReasonCustom(reasonList: reasonList)
let fineNoTemplate = WidgetFineNoTemplate(date: fine.date, payed: fine.payed, number: fine.number, id: fine.id, fineReason: fineReason)
return fineNoTemplate
}
// Get timeline
let dateForNextTimelineRequest = Date(timeIntervalSinceNow: timeIntervalToUpdate)
let widgetEntryType: WidgetEntryType = .success(person: person, fineList: fineNoTemplateList)
let entry = WidgetEntry(date: dateForNextTimelineRequest, widgetEntryType: widgetEntryType, style: style)
let timeline = Timeline(entries: [entry], policy: .atEnd)
completion(timeline)
} else {
// No internet connection
let dateForNextTimelineRequest = Date(timeIntervalSinceNow: timeIntervalToUpdateNoconnection)
let widgetEntryType: WidgetEntryType = .noConnection
let entry = WidgetEntry(date: dateForNextTimelineRequest, widgetEntryType: widgetEntryType, style: style)
let timeline = Timeline(entries: [entry], policy: .atEnd)
completion(timeline)
}
}
} else {
// No person is logged in
let dateForNextTimelineRequest = Date(timeIntervalSinceNow: timeIntervalToUpdateNoconnection)
let widgetEntryType: WidgetEntryType = .noPersonLoggedIn
let entry = WidgetEntry(date: dateForNextTimelineRequest, widgetEntryType: widgetEntryType, style: .default)
let timeline = Timeline(entries: [entry], policy: .atEnd)
completion(timeline)
}
}
/// Creates a placeholder of the widget
func placeholder(with: Context) -> WidgetEntry {
WidgetEntry(date: Date(), widgetEntryType: .success(person: .default, fineList: .random), style: .plain)
}
}
/// Entry of timeline of Strafen Widget
struct WidgetEntry: TimelineEntry {
/// Date of next timeline request
let date: Date
/// Widget entry type
let widgetEntryType: WidgetEntryType
/// Widget style
let style: WidgetUrls.CodableSettings.Style
}
/// Type of Widget entry
enum WidgetEntryType {
/// Widget entry type with success
case success(person: WidgetUrls.CodableSettings.Person, fineList: [WidgetFineNoTemplate])
/// Widget entry type with no connection
case noConnection
/// Widget entry type with no person logged in
case noPersonLoggedIn
}
| 39.539063 | 159 | 0.599881 |
f728c6e7b47ce6deaebb3d898a73e9f0227732b3 | 863 | import SwiftUI
struct OneTap: View {
@State var tapCount = 0.0
var rotationEffect: Angle {
return Angle(degrees: 360 * tapCount)
}
var body: some View {
let tapGesture = TapGesture(count: 1)
.onEnded {
withAnimation {
self.tapCount += 1
}
}
return ImageView4()
.rotationEffect(rotationEffect)
.gesture(tapGesture)
}
}
struct OneTap_Previews: PreviewProvider {
static var previews: some View {
OneTap()
}
}
struct ImageView4: View {
var body: some View {
HStack {
Image(systemName: "arrow.down.square.fill")
.resizable()
.foregroundColor(Color.purple)
}
.padding()
.frame(width: 300, height: 300)
}
}
| 20.547619 | 55 | 0.512167 |
28b9a924b84cfc7d27ab7cf7968368f9469d1d6c | 20,081 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
SceneKit node giving the user hints about the status of ARKit world tracking.
*/
import Foundation
import ARKit
/**
An `SCNNode` which is used to provide uses with visual cues about the status of ARKit world tracking.
- Tag: FocusSquare
*/
class FocusSquare: SCNNode {
// MARK: - Types
enum State: Equatable {
case initializing
case detecting(hitTestResult: ARHitTestResult, camera: ARCamera?)
}
// MARK: - Configuration Properties
// Original size of the focus square in meters.
static let size: Float = 0.17
// Thickness of the focus square lines in meters.
static let thickness: Float = 0.018
// Scale factor for the focus square when it is closed, w.r.t. the original size.
static let scaleForClosedSquare: Float = 0.97
// Side length of the focus square segments when it is open (w.r.t. to a 1x1 square).
static let sideLengthForOpenSegments: CGFloat = 0.2
// Duration of the open/close animation
static let animationDuration = 0.7
static let primaryColor = #colorLiteral(red: 1, green: 0.8, blue: 0, alpha: 1)
// Color of the focus square fill.
static let fillColor = #colorLiteral(red: 1, green: 0.9254901961, blue: 0.4117647059, alpha: 1)
// MARK: - Properties
/// The most recent position of the focus square based on the current state.
var lastPosition: float3? {
switch state {
case .initializing: return nil
case .detecting(let hitTestResult, _): return hitTestResult.worldTransform.translation
}
}
var state: State = .initializing {
didSet {
guard state != oldValue else { return }
switch state {
case .initializing:
displayAsBillboard()
case let .detecting(hitTestResult, camera):
if let planeAnchor = hitTestResult.anchor as? ARPlaneAnchor {
displayAsClosed(for: hitTestResult, planeAnchor: planeAnchor, camera: camera)
currentPlaneAnchor = planeAnchor
} else {
displayAsOpen(for: hitTestResult, camera: camera)
currentPlaneAnchor = nil
}
}
}
}
/// Indicates whether the segments of the focus square are disconnected.
private var isOpen = false
/// Indicates if the square is currently being animated.
private var isAnimating = false
/// Indicates if the square is currently changing its alignment.
private var isChangingAlignment = false
/// The focus square's current alignment.
private var currentAlignment: ARPlaneAnchor.Alignment?
/// The current plane anchor if the focus square is on a plane.
private(set) var currentPlaneAnchor: ARPlaneAnchor?
/// The focus square's most recent positions.
private var recentFocusSquarePositions: [float3] = []
/// The focus square's most recent alignments.
private(set) var recentFocusSquareAlignments: [ARPlaneAnchor.Alignment] = []
/// Previously visited plane anchors.
private var anchorsOfVisitedPlanes: Set<ARAnchor> = []
/// List of the segments in the focus square.
private var segments: [FocusSquare.Segment] = []
/// The primary node that controls the position of other `FocusSquare` nodes.
private let positioningNode = SCNNode()
// MARK: - Initialization
override init() {
super.init()
opacity = 0.0
/*
The focus square consists of eight segments as follows, which can be individually animated.
s1 s2
_ _
s3 | | s4
s5 | | s6
- -
s7 s8
*/
let s1 = Segment(name: "s1", corner: .topLeft, alignment: .horizontal)
let s2 = Segment(name: "s2", corner: .topRight, alignment: .horizontal)
let s3 = Segment(name: "s3", corner: .topLeft, alignment: .vertical)
let s4 = Segment(name: "s4", corner: .topRight, alignment: .vertical)
let s5 = Segment(name: "s5", corner: .bottomLeft, alignment: .vertical)
let s6 = Segment(name: "s6", corner: .bottomRight, alignment: .vertical)
let s7 = Segment(name: "s7", corner: .bottomLeft, alignment: .horizontal)
let s8 = Segment(name: "s8", corner: .bottomRight, alignment: .horizontal)
segments = [s1, s2, s3, s4, s5, s6, s7, s8]
let sl: Float = 0.5 // segment length
let c: Float = FocusSquare.thickness / 2 // correction to align lines perfectly
s1.simdPosition += float3(-(sl / 2 - c), -(sl - c), 0)
s2.simdPosition += float3(sl / 2 - c, -(sl - c), 0)
s3.simdPosition += float3(-sl, -sl / 2, 0)
s4.simdPosition += float3(sl, -sl / 2, 0)
s5.simdPosition += float3(-sl, sl / 2, 0)
s6.simdPosition += float3(sl, sl / 2, 0)
s7.simdPosition += float3(-(sl / 2 - c), sl - c, 0)
s8.simdPosition += float3(sl / 2 - c, sl - c, 0)
positioningNode.eulerAngles.x = .pi / 2 // Horizontal
positioningNode.simdScale = float3(FocusSquare.size * FocusSquare.scaleForClosedSquare)
for segment in segments {
positioningNode.addChildNode(segment)
}
positioningNode.addChildNode(fillPlane)
// Always render focus square on top of other content.
displayNodeHierarchyOnTop(true)
addChildNode(positioningNode)
// Start the focus square as a billboard.
displayAsBillboard()
}
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
// MARK: - Appearance
/// Hides the focus square.
func hide() {
guard action(forKey: "hide") == nil else { return }
displayNodeHierarchyOnTop(false)
runAction(.fadeOut(duration: 0.5), forKey: "hide")
}
/// Unhides the focus square.
func unhide() {
guard action(forKey: "unhide") == nil else { return }
displayNodeHierarchyOnTop(true)
runAction(.fadeIn(duration: 0.5), forKey: "unhide")
}
/// Displays the focus square parallel to the camera plane.
private func displayAsBillboard() {
simdTransform = matrix_identity_float4x4
eulerAngles.x = .pi / 2
simdPosition = float3(0, 0, -0.8)
unhide()
performOpenAnimation()
}
/// Called when a surface has been detected.
private func displayAsOpen(for hitTestResult: ARHitTestResult, camera: ARCamera?) {
performOpenAnimation()
let position = hitTestResult.worldTransform.translation
recentFocusSquarePositions.append(position)
updateTransform(for: position, hitTestResult: hitTestResult, camera: camera)
}
/// Called when a plane has been detected.
private func displayAsClosed(for hitTestResult: ARHitTestResult, planeAnchor: ARPlaneAnchor, camera: ARCamera?) {
performCloseAnimation(flash: !anchorsOfVisitedPlanes.contains(planeAnchor))
anchorsOfVisitedPlanes.insert(planeAnchor)
let position = hitTestResult.worldTransform.translation
recentFocusSquarePositions.append(position)
updateTransform(for: position, hitTestResult: hitTestResult, camera: camera)
}
// MARK: Helper Methods
/// Update the transform of the focus square to be aligned with the camera.
private func updateTransform(for position: float3, hitTestResult: ARHitTestResult, camera: ARCamera?) {
// Average using several most recent positions.
recentFocusSquarePositions = Array(recentFocusSquarePositions.suffix(10))
// Move to average of recent positions to avoid jitter.
let average = recentFocusSquarePositions.reduce(float3(0), { $0 + $1 }) / Float(recentFocusSquarePositions.count)
self.simdPosition = average
self.simdScale = float3(scaleBasedOnDistance(camera: camera))
// Correct y rotation of camera square.
guard let camera = camera else { return }
let tilt = abs(camera.eulerAngles.x)
let threshold1: Float = .pi / 2 * 0.65
let threshold2: Float = .pi / 2 * 0.75
let yaw = atan2f(camera.transform.columns.0.x, camera.transform.columns.1.x)
var angle: Float = 0
switch tilt {
case 0..<threshold1:
angle = camera.eulerAngles.y
case threshold1..<threshold2:
let relativeInRange = abs((tilt - threshold1) / (threshold2 - threshold1))
let normalizedY = normalize(camera.eulerAngles.y, forMinimalRotationTo: yaw)
angle = normalizedY * (1 - relativeInRange) + yaw * relativeInRange
default:
angle = yaw
}
if state != .initializing {
updateAlignment(for: hitTestResult, yRotationAngle: angle)
}
}
private func updateAlignment(for hitTestResult: ARHitTestResult, yRotationAngle angle: Float) {
// Abort if an animation is currently in progress.
if isChangingAlignment {
return
}
var shouldAnimateAlignmentChange = false
let tempNode = SCNNode()
tempNode.simdRotation = float4(0, 1, 0, angle)
// Determine current alignment
var alignment: ARPlaneAnchor.Alignment?
if let planeAnchor = hitTestResult.anchor as? ARPlaneAnchor {
alignment = planeAnchor.alignment
} else if hitTestResult.type == .estimatedHorizontalPlane {
alignment = .horizontal
} else if hitTestResult.type == .estimatedVerticalPlane {
alignment = .vertical
}
// add to list of recent alignments
if alignment != nil {
recentFocusSquareAlignments.append(alignment!)
}
// Average using several most recent alignments.
recentFocusSquareAlignments = Array(recentFocusSquareAlignments.suffix(20))
let horizontalHistory = recentFocusSquareAlignments.filter({ $0 == .horizontal }).count
let verticalHistory = recentFocusSquareAlignments.filter({ $0 == .vertical }).count
// Alignment is same as most of the history - change it
if alignment == .horizontal && horizontalHistory > 15 ||
alignment == .vertical && verticalHistory > 10 ||
hitTestResult.anchor is ARPlaneAnchor {
if alignment != currentAlignment {
shouldAnimateAlignmentChange = true
currentAlignment = alignment
recentFocusSquareAlignments.removeAll()
}
} else {
// Alignment is different than most of the history - ignore it
alignment = currentAlignment
return
}
if alignment == .vertical {
tempNode.simdOrientation = hitTestResult.worldTransform.orientation
shouldAnimateAlignmentChange = true
}
// Change the focus square's alignment
if shouldAnimateAlignmentChange {
performAlignmentAnimation(to: tempNode.simdOrientation)
} else {
simdOrientation = tempNode.simdOrientation
}
}
private func normalize(_ angle: Float, forMinimalRotationTo ref: Float) -> Float {
// Normalize angle in steps of 90 degrees such that the rotation to the other angle is minimal
var normalized = angle
while abs(normalized - ref) > .pi / 4 {
if angle > ref {
normalized -= .pi / 2
} else {
normalized += .pi / 2
}
}
return normalized
}
/**
Reduce visual size change with distance by scaling up when close and down when far away.
These adjustments result in a scale of 1.0x for a distance of 0.7 m or less
(estimated distance when looking at a table), and a scale of 1.2x
for a distance 1.5 m distance (estimated distance when looking at the floor).
*/
private func scaleBasedOnDistance(camera: ARCamera?) -> Float {
guard let camera = camera else { return 1.0 }
let distanceFromCamera = simd_length(simdWorldPosition - camera.transform.translation)
if distanceFromCamera < 0.7 {
return distanceFromCamera / 0.7
} else {
return 0.25 * distanceFromCamera + 0.825
}
}
// MARK: Animations
private func performOpenAnimation() {
guard !isOpen, !isAnimating else { return }
isOpen = true
isAnimating = true
// Open animation
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
positioningNode.opacity = 1.0
for segment in segments {
segment.open()
}
SCNTransaction.completionBlock = {
self.positioningNode.runAction(pulseAction(), forKey: "pulse")
// This is a safe operation because `SCNTransaction`'s completion block is called back on the main thread.
self.isAnimating = false
}
SCNTransaction.commit()
// Add a scale/bounce animation.
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
positioningNode.simdScale = float3(FocusSquare.size)
SCNTransaction.commit()
}
private func performCloseAnimation(flash: Bool = false) {
guard isOpen, !isAnimating else { return }
isOpen = false
isAnimating = true
positioningNode.removeAction(forKey: "pulse")
positioningNode.opacity = 1.0
// Close animation
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 2
positioningNode.opacity = 0.99
SCNTransaction.completionBlock = {
SCNTransaction.begin()
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
SCNTransaction.animationDuration = FocusSquare.animationDuration / 4
for segment in self.segments {
segment.close()
}
SCNTransaction.completionBlock = { self.isAnimating = false }
SCNTransaction.commit()
}
SCNTransaction.commit()
// Scale/bounce animation
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.x"), forKey: "transform.scale.x")
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.y"), forKey: "transform.scale.y")
positioningNode.addAnimation(scaleAnimation(for: "transform.scale.z"), forKey: "transform.scale.z")
if flash {
let waitAction = SCNAction.wait(duration: FocusSquare.animationDuration * 0.75)
let fadeInAction = SCNAction.fadeOpacity(to: 0.25, duration: FocusSquare.animationDuration * 0.125)
let fadeOutAction = SCNAction.fadeOpacity(to: 0.0, duration: FocusSquare.animationDuration * 0.125)
fillPlane.runAction(SCNAction.sequence([waitAction, fadeInAction, fadeOutAction]))
let flashSquareAction = flashAnimation(duration: FocusSquare.animationDuration * 0.25)
for segment in segments {
segment.runAction(.sequence([waitAction, flashSquareAction]))
}
}
}
private func performAlignmentAnimation(to newOrientation: simd_quatf) {
isChangingAlignment = true
SCNTransaction.begin()
SCNTransaction.completionBlock = {
self.isChangingAlignment = false
}
SCNTransaction.animationDuration = 0.5
SCNTransaction.animationTimingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
simdOrientation = newOrientation
SCNTransaction.commit()
}
// MARK: Convenience Methods
private func scaleAnimation(for keyPath: String) -> CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: keyPath)
let easeOut = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
let easeInOut = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
let linear = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
let size = FocusSquare.size
let ts = FocusSquare.size * FocusSquare.scaleForClosedSquare
let values = [size, size * 1.15, size * 1.15, ts * 0.97, ts]
let keyTimes: [NSNumber] = [0.00, 0.25, 0.50, 0.75, 1.00]
let timingFunctions = [easeOut, linear, easeOut, easeInOut]
scaleAnimation.values = values
scaleAnimation.keyTimes = keyTimes
scaleAnimation.timingFunctions = timingFunctions
scaleAnimation.duration = FocusSquare.animationDuration
return scaleAnimation
}
/// Sets the rendering order of the `positioningNode` to show on top or under other scene content.
func displayNodeHierarchyOnTop(_ isOnTop: Bool) {
// Recursivley traverses the node's children to update the rendering order depending on the `isOnTop` parameter.
func updateRenderOrder(for node: SCNNode) {
node.renderingOrder = isOnTop ? 2 : 0
for material in node.geometry?.materials ?? [] {
material.readsFromDepthBuffer = !isOnTop
}
for child in node.childNodes {
updateRenderOrder(for: child)
}
}
updateRenderOrder(for: positioningNode)
}
private lazy var fillPlane: SCNNode = {
let correctionFactor = FocusSquare.thickness / 2 // correction to align lines perfectly
let length = CGFloat(1.0 - FocusSquare.thickness * 2 + correctionFactor)
let plane = SCNPlane(width: length, height: length)
let node = SCNNode(geometry: plane)
node.name = "fillPlane"
node.opacity = 0.0
let material = plane.firstMaterial!
material.diffuse.contents = FocusSquare.fillColor
material.isDoubleSided = true
material.ambient.contents = UIColor.black
material.lightingModel = .constant
material.emission.contents = FocusSquare.fillColor
return node
}()
}
// MARK: - Animations and Actions
private func pulseAction() -> SCNAction {
let pulseOutAction = SCNAction.fadeOpacity(to: 0.4, duration: 0.5)
let pulseInAction = SCNAction.fadeOpacity(to: 1.0, duration: 0.5)
pulseOutAction.timingMode = .easeInEaseOut
pulseInAction.timingMode = .easeInEaseOut
return SCNAction.repeatForever(SCNAction.sequence([pulseOutAction, pulseInAction]))
}
private func flashAnimation(duration: TimeInterval) -> SCNAction {
let action = SCNAction.customAction(duration: duration) { (node, elapsedTime) -> Void in
// animate color from HSB 48/100/100 to 48/30/100 and back
let elapsedTimePercentage = elapsedTime / CGFloat(duration)
let saturation = 2.8 * (elapsedTimePercentage - 0.5) * (elapsedTimePercentage - 0.5) + 0.3
if let material = node.geometry?.firstMaterial {
material.diffuse.contents = UIColor(hue: 0.1333, saturation: saturation, brightness: 1.0, alpha: 1.0)
}
}
return action
}
| 39.764356 | 121 | 0.632986 |
e43419f27e81ee9adb5e6c64b1f296c787489093 | 428 | //
// ImageLoader.swift
// TheMovieDB
//
// Created by Tiago Xavier da Cunha Almeida on 11/06/2020.
// Copyright © 2020 Tiago Xavier da Cunha Almeida. All rights reserved.
//
import UIKit
struct DataLoader {
static func getData(with urlString : String?) -> Data? {
guard let url = URL(string: urlString ?? "") else {
return nil
}
return try? Data(contentsOf: url)
}
}
| 20.380952 | 72 | 0.607477 |
f4c29376d87b61bd12d6c97ae3cfe4fba27eccc6 | 1,053 | //
// RegisterResponse.swift
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
import ObjectMapper
class RegisterResponse : NSObject, NSCoding, Mappable{
var data : RegisterData?
var message : String?
class func newInstance(map: Map) -> Mappable?{
return RegisterResponse()
}
required init?(map: Map){}
private override init(){}
func mapping(map: Map)
{
data <- map["data"]
message <- map["message"]
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
@objc required init(coder aDecoder: NSCoder)
{
data = aDecoder.decodeObject(forKey: "data") as? RegisterData
message = aDecoder.decodeObject(forKey: "message") as? String
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
@objc func encode(with aCoder: NSCoder)
{
if data != nil{
aCoder.encode(data, forKey: "data")
}
if message != nil{
aCoder.encode(message, forKey: "message")
}
}
}
| 19.145455 | 81 | 0.660969 |
f86a0e79c5d2796a285500cb99c3d531441292a2 | 3,463 | // SPDX-License-Identifier: MIT
// Copyright © 2018-2020 WireGuard LLC. All Rights Reserved.
import UIKit
import os.log
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var mainVC: MainViewController?
var isLaunchedForSpecificAction = false
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Logger.configureGlobal(tagged: "APP", withFilePath: FileManager.logFileURL?.path)
if let launchOptions = launchOptions {
if launchOptions[.url] != nil || launchOptions[.shortcutItem] != nil {
isLaunchedForSpecificAction = true
}
}
let window = UIWindow(frame: UIScreen.main.bounds)
if #available(iOS 13.0, *) {
window.backgroundColor = .systemBackground
} else {
window.backgroundColor = .white
}
self.window = window
let mainVC = MainViewController()
window.rootViewController = mainVC
window.makeKeyAndVisible()
self.mainVC = mainVC
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
mainVC?.importFromDisposableFile(url: url)
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
mainVC?.refreshTunnelConnectionStatuses()
}
func applicationWillResignActive(_ application: UIApplication) {
guard let allTunnelNames = mainVC?.allTunnelNames() else { return }
application.shortcutItems = QuickActionItem.createItems(allTunnelNames: allTunnelNames)
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
guard shortcutItem.type == QuickActionItem.type else {
completionHandler(false)
return
}
let tunnelName = shortcutItem.localizedTitle
mainVC?.showTunnelDetailForTunnel(named: tunnelName, animated: false, shouldToggleStatus: true)
completionHandler(true)
}
}
extension AppDelegate {
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
return !self.isLaunchedForSpecificAction
}
func application(_ application: UIApplication, viewControllerWithRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? {
guard let vcIdentifier = identifierComponents.last else { return nil }
if vcIdentifier.hasPrefix("TunnelDetailVC:") {
let tunnelName = String(vcIdentifier.suffix(vcIdentifier.count - "TunnelDetailVC:".count))
if let tunnelsManager = mainVC?.tunnelsManager {
if let tunnel = tunnelsManager.tunnel(named: tunnelName) {
return TunnelDetailTableViewController(tunnelsManager: tunnelsManager, tunnel: tunnel)
}
} else {
// Show it when tunnelsManager is available
mainVC?.showTunnelDetailForTunnel(named: tunnelName, animated: false, shouldToggleStatus: false)
}
}
return nil
}
}
| 38.477778 | 165 | 0.680913 |
f7201ccc3dadc38275640c56f0649dedee9ec308 | 2,885 | //
// CustomAlertView.swift
// HelpZRequester
//
// Created by sriharshay on 24/03/20.
// Copyright © 2020 harsha. All rights reserved.
//
import UIKit
public class CustomAlertView: UIView {
@IBOutlet public weak var okButton: UIButton!
@IBOutlet public weak var cancelButton: UIButton!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var message: UILabel!
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var alertBaseView: UIView!
@IBOutlet weak var buttonsStack: UIStackView!
private let nibName = String(describing: CustomAlertView.self)
private var contentView: UIView?
// Caallbacks
var okClicked: (()->())?
var cancelClicked: (()->())?
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.setupUI()
}
private func setupUI() {
guard let view = loadViewFromNib() else { return }
view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
self.addSubview(view)
contentView = view
self.icon.layer.cornerRadius = self.icon.bounds.size.width / 2
self.icon.layer.borderWidth = 5.0
self.icon.layer.borderColor = UIColor.white.cgColor
alertBaseView.layer.cornerRadius = 10.0
}
private func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
public override func awakeFromNib() {
super.awakeFromNib()
}
public func showAlert(alertType: AlertType, title: String?, message: String?) {
if title == nil {self.title.isHidden = true} else {self.title.isHidden = false}
if message == nil {self.message.isHidden = true} else {self.message.isHidden = false}
self.title.text = title
self.message.text = message
switch alertType {
case .success: self.icon.image = UIImage(named: "ic_alert_success")
case .error: self.icon.image = UIImage(named: "ic_alert_error")
case .info: self.icon.image = UIImage(named: "ic_alert_info")
}
guard let contentView = self.contentView else {return}
UIApplication.shared.keyWindow?.addSubview(contentView)
}
@IBAction func cancelClicked(_ sender: Any) {
self.contentView?.removeFromSuperview()
self.cancelClicked?()
}
@IBAction func okClicked(_ sender: Any) {
self.contentView?.removeFromSuperview()
self.okClicked?()
}
}
public enum AlertType {
case success
case info
case error
}
| 31.703297 | 111 | 0.640901 |
90142ffae2647f61fef9eaee3389fa716611b2d8 | 977 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "QuranAPIWrapper",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(name: "QuranAPIWrapper", targets: ["QuranAPIWrapper"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(name: "QuranAPIWrapper", dependencies: []),
.testTarget(name: "QuranAPIWrapperTests", dependencies: ["QuranAPIWrapper"]),
]
)
| 42.478261 | 117 | 0.680655 |
bf022819767988aeb05c17c48f94a4a7b9344645 | 15,317 | //
// FilterPickerView.swift
// YouTag
//
// Created by Youstanzr on 3/15/20.
// Copyright © 2020 Youstanzr. All rights reserved.
//
import UIKit
protocol FilterPickerViewDelegate: class {
func processNewFilter(type: String, filters: NSMutableArray)
}
class FilterPickerView: UIView {
weak var delegate: FilterPickerViewDelegate?
var tagView: YYTTagView!
let contentView: UIView = {
let v = UIView()
v.backgroundColor = .clear
return v
}()
let filterSegment: UISegmentedControl = {
let s = UISegmentedControl(items: ["Tag","Artist","Album","Year","Length"])
s.selectedSegmentIndex = 0
s.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.init(name: "DINCondensed-Bold", size: 20)!], for: .normal)
s.backgroundColor = GraphicColors.backgroundWhite
if #available(iOS 13.0, *) {
s.selectedSegmentTintColor = GraphicColors.orange
s.layer.maskedCorners = .init()
} else {
s.layer.cornerRadius = 0
}
return s
}()
let releaseYrSegment: UISegmentedControl = {
let s = UISegmentedControl(items: ["Year range", "Exact year"])
s.selectedSegmentIndex = 0
s.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.init(name: "DINCondensed-Bold", size: 20)!], for: .normal)
s.backgroundColor = GraphicColors.backgroundWhite
if #available(iOS 13.0, *) {
s.selectedSegmentTintColor = GraphicColors.orange
s.layer.maskedCorners = .init()
} else {
s.layer.cornerRadius = 0
}
return s
}()
let pickerView: UIView = {
let v = UIView()
v.backgroundColor = GraphicColors.backgroundWhite
return v
}()
let closeButton = UIButton()
let addButton: UIButton = {
let button = UIButton()
button.backgroundColor = GraphicColors.green
button.titleLabel?.textColor = .white
button.titleLabel?.font = .boldSystemFont(ofSize: 38)
button.setTitle("+", for: .normal)
button.contentVerticalAlignment = .top
button.titleEdgeInsets = UIEdgeInsets(top: -5.0, left: 0.0, bottom: 0.0, right: 0.0)
return button
}()
let rangeSliderView: UIView = {
let v = UIView()
v.backgroundColor = .clear
return v
}()
let rangeSlider: YYTRangeSlider = {
let rSlider = YYTRangeSlider(frame: .zero)
rSlider.trackTintColor = GraphicColors.trackGray
rSlider.trackHighlightTintColor = GraphicColors.orange
rSlider.thumbColor = .lightGray
return rSlider
}()
let rangeSliderLowerLabel: UILabel = {
let lbl = UILabel()
lbl.text = "00:00"
lbl.font = UIFont.init(name: "DINCondensed-Bold", size: 22)
lbl.textAlignment = .left
return lbl
}()
let rangeSliderUpperLabel: UILabel = {
let lbl = UILabel()
lbl.text = "10:00"
lbl.font = UIFont.init(name: "DINCondensed-Bold", size: 22)
lbl.textAlignment = .right
return lbl
}()
fileprivate var tagViewDefaultTopAnchor: NSLayoutConstraint?
fileprivate var tagViewWithSegmentTopAnchor: NSLayoutConstraint?
fileprivate var rangeSliderViewDefaultTopAnchor: NSLayoutConstraint?
fileprivate var rangeSliderViewWithSegmentTopAnchor: NSLayoutConstraint?
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(frame: UIScreen.main.bounds)
self.isHidden = true
self.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
self.addSubview(closeButton)
closeButton.addTarget(self, action: #selector(close), for: .touchUpInside)
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
closeButton.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
closeButton.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
closeButton.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
self.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
contentView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
contentView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.36).isActive = true
filterSegment.addTarget(self, action: #selector(filterValueChanged(sender:)), for: .valueChanged)
contentView.addSubview(filterSegment)
filterSegment.translatesAutoresizingMaskIntoConstraints = false
filterSegment.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
filterSegment.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
filterSegment.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
filterSegment.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 0.15).isActive = true
releaseYrSegment.isHidden = true
releaseYrSegment.addTarget(self, action: #selector(releaseYrValueChanged(_:)), for: .valueChanged)
pickerView.addSubview(releaseYrSegment)
releaseYrSegment.translatesAutoresizingMaskIntoConstraints = false
releaseYrSegment.leadingAnchor.constraint(equalTo: pickerView.leadingAnchor, constant: 5).isActive = true
releaseYrSegment.trailingAnchor.constraint(equalTo: pickerView.trailingAnchor, constant: -5).isActive = true
releaseYrSegment.topAnchor.constraint(equalTo: pickerView.topAnchor, constant: 5).isActive = true
releaseYrSegment.heightAnchor.constraint(equalTo: pickerView.heightAnchor, multiplier: 0.15).isActive = true
contentView.addSubview(addButton)
addButton.addTarget(self, action: #selector(add), for: .touchUpInside)
addButton.translatesAutoresizingMaskIntoConstraints = false
addButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
addButton.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
addButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
addButton.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 0.225).isActive = true
contentView.addSubview(pickerView)
pickerView.translatesAutoresizingMaskIntoConstraints = false
pickerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
pickerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
pickerView.topAnchor.constraint(equalTo: filterSegment.bottomAnchor).isActive = true
pickerView.bottomAnchor.constraint(equalTo: addButton.topAnchor).isActive = true
tagView = YYTTagView(frame: .zero, tagsList: LibraryManager.getAll(.tags), isAddEnabled: false, isMultiSelection: true, isDeleteEnabled: false, suggestionDataSource: nil)
pickerView.addSubview(tagView)
tagView.translatesAutoresizingMaskIntoConstraints = false
tagView.leadingAnchor.constraint(equalTo: pickerView.leadingAnchor, constant: 5).isActive = true
tagView.trailingAnchor.constraint(equalTo: pickerView.trailingAnchor, constant: -5).isActive = true
tagView.bottomAnchor.constraint(equalTo: pickerView.bottomAnchor, constant: -5).isActive = true
tagViewDefaultTopAnchor = tagView.topAnchor.constraint(equalTo: pickerView.topAnchor, constant: 5)
tagViewWithSegmentTopAnchor = tagView.topAnchor.constraint(equalTo: releaseYrSegment.bottomAnchor, constant: 5)
tagViewDefaultTopAnchor?.isActive = true
tagViewWithSegmentTopAnchor?.isActive = false
rangeSliderView.isHidden = true
pickerView.addSubview(rangeSliderView)
rangeSliderView.translatesAutoresizingMaskIntoConstraints = false
rangeSliderView.leadingAnchor.constraint(equalTo: pickerView.leadingAnchor, constant: 15).isActive = true
rangeSliderView.trailingAnchor.constraint(equalTo: pickerView.trailingAnchor, constant: -15).isActive = true
rangeSliderView.bottomAnchor.constraint(equalTo: pickerView.bottomAnchor, constant: -5).isActive = true
rangeSliderViewDefaultTopAnchor = rangeSliderView.topAnchor.constraint(equalTo: pickerView.topAnchor, constant: 5)
rangeSliderViewWithSegmentTopAnchor = rangeSliderView.topAnchor.constraint(equalTo: releaseYrSegment.bottomAnchor, constant: 5)
rangeSliderViewDefaultTopAnchor?.isActive = true
rangeSliderViewWithSegmentTopAnchor?.isActive = false
rangeSlider.addTarget(self, action: #selector(rangeSliderValueChanged(_:)), for: .valueChanged)
rangeSliderView.addSubview(rangeSlider)
rangeSlider.translatesAutoresizingMaskIntoConstraints = false
rangeSlider.leadingAnchor.constraint(equalTo: rangeSliderView.leadingAnchor, constant: 5).isActive = true
rangeSlider.trailingAnchor.constraint(equalTo: rangeSliderView.trailingAnchor, constant: -5).isActive = true
rangeSlider.heightAnchor.constraint(equalToConstant: 30).isActive = true
rangeSlider.centerYAnchor.constraint(equalTo: rangeSliderView.centerYAnchor).isActive = true
rangeSliderView.addSubview(rangeSliderLowerLabel)
rangeSliderLowerLabel.translatesAutoresizingMaskIntoConstraints = false
rangeSliderLowerLabel.leadingAnchor.constraint(equalTo: rangeSlider.leadingAnchor).isActive = true
rangeSliderLowerLabel.widthAnchor.constraint(equalTo: rangeSliderView.widthAnchor, multiplier: 0.25).isActive = true
rangeSliderLowerLabel.topAnchor.constraint(equalTo: rangeSlider.bottomAnchor).isActive = true
rangeSliderLowerLabel.heightAnchor.constraint(equalTo: rangeSliderView.heightAnchor, multiplier: 0.15).isActive = true
rangeSliderView.addSubview(rangeSliderUpperLabel)
rangeSliderUpperLabel.translatesAutoresizingMaskIntoConstraints = false
rangeSliderUpperLabel.trailingAnchor.constraint(equalTo: rangeSlider.trailingAnchor).isActive = true
rangeSliderUpperLabel.widthAnchor.constraint(equalTo: rangeSliderView.widthAnchor, multiplier: 0.25).isActive = true
rangeSliderUpperLabel.topAnchor.constraint(equalTo: rangeSlider.bottomAnchor).isActive = true
rangeSliderUpperLabel.heightAnchor.constraint(equalTo: rangeSliderView.heightAnchor, multiplier: 0.15).isActive = true
}
func show(animated: Bool) {
print("Show tag picker view")
self.isHidden = false
self.filterValueChanged(sender: filterSegment)
if animated {
self.contentView.frame.origin.y = UIScreen.main.bounds.height
UIView.animate(withDuration: 0.2, animations: {
self.contentView.frame.origin.y = UIScreen.main.bounds.height - self.contentView.frame.height
}, completion: nil)
}
}
@objc func close() {
print("Close button pressed")
self.isHidden = true
}
@objc func add() {
print("Add button pressed")
if filterSegment.selectedSegmentIndex == 0 && tagView.selectedTagList.count > 0 {
// selected tags filter
delegate?.processNewFilter(type: "tags", filters: tagView.selectedTagList)
} else if filterSegment.selectedSegmentIndex == 1 && tagView.selectedTagList.count > 0 {
// selected artists filter
delegate?.processNewFilter(type: "artists", filters: tagView.selectedTagList)
} else if filterSegment.selectedSegmentIndex == 2 && tagView.selectedTagList.count > 0 {
// selected album filter
delegate?.processNewFilter(type: "album", filters: tagView.selectedTagList)
} else if filterSegment.selectedSegmentIndex == 3 && releaseYrSegment.selectedSegmentIndex == 0
&& Int(rangeSlider.lowerValue.rounded(.toNearestOrAwayFromZero)) != Int(rangeSlider.upperValue.rounded(.toNearestOrAwayFromZero)) {
// selected year range filter
delegate?.processNewFilter(type: "releaseYearRange",
filters: NSMutableArray(objects: Int(rangeSlider.lowerValue.rounded(.toNearestOrAwayFromZero))
, Int(rangeSlider.upperValue.rounded(.toNearestOrAwayFromZero))))
} else if filterSegment.selectedSegmentIndex == 3 && releaseYrSegment.selectedSegmentIndex == 1 && tagView.selectedTagList.count > 0 {
// selected exact year filter
delegate?.processNewFilter(type: "releaseYear", filters: tagView.selectedTagList)
} else if filterSegment.selectedSegmentIndex == 4
&& Int(rangeSlider.lowerValue.rounded(.toNearestOrAwayFromZero)) != Int(rangeSlider.upperValue.rounded(.toNearestOrAwayFromZero)) {
// selected duration filter
delegate?.processNewFilter(type: "duration",
filters: NSMutableArray(objects: TimeInterval(rangeSlider.lowerValue).rounded(.toNearestOrAwayFromZero)
, TimeInterval(rangeSlider.upperValue).rounded(.toNearestOrAwayFromZero)))
} else {
close()
}
self.tagView.deselectAllTags()
}
@objc func filterValueChanged(sender: UISegmentedControl) {
tagView.isHidden = true
releaseYrSegment.isHidden = true
rangeSliderView.isHidden = true
tagViewWithSegmentTopAnchor?.isActive = false
tagViewDefaultTopAnchor?.isActive = true
rangeSliderViewWithSegmentTopAnchor?.isActive = false
rangeSliderViewDefaultTopAnchor?.isActive = true
switch sender.selectedSegmentIndex {
case 0:
tagView.isHidden = false
tagView.tagsList = LibraryManager.getAll(.tags)
break
case 1:
tagView.isHidden = false
tagView.tagsList = LibraryManager.getAll(.artists)
break
case 2:
tagView.isHidden = false
tagView.tagsList = LibraryManager.getAll(.album)
break
case 3:
releaseYrSegment.isHidden = false
releaseYrValueChanged(releaseYrSegment)
break
case 4:
rangeSliderView.isHidden = false
rangeSlider.minimumValue = CGFloat(LibraryManager.getDuration(.min))
rangeSlider.maximumValue = CGFloat(LibraryManager.getDuration(.max))
rangeSlider.lowerValue = rangeSlider.minimumValue
rangeSlider.upperValue = rangeSlider.maximumValue
rangeSliderLowerLabel.text = LibraryManager.getDuration(.min).stringFromTimeInterval()
rangeSliderUpperLabel.text = LibraryManager.getDuration(.max).stringFromTimeInterval()
break
default:
break
}
tagView.reloadData()
self.layoutIfNeeded()
tagView.setContentOffset(.zero, animated: false) // Scroll to top
}
@objc func releaseYrValueChanged(_ sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
tagView.isHidden = true
rangeSliderView.isHidden = false
rangeSliderViewDefaultTopAnchor?.isActive = false
rangeSliderViewWithSegmentTopAnchor?.isActive = true
rangeSlider.minimumValue = CGFloat(LibraryManager.getReleaseYear(.min))
rangeSlider.maximumValue = CGFloat(LibraryManager.getReleaseYear(.max))
rangeSlider.lowerValue = rangeSlider.minimumValue
rangeSlider.upperValue = rangeSlider.maximumValue
rangeSliderLowerLabel.text = String(LibraryManager.getReleaseYear(.min))
rangeSliderUpperLabel.text = String(LibraryManager.getReleaseYear(.max))
} else {
rangeSliderView.isHidden = true
tagView.isHidden = false
tagView.tagsList = LibraryManager.getAll(.releaseYear)
tagViewDefaultTopAnchor?.isActive = false
tagViewWithSegmentTopAnchor?.isActive = true
}
tagView.reloadData()
self.layoutIfNeeded()
}
@objc func rangeSliderValueChanged(_ sender: YYTRangeSlider) {
if filterSegment.selectedSegmentIndex == 3 { // release year selected
rangeSliderLowerLabel.text = String(Int(sender.lowerValue.rounded(.toNearestOrAwayFromZero)))
rangeSliderUpperLabel.text = String(Int(sender.upperValue.rounded(.toNearestOrAwayFromZero)))
} else { //length selected
rangeSliderLowerLabel.text = TimeInterval(sender.lowerValue).rounded(.toNearestOrAwayFromZero).stringFromTimeInterval()
rangeSliderUpperLabel.text = TimeInterval(sender.upperValue).rounded(.toNearestOrAwayFromZero).stringFromTimeInterval()
}
}
}
| 46.840979 | 178 | 0.786708 |
f8f101645172873f1af233fd3abc203f059486f0 | 1,731 | //
// This file is autogenerated
//
//
// SecretUI.swift
// Keybase
// Copyright © 2016 Keybase. All rights reserved.
//
import Foundation
import SwiftyJSON
//
// SecretUI
//
public class SecretEntryArg {
public let desc: String?
public let prompt: String?
public let err: String?
public let cancel: String?
public let ok: String?
public let reason: String?
public let showTyping: Bool?
public init(desc: String, prompt: String, err: String, cancel: String, ok: String, reason: String, showTyping: Bool) {
self.desc = desc
self.prompt = prompt
self.err = err
self.cancel = cancel
self.ok = ok
self.reason = reason
self.showTyping = showTyping
}
public class func fromJSON(_ json: JSON) -> SecretEntryArg {
return SecretEntryArg(desc: json["desc"].stringValue, prompt: json["prompt"].stringValue, err: json["err"].stringValue, cancel: json["cancel"].stringValue, ok: json["ok"].stringValue, reason: json["reason"].stringValue, showTyping: json["showTyping"].boolValue)
}
public class func fromJSONArray(_ json: [JSON]) -> [SecretEntryArg] {
return json.map { fromJSON($0) }
}
}
public class SecretEntryRes {
public let text: String?
public let canceled: Bool?
public let storeSecret: Bool?
public init(text: String, canceled: Bool, storeSecret: Bool) {
self.text = text
self.canceled = canceled
self.storeSecret = storeSecret
}
public class func fromJSON(_ json: JSON) -> SecretEntryRes {
return SecretEntryRes(text: json["text"].stringValue, canceled: json["canceled"].boolValue, storeSecret: json["storeSecret"].boolValue)
}
public class func fromJSONArray(_ json: [JSON]) -> [SecretEntryRes] {
return json.map { fromJSON($0) }
}
}
| 23.08 | 265 | 0.699018 |
2f2e1b0f885e330f094d7c7258d0492ae49151db | 24,339 | //
// GameScene.swift
// FlappyBird
//
// Created by pmst on 15/10/4.
// Copyright (c) 2015年 pmst. All rights reserved.
//
import SpriteKit
enum Layer: CGFloat {
case Background
case Obstacle
case Foreground
case Player
case UI
case Flash
}
enum GameState{
case MainMenu
case Tutorial
case Play
case Falling
case ShowingScore
case GameOver
}
struct PhysicsCategory {
static let None: UInt32 = 0
static let Player: UInt32 = 0b1 // 1
static let Obstacle: UInt32 = 0b10 // 2
static let Ground: UInt32 = 0b100 // 4
}
class GameScene: SKScene,SKPhysicsContactDelegate{
// MARK: - 常量
let kGravity:CGFloat = -1500.0
let kImpulse:CGFloat = 400
let kGroundSpeed:CGFloat = 150.0
let kBottomObstacleMinFraction: CGFloat = 0.1
let kBottomObstacleMaxFraction: CGFloat = 0.6
let kGapMultiplier: CGFloat = 3.5
let kFontName = "AmericanTypewriter-Bold"
let kMargin: CGFloat = 20.0
let kAnimDelay = 0.3
let kMinDegrees: CGFloat = -90
let kMaxDegrees: CGFloat = 25
let kAngularVelocity: CGFloat = 1000.0
let worldNode = SKNode()
var playableStart:CGFloat = 0
var playableHeight:CGFloat = 0
let player = SKSpriteNode(imageNamed: "Bird0")
var lastUpdateTime :NSTimeInterval = 0
var dt:NSTimeInterval = 0
var playerVelocity = CGPoint.zero
let sombrero = SKSpriteNode(imageNamed: "Sombrero")
var hitGround = false
var hitObstacle = false
var gameState: GameState = .Play
var scoreLabel:SKLabelNode!
var score = 0
var playerAngularVelocity: CGFloat = 0.0
var lastTouchTime: NSTimeInterval = 0
var lastTouchY: CGFloat = 0.0
// MARK: - 变量
// MARK: - 音乐
let dingAction = SKAction.playSoundFileNamed("ding.wav", waitForCompletion: false)
let flapAction = SKAction.playSoundFileNamed("flapping.wav", waitForCompletion: false)
let whackAction = SKAction.playSoundFileNamed("whack.wav", waitForCompletion: false)
let fallingAction = SKAction.playSoundFileNamed("falling.wav", waitForCompletion: false)
let hitGroundAction = SKAction.playSoundFileNamed("hitGround.wav", waitForCompletion: false)
let popAction = SKAction.playSoundFileNamed("pop.wav", waitForCompletion: false)
let coinAction = SKAction.playSoundFileNamed("coin.wav", waitForCompletion: false)
init(size: CGSize, gameState: GameState) {
self.gameState = gameState
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToView(view: SKView) {
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
addChild(worldNode)
// 以下为替换内容
if gameState == .MainMenu {
switchToMainMenu()
} else {
switchToTutorial()
}
}
// MARK: Setup Method
func setupBackground(){
// 1
let background = SKSpriteNode(imageNamed: "Background")
background.anchorPoint = CGPointMake(0.5, 1)
background.position = CGPointMake(size.width/2.0, size.height)
background.zPosition = Layer.Background.rawValue
worldNode.addChild(background)
// 2
playableStart = size.height - background.size.height
playableHeight = background.size.height
// 新增
let lowerLeft = CGPoint(x: 0, y: playableStart)
let lowerRight = CGPoint(x: size.width, y: playableStart)
// 1
self.physicsBody = SKPhysicsBody(edgeFromPoint: lowerLeft, toPoint: lowerRight)
self.physicsBody?.categoryBitMask = PhysicsCategory.Ground
self.physicsBody?.collisionBitMask = 0
self.physicsBody?.contactTestBitMask = PhysicsCategory.Player
}
func setupForeground() {
for i in 0..<2{
let foreground = SKSpriteNode(imageNamed: "Ground")
foreground.anchorPoint = CGPoint(x: 0, y: 1)
// 改动1
foreground.position = CGPoint(x: CGFloat(i) * size.width, y: playableStart)
foreground.zPosition = Layer.Foreground.rawValue
// 改动2
foreground.name = "foreground"
worldNode.addChild(foreground)
}
}
func setupPlayer(){
player.position = CGPointMake(size.width * 0.2, playableHeight * 0.4 + playableStart)
player.zPosition = Layer.Player.rawValue
let offsetX = player.size.width * player.anchorPoint.x
let offsetY = player.size.height * player.anchorPoint.y
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 17 - offsetX, 23 - offsetY)
CGPathAddLineToPoint(path, nil, 39 - offsetX, 22 - offsetY)
CGPathAddLineToPoint(path, nil, 38 - offsetX, 10 - offsetY)
CGPathAddLineToPoint(path, nil, 21 - offsetX, 0 - offsetY)
CGPathAddLineToPoint(path, nil, 4 - offsetX, 1 - offsetY)
CGPathAddLineToPoint(path, nil, 3 - offsetX, 15 - offsetY)
CGPathCloseSubpath(path)
player.physicsBody = SKPhysicsBody(polygonFromPath: path)
player.physicsBody?.categoryBitMask = PhysicsCategory.Player
player.physicsBody?.collisionBitMask = 0
player.physicsBody?.contactTestBitMask = PhysicsCategory.Obstacle | PhysicsCategory.Ground
worldNode.addChild(player)
}
func setupSomebrero(){
sombrero.position = CGPointMake(31 - sombrero.size.width/2, 29 - sombrero.size.height/2)
player.addChild(sombrero)
}
func setupLabel() {
scoreLabel = SKLabelNode(fontNamed: "AmericanTypewriter-Bold")
scoreLabel.fontColor = SKColor(red: 101.0/255.0, green: 71.0/255.0, blue: 73.0/255.0, alpha: 1.0)
scoreLabel.position = CGPoint(x: size.width/2, y: size.height - 20)
scoreLabel.text = "0"
scoreLabel.verticalAlignmentMode = .Top
scoreLabel.zPosition = Layer.UI.rawValue
worldNode.addChild(scoreLabel)
}
func setupScorecard() {
if score > bestScore() {
setBestScore(score)
}
let scorecard = SKSpriteNode(imageNamed: "ScoreCard")
scorecard.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5)
scorecard.name = "Tutorial"
scorecard.zPosition = Layer.UI.rawValue
worldNode.addChild(scorecard)
let lastScore = SKLabelNode(fontNamed: kFontName)
lastScore.fontColor = SKColor(red: 101.0/255.0, green: 71.0/255.0, blue: 73.0/255.0, alpha: 1.0)
lastScore.position = CGPoint(x: -scorecard.size.width * 0.25, y: -scorecard.size.height * 0.2)
lastScore.text = "\(score)"
scorecard.addChild(lastScore)
let bestScoreLabel = SKLabelNode(fontNamed: kFontName)
bestScoreLabel.fontColor = SKColor(red: 101.0/255.0, green: 71.0/255.0, blue: 73.0/255.0, alpha: 1.0)
bestScoreLabel.position = CGPoint(x: scorecard.size.width * 0.25, y: -scorecard.size.height * 0.2)
bestScoreLabel.text = "\(self.bestScore())"
scorecard.addChild(bestScoreLabel)
let gameOver = SKSpriteNode(imageNamed: "GameOver")
gameOver.position = CGPoint(x: size.width/2, y: size.height/2 + scorecard.size.height/2 + kMargin + gameOver.size.height/2)
gameOver.zPosition = Layer.UI.rawValue
worldNode.addChild(gameOver)
let okButton = SKSpriteNode(imageNamed: "Button")
okButton.position = CGPoint(x: size.width * 0.25, y: size.height/2 - scorecard.size.height/2 - kMargin - okButton.size.height/2)
okButton.zPosition = Layer.UI.rawValue
worldNode.addChild(okButton)
let ok = SKSpriteNode(imageNamed: "OK")
ok.position = CGPoint.zero
ok.zPosition = Layer.UI.rawValue
okButton.addChild(ok)
//MARK - BUG 如果死的很快 这里的sharebutton.size = (0,0)
let shareButton = SKSpriteNode(imageNamed: "Button")
shareButton.position = CGPoint(x: size.width * 0.75, y: size.height/2 - scorecard.size.height/2 - kMargin - shareButton.size.height/2)
shareButton.zPosition = Layer.UI.rawValue
worldNode.addChild(shareButton)
let share = SKSpriteNode(imageNamed: "Share")
share.position = CGPoint.zero
share.zPosition = Layer.UI.rawValue
shareButton.addChild(share)
gameOver.setScale(0)
gameOver.alpha = 0
let group = SKAction.group([
SKAction.fadeInWithDuration(kAnimDelay),
SKAction.scaleTo(1.0, duration: kAnimDelay)
])
group.timingMode = .EaseInEaseOut
gameOver.runAction(SKAction.sequence([
SKAction.waitForDuration(kAnimDelay),
group
]))
scorecard.position = CGPoint(x: size.width * 0.5, y: -scorecard.size.height/2)
let moveTo = SKAction.moveTo(CGPoint(x: size.width/2, y: size.height/2), duration: kAnimDelay)
moveTo.timingMode = .EaseInEaseOut
scorecard.runAction(SKAction.sequence([
SKAction.waitForDuration(kAnimDelay * 2),
moveTo
]))
okButton.alpha = 0
shareButton.alpha = 0
let fadeIn = SKAction.sequence([
SKAction.waitForDuration(kAnimDelay * 3),
SKAction.fadeInWithDuration(kAnimDelay)
])
okButton.runAction(fadeIn)
shareButton.runAction(fadeIn)
let pops = SKAction.sequence([
SKAction.waitForDuration(kAnimDelay),
popAction,
SKAction.waitForDuration(kAnimDelay),
popAction,
SKAction.waitForDuration(kAnimDelay),
popAction,
SKAction.runBlock(switchToGameOver)
])
runAction(pops)
}
func setupMainMenu() {
let logo = SKSpriteNode(imageNamed: "Logo")
logo.position = CGPoint(x: size.width/2, y: size.height * 0.8)
logo.zPosition = Layer.UI.rawValue
worldNode.addChild(logo)
// Play button
let playButton = SKSpriteNode(imageNamed: "Button")
playButton.position = CGPoint(x: size.width * 0.25, y: size.height * 0.25)
playButton.zPosition = Layer.UI.rawValue
worldNode.addChild(playButton)
let play = SKSpriteNode(imageNamed: "Play")
play.position = CGPoint.zero
playButton.addChild(play)
// Rate button
let rateButton = SKSpriteNode(imageNamed: "Button")
rateButton.position = CGPoint(x: size.width * 0.75, y: size.height * 0.25)
rateButton.zPosition = Layer.UI.rawValue
worldNode.addChild(rateButton)
let rate = SKSpriteNode(imageNamed: "Rate")
rate.position = CGPoint.zero
rateButton.addChild(rate)
// Learn button
let learn = SKSpriteNode(imageNamed: "button_learn")
learn.position = CGPoint(x: size.width * 0.5, y: learn.size.height/2 + kMargin)
learn.zPosition = Layer.UI.rawValue
worldNode.addChild(learn)
// Bounce button
let scaleUp = SKAction.scaleTo(1.02, duration: 0.75)
scaleUp.timingMode = .EaseInEaseOut
let scaleDown = SKAction.scaleTo(0.98, duration: 0.75)
scaleDown.timingMode = .EaseInEaseOut
learn.runAction(SKAction.repeatActionForever(SKAction.sequence([
scaleUp, scaleDown
])))
}
func setupTutorial() {
let tutorial = SKSpriteNode(imageNamed: "Tutorial")
tutorial.position = CGPoint(x: size.width * 0.5, y: playableHeight * 0.4 + playableStart)
tutorial.name = "Tutorial"
tutorial.zPosition = Layer.UI.rawValue
worldNode.addChild(tutorial)
let ready = SKSpriteNode(imageNamed: "Ready")
ready.position = CGPoint(x: size.width * 0.5, y: playableHeight * 0.7 + playableStart)
ready.name = "Tutorial"
ready.zPosition = Layer.UI.rawValue
worldNode.addChild(ready)
}
func setupPlayerAnimation() {
var textures: Array<SKTexture> = []
for i in 0..<4 {
textures.append(SKTexture(imageNamed: "Bird\(i)"))
}
for i in 3.stride(through: 0, by: -1) {
textures.append(SKTexture(imageNamed: "Bird\(i)"))
}
let playerAnimation = SKAction.animateWithTextures(textures, timePerFrame: 0.07)
player.runAction(SKAction.repeatActionForever(playerAnimation))
}
// MARK: - GamePlay
func createObstacle()->SKSpriteNode{
let sprite = SKSpriteNode(imageNamed: "Cactus")
sprite.zPosition = Layer.Obstacle.rawValue
sprite.userData = NSMutableDictionary()
//========以下为新增内容=========
let offsetX = sprite.size.width * sprite.anchorPoint.x
let offsetY = sprite.size.height * sprite.anchorPoint.y
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 3 - offsetX, 0 - offsetY)
CGPathAddLineToPoint(path, nil, 5 - offsetX, 309 - offsetY)
CGPathAddLineToPoint(path, nil, 16 - offsetX, 315 - offsetY)
CGPathAddLineToPoint(path, nil, 39 - offsetX, 315 - offsetY)
CGPathAddLineToPoint(path, nil, 51 - offsetX, 306 - offsetY)
CGPathAddLineToPoint(path, nil, 49 - offsetX, 1 - offsetY)
CGPathCloseSubpath(path)
sprite.physicsBody = SKPhysicsBody(polygonFromPath: path)
sprite.physicsBody?.categoryBitMask = PhysicsCategory.Obstacle
sprite.physicsBody?.collisionBitMask = 0
sprite.physicsBody?.contactTestBitMask = PhysicsCategory.Player
return sprite
}
func spawnObstacle(){
//1
let bottomObstacle = createObstacle()
let startX = size.width + bottomObstacle.size.width/2
let bottomObstacleMin = (playableStart - bottomObstacle.size.height/2) + playableHeight * kBottomObstacleMinFraction
let bottomObstacleMax = (playableStart - bottomObstacle.size.height/2) + playableHeight * kBottomObstacleMaxFraction
bottomObstacle.position = CGPointMake(startX, CGFloat.random(min: bottomObstacleMin, max: bottomObstacleMax))
bottomObstacle.name = "BottomObstacle"
worldNode.addChild(bottomObstacle)
let topObstacle = createObstacle()
topObstacle.zRotation = CGFloat(180).degreesToRadians()
topObstacle.position = CGPoint(x: startX, y: bottomObstacle.position.y + bottomObstacle.size.height/2 + topObstacle.size.height/2 + player.size.height * kGapMultiplier)
topObstacle.name = "TopObstacle"
worldNode.addChild(topObstacle)
let moveX = size.width + topObstacle.size.width
let moveDuration = moveX / kGroundSpeed
let sequence = SKAction.sequence([
SKAction.moveByX(-moveX, y: 0, duration: NSTimeInterval(moveDuration)),
SKAction.removeFromParent()
])
topObstacle.runAction(sequence)
bottomObstacle.runAction(sequence)
}
func startSpawning(){
let firstDelay = SKAction.waitForDuration(1.75)
let spawn = SKAction.runBlock(spawnObstacle)
let everyDelay = SKAction.waitForDuration(1.5)
let spawnSequence = SKAction.sequence([
spawn,everyDelay
])
let foreverSpawn = SKAction.repeatActionForever(spawnSequence)
let overallSequence = SKAction.sequence([firstDelay,foreverSpawn])
runAction(overallSequence, withKey: "spawn")
}
func stopSpawning() {
removeActionForKey("spawn")
worldNode.enumerateChildNodesWithName("TopObstacle", usingBlock: { node, stop in
node.removeAllActions()
})
worldNode.enumerateChildNodesWithName("BottomObstacle", usingBlock: { node, stop in
node.removeAllActions()
})
}
func flapPlayer(){
// 发出一次煽动翅膀的声音
runAction(flapAction)
// 重新设定player的速度!!
playerVelocity = CGPointMake(0, kImpulse)
playerAngularVelocity = kAngularVelocity.degreesToRadians()
lastTouchTime = lastUpdateTime
lastTouchY = player.position.y
// 使得帽子下上跳动
let moveUp = SKAction.moveByX(0, y: 12, duration: 0.15)
moveUp.timingMode = .EaseInEaseOut
let moveDown = moveUp.reversedAction()
sombrero.runAction(SKAction.sequence([moveUp,moveDown]))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
let touchLocation = touch?.locationInNode(self)
switch gameState {
case .MainMenu:
if touchLocation?.y < size.height * 0.15 {
//learn()
} else if touchLocation?.x < size.width * 0.6 {
switchToNewGame(.Tutorial)
}
break
case .Tutorial:
switchToPlay()
break
case .Play:
flapPlayer()
break
case .Falling:
break
case .ShowingScore:
break
case .GameOver:
if touchLocation?.x < size.width * 0.6 {
switchToNewGame(.MainMenu)
}
break
}
}
// MARK: - Updates
override func update(currentTime: CFTimeInterval) {
if lastUpdateTime > 0 {
dt = currentTime - lastUpdateTime
} else {
dt = 0
}
lastUpdateTime = currentTime
switch gameState {
case .MainMenu:
break
case .Tutorial:
break
case .Play:
updateForeground()
updatePlayer()
checkHitObstacle()
checkHitGround()
updateScore()
break
case .Falling:
updatePlayer()
checkHitGround()
break
case .ShowingScore:
break
case .GameOver:
break
}
}
func updatePlayer(){
// 只有Y轴上的重力加速度为-1500
let gravity = CGPoint(x: 0, y: kGravity)
let gravityStep = gravity * CGFloat(dt) //计算dt时间下速度的增量
playerVelocity += gravityStep //计算当前速度
// 位置计算
let velocityStep = playerVelocity * CGFloat(dt) //计算dt时间中下落或上升距离
player.position += velocityStep //计算player的位置
// 倘若Player的Y坐标位置在地面上了就不能再下落了 直接设置其位置的y值为地面的表层坐标
if player.position.y - player.size.height/2 < playableStart {
player.position = CGPoint(x: player.position.x, y: playableStart + player.size.height/2)
}
if player.position.y < lastTouchY {
playerAngularVelocity = -kAngularVelocity.degreesToRadians()
}
// Rotate player
let angularStep = playerAngularVelocity * CGFloat(dt)
player.zRotation += angularStep
player.zRotation = min(max(player.zRotation, kMinDegrees.degreesToRadians()), kMaxDegrees.degreesToRadians())
}
func updateForeground(){
worldNode.enumerateChildNodesWithName("foreground") { (node, stop) -> Void in
if let foreground = node as? SKSpriteNode{
let moveAmt = CGPointMake(-self.kGroundSpeed * CGFloat(self.dt), 0)
foreground.position += moveAmt
if foreground.position.x < -foreground.size.width{
foreground.position += CGPoint(x: foreground.size.width * CGFloat(2), y: 0)
}
}
}
}
func checkHitObstacle() {
if hitObstacle {
hitObstacle = false
switchToFalling()
}
}
func checkHitGround() {
if hitGround {
hitGround = false
playerVelocity = CGPoint.zero
player.zRotation = CGFloat(-90).degreesToRadians()
player.position = CGPoint(x: player.position.x, y: playableStart + player.size.width/2)
runAction(hitGroundAction)
switchToShowScore()
}
}
func updateScore() {
worldNode.enumerateChildNodesWithName("BottomObstacle", usingBlock: { node, stop in
if let obstacle = node as? SKSpriteNode {
if let passed = obstacle.userData?["Passed"] as? NSNumber {
if passed.boolValue {
return
}
}
if self.player.position.x > obstacle.position.x + obstacle.size.width/2 {
self.score++
self.scoreLabel.text = "\(self.score)"
self.runAction(self.coinAction)
obstacle.userData?["Passed"] = NSNumber(bool: true)
}
}
})
}
// MARK: - Game States
func switchToMainMenu() {
gameState = .MainMenu
setupBackground()
setupForeground()
setupPlayer()
setupSomebrero()
//TODO: 实现setupMainMenu()主界面布局
setupMainMenu()
setupPlayerAnimation()
}
func switchToTutorial() {
gameState = .Tutorial
setupBackground()
setupForeground()
setupPlayer()
setupSomebrero()
setupLabel()
//TODO: 实现setupTutorial()教程界面布局
setupTutorial()
setupPlayerAnimation()
}
func switchToFalling() {
gameState = .Falling
// Screen shake
let shake = SKAction.screenShakeWithNode(worldNode, amount: CGPoint(x: 0, y: 7.0), oscillations: 10, duration: 1.0)
worldNode.runAction(shake)
// Flash
let whiteNode = SKSpriteNode(color: SKColor.whiteColor(), size: size)
whiteNode.position = CGPoint(x: size.width/2, y: size.height/2)
whiteNode.zPosition = Layer.Flash.rawValue
worldNode.addChild(whiteNode)
whiteNode.runAction(SKAction.removeFromParentAfterDelay(0.01))
runAction(SKAction.sequence([
whackAction,
SKAction.waitForDuration(0.1),
fallingAction
]))
player.removeAllActions()
stopSpawning()
}
func switchToShowScore() {
gameState = .ShowingScore
player.removeAllActions()
stopSpawning()
setupScorecard()
}
func switchToNewGame(gameState: GameState) {
runAction(popAction)
let newScene = GameScene(size: size,gameState:gameState)
let transition = SKTransition.fadeWithColor(SKColor.blackColor(), duration: 0.5)
view?.presentScene(newScene, transition: transition)
}
func switchToGameOver() {
gameState = .GameOver
}
func switchToPlay() {
// Set state
gameState = .Play
// Remove tutorial
worldNode.enumerateChildNodesWithName("Tutorial", usingBlock: { node, stop in
node.runAction(SKAction.sequence([
SKAction.fadeOutWithDuration(0.5),
SKAction.removeFromParent()
]))
})
// Start spawning
startSpawning()
// Move player
flapPlayer()
}
// MARK: - SCORE
func bestScore()->Int{
return NSUserDefaults.standardUserDefaults().integerForKey("BestScore")
}
func setBestScore(bestScore:Int){
NSUserDefaults.standardUserDefaults().setInteger(bestScore, forKey: "BestScore")
NSUserDefaults.standardUserDefaults().synchronize()
}
// MARK: - Physics
func didBeginContact(contact: SKPhysicsContact) {
let other = contact.bodyA.categoryBitMask == PhysicsCategory.Player ? contact.bodyB : contact.bodyA
if other.categoryBitMask == PhysicsCategory.Ground {
hitGround = true
}
if other.categoryBitMask == PhysicsCategory.Obstacle {
hitObstacle = true
}
}
}
| 33.114286 | 176 | 0.604955 |
e0a429938b02e52875a22ebe5f54acf00a09085c | 719 | //
// ActionSheetMultiSelectToggleItemAppearance.swift
// Sheeeeeeeeet
//
// Created by Daniel Saidi on 2018-03-31.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
import UIKit
open class ActionSheetMultiSelectToggleItemAppearance: ActionSheetItemAppearance {
public override init() {
super.init()
}
public override init(copy: ActionSheetItemAppearance) {
super.init(copy: copy)
let copy = copy as? ActionSheetMultiSelectToggleItemAppearance
deselectAllTextColor = copy?.deselectAllTextColor
selectAllTextColor = copy?.selectAllTextColor
}
public var deselectAllTextColor: UIColor?
public var selectAllTextColor: UIColor?
}
| 26.62963 | 82 | 0.719054 |
acaa3e0339933e0f1f26f89389830278e4b03860 | 4,472 | //
// ActionButtonTheme.swift
// 110DigitalLabs
//
// Created by Venkat Krovi on 1/20/20.
// Copyright © 2020 110DigitalLabs. All rights reserved.
//
import UIKit
public struct ActionButtonTheme {
let initalBackgroundColor: UIColor
let disabledBackgroundColor: UIColor?
let selectedBackgroundColor: UIColor?
let highlightedBackgroundColor: UIColor?
let selectedStateHighlightedBackgroundColor: UIColor?
let titleFont: UIFont
let titleColor: UIColor
let titleHighlightedTextColor: UIColor?
let isRounded: Bool?
let border: Bool
let selectedTitleColor: UIColor
public static func primary(mode: Theme.Mode) -> ActionButtonTheme {
return mode == .light ? primaryLightTheme() : primaryDarkTheme()
}
public static func secondary(mode: Theme.Mode) -> ActionButtonTheme {
return mode == .light ? secondaryLightTheme() : secondaryDarkTheme()
}
private static func primaryLightTheme() -> ActionButtonTheme {
return ActionButtonTheme(initalBackgroundColor: Theme.Light.primaryButtonBackgroundColor,
disabledBackgroundColor: nil,
selectedBackgroundColor: Theme.Light.primaryButtonHighlightedBackgroundColor,
highlightedBackgroundColor: nil,
selectedStateHighlightedBackgroundColor: nil,
titleFont: Dimens.Common.actionButtonFont,
titleColor: Theme.Light.primaryButtonTitleColor,
titleHighlightedTextColor: Theme.Light.primaryButtonHighlightedTitleColor,
isRounded: false,
border: false,
selectedTitleColor: .black)
}
private static func primaryDarkTheme() -> ActionButtonTheme {
return ActionButtonTheme(initalBackgroundColor: Theme.Dark.primaryButtonBackgroundColor,
disabledBackgroundColor: nil,
selectedBackgroundColor: nil,
highlightedBackgroundColor: Theme.Dark.primaryButtonHighlightedBackgroundColor,
selectedStateHighlightedBackgroundColor: nil,
titleFont: Dimens.Common.actionButtonFont,
titleColor: Theme.Dark.primaryButtonTitleColor,
titleHighlightedTextColor: Theme.Dark.primaryButtonHighlightedTitleColor,
isRounded: false,
border: false,
selectedTitleColor: .lightText)
}
private static func secondaryLightTheme() -> ActionButtonTheme {
return ActionButtonTheme(initalBackgroundColor: .clear,
disabledBackgroundColor: nil,
selectedBackgroundColor: .clear,
highlightedBackgroundColor: .clear,
selectedStateHighlightedBackgroundColor: .clear,
titleFont: Dimens.Common.secondaryButtonFont,
titleColor: Theme.Light.secondaryButtonTitleColor,
titleHighlightedTextColor: Theme.Light.secondaryButtonHighlightedTitleColor,
isRounded: false,
border: false,
selectedTitleColor: .white)
}
private static func secondaryDarkTheme() -> ActionButtonTheme {
return ActionButtonTheme(initalBackgroundColor: .clear,
disabledBackgroundColor: nil,
selectedBackgroundColor: .clear,
highlightedBackgroundColor: .clear,
selectedStateHighlightedBackgroundColor: .clear,
titleFont: Dimens.Common.secondaryButtonFont,
titleColor: Theme.Dark.secondaryButtonTitleColor,
titleHighlightedTextColor: Theme.Dark.secondaryButtonHighlightedTitleColor,
isRounded: false,
border: false,
selectedTitleColor: .white)
}
}
| 51.402299 | 112 | 0.565966 |
6a4c40ef48892cad7fcaa755a21916120c990f18 | 15,357 | /**
* Copyright IBM Corporation 2016
*
* 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 UIKit
import SVProgressHUD
class FeedViewController: UIViewController {
//represents the inner cicle that spins within the navigation bar on top
@IBOutlet weak var logoImageView: UIImageView!
//represents the outer eye of the inner cicle that spins
@IBOutlet weak var outerEyeImageView: UIImageView!
//collection view that displays the images in the feed
@IBOutlet weak var collectionView: UICollectionView!
//constraint outlet for the outer eye image view's top space
@IBOutlet weak var outerEyeImageViewTopSpaceConstraint: NSLayoutConstraint!
//constraint outlet for the collection view's top space
@IBOutlet weak var collectionViewTopSpaceConstraint: NSLayoutConstraint!
//top bar that shows on intial load of the app
@IBOutlet weak var defaultTopBarView: UIView!
//top bar that shows when displaying search results
@IBOutlet var searchTopBarView: UIView!
//label used to show searchQuery
@IBOutlet weak var wordTagLabel: UILabel!
//label to give user feedback on the results they wanted
@IBOutlet weak var noResultsLabel: UILabel!
@IBOutlet weak var alertBannerView: UIView!
@IBOutlet weak var alertBannerLabel: UILabel!
@IBOutlet weak var topAlertConstraint: NSLayoutConstraint!
//search query parameters that will be sent to the server for results
var searchQuery: String?
//view model of the Feed View controller. It will keep track of state and handle data for this view controller
var viewModel: FeedViewModel!
//Allows for pull down to refresh
var refreshControl: UIRefreshControl!
//state variable used to know if we we were unable to present this alert because the FeedViewController wasn't visible
var failedToPresentImageFeedErrorAlert = false
//Defines the minimum spacing between cells in the collection view
let kMinimumInterItemSpacingForSectionAtIndex: CGFloat = 0
/**
Method called upon view did load. It sets up the collection view, sets up the view model, starts the loading animation at app launch, determines the feed model, and observes when the application becomes active
*/
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupViewModel()
startLoadingAnimationAtAppLaunch()
determineFeedMode()
observeWhenApplicationBecomesActive()
}
/**
Method to determine if we should put the search top bar up because we just performed a search query
*/
func determineFeedMode() {
if let query = searchQuery {
searchTopBarView.frame = defaultTopBarView.frame
defaultTopBarView.isHidden = true
searchTopBarView.isHidden = false
wordTagLabel.text = query.uppercased()
Utils.kernLabelString(wordTagLabel, spacingValue: 1.4)
self.view.addSubview(searchTopBarView)
alertBannerLabel.text = NSLocalizedString("Error Fetching Images, try again later.", comment: "")
}
}
/**
Method observes when the application becomes active. It does this so we can restart the loading animation
*/
func observeWhenApplicationBecomesActive() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector:#selector(FeedViewController.didBecomeActive),
name:NSNotification.Name.UIApplicationDidBecomeActive,
object:nil)
}
/**
Method is called when the application did become active. It trys to restart the loading animation
*/
func didBecomeActive() {
tryToStartLoadingAnimation()
}
/**
Method called upon view will appear. It trys to start the loading animation if there are any photos in the BluemixDataManager's imagesCurrentlyUploading property. It also sets the status bar to white and sets the navigation bar to hidden
- parameter animated: Bool
*/
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.suscribeToBluemixDataManagerNotifications()
// ensure collection view loads correctly under different circumstances
if collectionView.numberOfItems(inSection: 1) < BluemixDataManager.SharedInstance.images.count {
logoImageView.startRotating(1)
viewModel.repullForNewData()
} else {
reloadDataInCollectionView()
}
UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
self.navigationController?.setNavigationBarHidden(true, animated: false)
tryToStartLoadingAnimation()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if searchQuery != nil && self.isMovingToParentViewController &&
collectionView.numberOfItems(inSection: 1) < 1 && noResultsLabel.isHidden {
SVProgressHUD.show()
} else {
tryToShowImageFeedAlert()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
viewModel.unsubscribeFromBluemixDataManagerNotifications()
}
/**
Method called as a callback from the OS when the app receives a memory warning from the OS
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/**
Method sets up the view model, passes the callback we want to be called when there are notifications from the feed view model
*/
func setupViewModel() {
viewModel = FeedViewModel(notifyFeedVC: handleFeedViewModelNotifications, searchQuery: searchQuery)
}
/**
Method sets up the collection view with various initial properties
*/
func setupCollectionView() {
collectionView.delegate = self
collectionView.dataSource = self
Utils.registerNibWithCollectionView("EmptyFeedCollectionViewCell", collectionView: collectionView)
Utils.registerNibWithCollectionView("ImageFeedCollectionViewCell", collectionView: collectionView)
Utils.registerNibWithCollectionView("ImagesCurrentlyUploadingImageFeedCollectionViewCell", collectionView: collectionView)
self.refreshControl = UIRefreshControl()
self.refreshControl.addTarget(self, action: #selector(FeedViewController.userTriggeredRefresh), for: UIControlEvents.valueChanged)
self.refreshControl.isHidden = true
self.refreshControl.tintColor = UIColor.clear
self.collectionView.addSubview(refreshControl)
}
/**
Method reloads the data in the collection view. It is typically called by its view model when it receives data.
*/
func reloadDataInCollectionView() {
collectionView.reloadData()
tryToStopLoadingAnimation()
self.collectionView.setContentOffset(CGPoint.zero, animated: true)
if viewModel.numberOfItemsInSection(1) > viewModel.numberOfCellsWhenUserHasNoPhotos {
dismissImageFeedErrorAlert()
}
}
/**
Method is called when the user triggers a pull to refresh
*/
func userTriggeredRefresh() {
dismissImageFeedErrorAlert()
logoImageView.startRotating(1)
self.refreshControl.endRefreshing()
// fixes offset of emptyCollectionViewCell
collectionView.setContentOffset(CGPoint.zero, animated: true)
viewModel.repullForNewData()
}
/**
Method starts the loading animation at app launch
*/
func startLoadingAnimationAtAppLaunch() {
if viewModel.shouldBeginLoadingAtAppLaunch() {
DispatchQueue.main.async {
self.logoImageView.startRotating(1)
}
}
}
/**
Method will try to start the loading animation if there are any images in the imagesCurrentlyUploading property of the BluemixDataManager. This allows for the loading animation to start up again if the user switches between the image feed and profile vc
*/
func tryToStartLoadingAnimation() {
if viewModel.shouldStartLoadingAnimation() {
logoImageView.startRotating(1)
}
}
/**
Method will only allow the loading animation of the eye to stop if the imagesCurrentlyUploading property of the BluemixDataManager is empty. This is because if the imagesCurrentlyUploading has picture in it, then we want to ensure the eye continues to spin until all the images in the imagesCurrentlyUploading property have finished uploading
*/
func tryToStopLoadingAnimation() {
if viewModel.shouldStopLoadingAnimation() {
logoImageView.stopRotating()
}
}
/**
Display an error alert when we couldn't fetch images from the server
*/
func displayImageFeedErrorAlert() {
if self.isVisible() {
noResultsLabel.isHidden = true
self.topAlertConstraint.constant = self.alertBannerView.frame.size.height - 20
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 15, options: UIViewAnimationOptions(), animations: {
self.view.layoutIfNeeded()
}, completion: nil)
failedToPresentImageFeedErrorAlert = false
} else {
failedToPresentImageFeedErrorAlert = true
}
}
func dismissImageFeedErrorAlert() {
if self.topAlertConstraint.constant > 0 {
self.topAlertConstraint.constant = 0
UIView.animate(withDuration: 0.2, animations: {
self.view.layoutIfNeeded()
})
}
}
/**
Method will be called in viewDidAppear if we were unable to present this alert because the FeedViewController wasn't visible
*/
fileprivate func tryToShowImageFeedAlert() {
if failedToPresentImageFeedErrorAlert {
displayImageFeedErrorAlert()
}
}
/**
Method is caleld when the search icon in the top right corner is pressed
- parameter sender: Any
*/
@IBAction func transitionToSearch(_ sender: Any) {
if let vc = Utils.vcWithNameFromStoryboardWithName("SearchViewController", storyboardName: "Feed") as? SearchViewController {
self.navigationController?.pushViewController(vc, animated: true)
}
}
/**
Method pops the vc on the navigation stack when the back button is pressed when search results are shown
- parameter sender: Any
*/
@IBAction func popVC(_ sender: Any) {
SVProgressHUD.dismiss()
let _ = self.navigationController?.popViewController(animated: true)
}
}
extension FeedViewController: UICollectionViewDataSource {
/**
Method sets up the cell for item at indexPath by asking the view model to set up the collection view cell
- parameter collectionView: UICollectionView
- parameter indexPath: Indexpath
- returns: UICollectionViewCell
*/
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return viewModel.setUpCollectionViewCell(indexPath, collectionView : collectionView)
}
/**
Method sets the number of items in a section by asking the view model how many items are in this section
- parameter collectionView: UICollectionView
- parameter section: Int
- returns: Int
*/
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.numberOfItemsInSection(section)
}
/**
Method returns the number of sections in the collection view by asking its view moddel how many sections are in the collection view
- parameter collectionView: UICollectionview
- returns: Int
*/
func numberOfSections(in collectionView: UICollectionView) -> Int {
return viewModel.numberOfSectionsInCollectionView()
}
}
extension FeedViewController: UICollectionViewDelegate {
/**
Method is called when a cell in the collection view is selected
- parameter collectionView: UICollectionView
- parameter indexPath: IndexPath
*/
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let imageDetailViewModel = viewModel.prepareImageDetailViewModelForSelectedCellAtIndexPath(indexPath),
let imageDetailVC = Utils.vcWithNameFromStoryboardWithName("ImageDetailViewController", storyboardName: "Feed") as? ImageDetailViewController {
imageDetailVC.viewModel = imageDetailViewModel
self.navigationController?.pushViewController(imageDetailVC, animated: true)
}
}
}
extension FeedViewController: UICollectionViewDelegateFlowLayout {
/**
Method returns the size for item at indexPath by asking the view Model for the size for item at indexPath
- parameter collectionView: UICollectionView
- parameter collectionViewLayout: UICollectionViewLayout
- parameter indexPath: IndexPath
- returns: CGSize
*/
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return viewModel.sizeForItemAtIndexPath(indexPath, collectionView: collectionView)
}
}
//ViewModel -> ViewController Communication
extension FeedViewController {
/**
Method handles view model notifications given to this view controller from its view model
- parameter feedViewModelNotification: FeedviewModelNotifications
*/
func handleFeedViewModelNotifications(_ feedViewModelNotification: FeedViewModelNotification) {
if feedViewModelNotification == FeedViewModelNotification.reloadCollectionView {
reloadDataInCollectionView()
if searchQuery != nil {
SVProgressHUD.dismiss()
}
} else if feedViewModelNotification == FeedViewModelNotification.uploadingPhotoStarted {
collectionView.reloadData()
collectionView.contentOffset.y = 0
dismissImageFeedErrorAlert()
tryToStartLoadingAnimation()
} else if feedViewModelNotification == FeedViewModelNotification.noSearchResults {
SVProgressHUD.dismiss()
noResultsLabel.isHidden = self.topAlertConstraint.constant > 0
} else if feedViewModelNotification == FeedViewModelNotification.getImagesServerFailure {
reloadDataInCollectionView()
displayImageFeedErrorAlert()
}
}
}
| 35.548611 | 347 | 0.702286 |
abf4ca1cb9698289cda7002411edac08664ac1ec | 2,377 | //
// NetworkService.swift
// SimpleMapExample
//
// Created by paul on 12/08/2019.
// Copyright © 2019 pavel. All rights reserved.
//
import Foundation
import UIKit
enum Endpoint: String {
case cars
}
public protocol DataReader {
func fetchCars(result: @escaping (Result<[Car], NetworkServiceError>) -> Void)
}
public struct NetworkService: DataReader {
public init() {}
private let urlSession = URLSession.shared
private let baseURL = URL(string: Api.baseURLString)
private let jsonDecoder = JSONDecoder()
private func fetchResources<T: Decodable>(url: URL, completion: @escaping (Result<T, NetworkServiceError>) -> Void) {
urlSession.dataTask(with: url) { (result) in
switch result {
case .success(let (response, data)):
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, 200..<299 ~= statusCode else {
do {
let values = try self.jsonDecoder.decode(ErrorResponse.self, from: data)
completion(.failure(.errorResponse(values)))
} catch {
completion(.failure(.invalidResponse))
}
return
}
do {
let values = try self.jsonDecoder.decode(T.self, from: data)
completion(.success(values))
} catch {
completion(.failure(.decodeError))
}
case .failure(let error):
completion(.failure(.serviceError(error)))
}
}.resume()
}
public func fetchCars(result: @escaping (Result<[Car], NetworkServiceError>) -> Void) {
guard let url = baseURL?.appendingPathComponent(Endpoint.cars.rawValue) else {
result(.failure(.invalidUrl))
return
}
fetchResources(url: url, completion: result)
}
}
public enum NetworkServiceError: Error {
case errorResponse(_ errorResponse: ErrorResponse)
case invalidUrl
case invalidEndpoint
case invalidResponse
case decodeError
case serviceError(_ error: Error) // for exmple device offline, server offline, epmty response or https cert errors.
// need more information from product owner to implement more detailed handler for these error cases
}
| 32.121622 | 121 | 0.603281 |
f8da905b4650a0760d0acda249db92e7ac2ad347 | 1,780 | //
// UICollectionView+Dequeueable.swift
// Unrepeatable
//
// Created by Nahuel Zapata on 5/19/19.
// Copyright © 2019 iNahuelZapata. All rights reserved.
//
import Foundation
import UIKit
extension UICollectionView {
func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("Unable to Dequeue Reusable UICollectionViewCell with identifier: \(T.reuseIdentifier)")
}
return cell
}
func dequeueReusableView<T: UICollectionReusableView>(for indexPath: IndexPath, ofKind kind: String) -> T {
guard let view = self.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: T.reuseIdentifier,
for: indexPath) as? T else {
fatalError("Unable to Dequeue UICollectionReusableView with identifier: \(T.reuseIdentifier)")
}
return view
}
func registerReusableCell<T: UICollectionViewCell>(_: T.Type) {
self.register(T.self, forCellWithReuseIdentifier: T.reuseIdentifier)
}
func registerReusableNibCell<T: UICollectionViewCell>(_: T.Type, forBundle bundle: Bundle) {
let nib = UINib(nibName: T.nibName, bundle: bundle)
self.register(nib, forCellWithReuseIdentifier: T.reuseIdentifier)
}
func registerReusableNibView<T: UICollectionReusableView>(_: T.Type, kind: String, forBundle bundle: Bundle) {
let nib = UINib(nibName: T.nibName, bundle: bundle)
self.register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: T.reuseIdentifier)
}
}
| 38.695652 | 114 | 0.66573 |
ac3bb2f311dce476f17f344c2a80f7dac1fa01cf | 903 | //
// UploadDemoTests.swift
// UploadDemoTests
//
// Created by FOX on 15/8/22.
// Copyright (c) 2015年 mingchen'lab. All rights reserved.
//
import UIKit
import XCTest
class UploadDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
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() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 24.405405 | 111 | 0.615725 |
7163a090179c2dd5b5590f149a36efa26a40577f | 2,900 | /*
* The MIT License
*
* Copyright (c) 2007—2018 NBCO Yandex.Money LLC
*
* 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 FunctionalSwift
import XCTest
import YandexMoneyCoreApi
/// Responsible for validating the API method.
open class ApiMethodTestCase: XCTestCase {
// MARK: - Method test methods
/// Performs validation for api method
///
/// - Parameters:
/// - responseType: Response type
/// - apiMethod: Api method
/// - stubsResponse: Stubs response
/// - verify: Will be called after stubs response retrieved or in case of error
public func validate<M: ApiMethod>(
_ apiMethod: M,
_ stubsResponse: StubsResponse.Type,
_ testClass: Swift.AnyClass,
verify: @escaping (Result<M.Response>) -> Void) {
NetworkTest<M>(session: session, testCase: self)
.set(timeout: stubTimeout)
.stub(apiMethod: apiMethod,
response: stubsResponse.ohhttpStubsResponse(for: testClass))
.validate { task, completion in
task.responseApi { result in
switch result {
case .right(let value):
verify(.right(value))
case .left(let error):
verify(.left(error))
}
completion(nil)
}
}
.perform(apiMethod: apiMethod)
}
// MARK: - Method test properties
private let session: ApiSession = {
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = DefaultHeadersFactory(userAgent: "UnitTest").makeHeaders().value
let session = ApiSession(hostProvider: TestHostProvider())
return session
}()
private let stubTimeout: TimeInterval = 5.0
}
| 37.662338 | 110 | 0.658621 |
0843f23fe50870225219c9f4f7c0b0edae4f9dae | 1,289 | //
// IndicatorView.swift
// Assessment
//
// Created by Tamilarasu on 12/04/2017.
// Copyright © 2017 iTamilan. All rights reserved.
//
import UIKit
class IndicatorView: UIView {
@IBOutlet weak var lblMessage: UILabel!
//Public Statis Methods
public static func addIndicatore(toView view:UIView?,withMessage message:String){
guard view != nil else {
print("No super view to add the indicator view")
return
}
DispatchQueue.main.async {
let indicatoreView : IndicatorView = Bundle.main.loadNibNamed(String(describing: IndicatorView.self), owner: view, options: nil)?.first as! IndicatorView
indicatoreView.lblMessage.text = message
indicatoreView.frame = (view?.bounds)!
view?.addSubview(indicatoreView)
}
}
public static func removeIndicatore(fromView view:UIView?){
DispatchQueue.main.async {
guard view != nil else {
print("No super view to remove the indicatore view")
return
}
for subView in (view?.subviews)!{
if subView is IndicatorView{
subView.removeFromSuperview()
}
}
}
}
}
| 29.976744 | 165 | 0.586501 |
bbf07d3db9c8b497d2cae37147b7d493318142c7 | 234 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
"""
{
{
var t{
{{{{
}
let d=({
{
}if a{{
{
}({
class
case c,case
| 13 | 87 | 0.666667 |
69202b6421968d5c708bf7c7babbf12d59763017 | 5,514 | import UIKit
import Neon
import DateToolsSwift
public protocol DayViewDelegate: AnyObject {
func dayViewDidSelectEventView(_ eventView: EventView)
func dayViewDidLongPressEventView(_ eventView: EventView)
func dayViewDidTapTimeline(dayView: DayView)
func dayView(dayView: DayView, didLongPressTimelineAt date: Date)
func dayView(dayView: DayView, willMoveTo date: Date)
func dayView(dayView: DayView, didMoveTo date: Date)
func dayView(dayView: DayView, didUpdate event: EventDescriptor)
}
public class DayView: UIView, EventViewDelegate, TimelinePagerViewDelegate {
public weak var dataSource: EventDataSource? {
get {
return timelinePagerView.dataSource
}
set(value) {
timelinePagerView.dataSource = value
}
}
public weak var delegate: DayViewDelegate?
/// Hides or shows header view
public var isHeaderViewVisible = true {
didSet {
headerHeight = isHeaderViewVisible ? DayView.headerVisibleHeight : 0
dayHeaderView.isHidden = !isHeaderViewVisible
setNeedsLayout()
}
}
public var timelineScrollOffset: CGPoint {
return timelinePagerView.timelineScrollOffset
}
static let headerVisibleHeight: CGFloat = 88
var headerHeight: CGFloat = headerVisibleHeight
open var autoScrollToFirstEvent: Bool {
get {
return timelinePagerView.autoScrollToFirstEvent
}
set (value) {
timelinePagerView.autoScrollToFirstEvent = value
}
}
let dayHeaderView: DayHeaderView
let timelinePagerView: TimelinePagerView
public var state: DayViewState? {
didSet {
dayHeaderView.state = state
timelinePagerView.state = state
}
}
public var calendar: Calendar = Calendar.autoupdatingCurrent
var style = CalendarStyle()
public init(calendar: Calendar = Calendar.autoupdatingCurrent) {
self.calendar = calendar
self.dayHeaderView = DayHeaderView(calendar: calendar)
self.timelinePagerView = TimelinePagerView(calendar: calendar)
super.init(frame: .zero)
configure()
}
override public init(frame: CGRect) {
self.dayHeaderView = DayHeaderView(calendar: calendar)
self.timelinePagerView = TimelinePagerView(calendar: calendar)
super.init(frame: frame)
configure()
}
required public init?(coder aDecoder: NSCoder) {
self.dayHeaderView = DayHeaderView(calendar: calendar)
self.timelinePagerView = TimelinePagerView(calendar: calendar)
super.init(coder: aDecoder)
configure()
}
func configure() {
addSubview(timelinePagerView)
addSubview(dayHeaderView)
timelinePagerView.delegate = self
if state == nil {
let newState = DayViewState()
newState.calendar = calendar
newState.move(to: Date())
state = newState
}
}
public func updateStyle(_ newStyle: CalendarStyle) {
style = newStyle.copy() as! CalendarStyle
dayHeaderView.updateStyle(style.header)
timelinePagerView.updateStyle(style.timeline)
}
public func timelinePanGestureRequire(toFail gesture: UIGestureRecognizer) {
timelinePagerView.timelinePanGestureRequire(toFail: gesture)
}
public func scrollTo(hour24: Float) {
timelinePagerView.scrollTo(hour24: hour24)
}
public func scrollToFirstEventIfNeeded() {
timelinePagerView.scrollToFirstEventIfNeeded()
}
public func reloadData() {
timelinePagerView.reloadData()
}
override public func layoutSubviews() {
super.layoutSubviews()
dayHeaderView.anchorAndFillEdge(.top, xPad: 0, yPad: layoutMargins.top, otherSize: headerHeight)
timelinePagerView.alignAndFill(align: .underCentered, relativeTo: dayHeaderView, padding: 0)
}
public func transitionToHorizontalSizeClass(_ sizeClass: UIUserInterfaceSizeClass) {
dayHeaderView.transitionToHorizontalSizeClass(sizeClass)
updateStyle(style)
}
public func create(event: EventDescriptor, animated: Bool = false) {
timelinePagerView.create(event: event, animated: animated)
}
public func beginEditing(event: EventDescriptor, animated: Bool = false) {
timelinePagerView.beginEditing(event: event, animated: animated)
}
public func cancelPendingEventCreation() {
timelinePagerView.cancelPendingEventCreation()
}
// MARK: EventViewDelegate
public func eventViewDidTap(_ eventView: EventView) {
delegate?.dayViewDidSelectEventView(eventView)
}
public func eventViewDidLongPress(_ eventview: EventView) {
delegate?.dayViewDidLongPressEventView(eventview)
}
// MARK: TimelinePagerViewDelegate
public func timelinePagerDidSelectEventView(_ eventView: EventView) {
delegate?.dayViewDidSelectEventView(eventView)
}
public func timelinePagerDidLongPressEventView(_ eventView: EventView) {
delegate?.dayViewDidLongPressEventView(eventView)
}
public func timelinePager(timelinePager: TimelinePagerView, willMoveTo date: Date) {
delegate?.dayView(dayView: self, willMoveTo: date)
}
public func timelinePager(timelinePager: TimelinePagerView, didMoveTo date: Date) {
delegate?.dayView(dayView: self, didMoveTo: date)
}
public func timelinePager(timelinePager: TimelinePagerView, didLongPressTimelineAt date: Date) {
delegate?.dayView(dayView: self, didLongPressTimelineAt: date)
}
public func timelinePagerDidTap(timelinePager: TimelinePagerView) {
delegate?.dayViewDidTapTimeline(dayView: self)
}
public func timelinePager(timelinePager: TimelinePagerView, didUpdate event: EventDescriptor) {
delegate?.dayView(dayView: self, didUpdate: event)
}
}
| 30.633333 | 100 | 0.751723 |
ff54acfcc70550dd394053ed399e20d20b766f59 | 3,219 | //
// Characteristic.swift
// ComposableCoreBluetooth
//
// Created by Philipp Gabriel on 15.07.20.
// Copyright © 2020 Philipp Gabriel. All rights reserved.
//
import Foundation
import CoreBluetooth
public struct Characteristic {
let rawValue: CBCharacteristic?
public let identifier: CBUUID
public let service: Service
public let properties: CBCharacteristicProperties
public var value: Data?
public var descriptors: [Descriptor]
public var isNotifying: Bool
init(from characteristic: CBCharacteristic) {
rawValue = characteristic
identifier = characteristic.uuid
service = Service(from: characteristic.service)
properties = characteristic.properties
value = characteristic.value
descriptors = characteristic.descriptors?.map(Descriptor.init) ?? []
isNotifying = characteristic.isNotifying
}
init(
rawValue: CBCharacteristic?,
identifier: CBUUID,
service: Service,
properties: CBCharacteristicProperties,
value: Data?,
descriptors: [Descriptor],
isNotifying: Bool
) {
self.rawValue = rawValue
self.identifier = identifier
self.service = service
self.properties = properties
self.value = value
self.descriptors = descriptors
self.isNotifying = isNotifying
}
}
extension Characteristic {
public enum Action: Equatable {
case didDiscoverDescriptors(Result<[Descriptor], BluetoothError>)
case didUpdateValue(Result<Data, BluetoothError>)
case didWriteValue(Result<Data, BluetoothError>)
case didUpdateNotificationState(Result<Bool, BluetoothError>)
}
}
extension Characteristic {
public static func mock(
identifier: CBUUID,
service: Service,
properties: CBCharacteristicProperties,
value: Data?,
descriptors: [Descriptor],
isNotifying: Bool
) -> Self {
Self(
rawValue: nil,
identifier: identifier,
service: service,
properties: properties,
value: value,
descriptors: descriptors,
isNotifying: isNotifying
)
}
}
extension Characteristic: Identifiable {
public var id: CBUUID {
return identifier
}
}
extension Characteristic: Equatable {
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.identifier == rhs.identifier &&
lhs.properties == rhs.properties &&
lhs.value == rhs.value &&
lhs.descriptors == rhs.descriptors &&
lhs.isNotifying == rhs.isNotifying &&
// Here we explicitly check for service property without
// checking its characteristics for equality
// to avoid recursion which leads to stack overflow
lhs.service.identifier == rhs.service.identifier &&
lhs.service.characteristics().count == rhs.service.characteristics().count &&
lhs.service.includedServices == rhs.service.includedServices &&
lhs.service.isPrimary == rhs.service.isPrimary &&
lhs.service.rawValue == rhs.service.rawValue
}
}
| 30.084112 | 89 | 0.641504 |
6966ebd098bde137599c372d5cfb6f88c0898c3c | 3,075 | //
// Recoverable.swift
// SkeletonView
//
// Created by Juanpe Catalán on 13/05/2018.
// Copyright © 2018 SkeletonView. All rights reserved.
//
import UIKit
protocol Recoverable {
func saveViewState()
func recoverViewState(forced: Bool)
}
extension UIView: Recoverable {
var viewState: RecoverableViewState? {
get { return ao_get(pkey: &ViewAssociatedKeys.viewState) as? RecoverableViewState }
set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.viewState) }
}
@objc func saveViewState() {
viewState = RecoverableViewState(view: self)
}
@objc func recoverViewState(forced: Bool) {
guard let safeViewState = viewState else { return }
startTransition { [weak self] in
self?.layer.cornerRadius = safeViewState.cornerRadius
self?.layer.masksToBounds = safeViewState.clipToBounds
if safeViewState.backgroundColor != self?.backgroundColor || forced {
self?.backgroundColor = safeViewState.backgroundColor
}
}
}
}
extension UILabel{
var labelState: RecoverableTextViewState? {
get { return ao_get(pkey: &ViewAssociatedKeys.labelViewState) as? RecoverableTextViewState }
set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.labelViewState) }
}
override func saveViewState() {
super.saveViewState()
labelState = RecoverableTextViewState(view: self)
}
override func recoverViewState(forced: Bool) {
super.recoverViewState(forced: forced)
startTransition { [weak self] in
self?.textColor = self?.labelState?.textColor
self?.text = self?.labelState?.text
}
}
}
extension UITextView{
var textState: RecoverableTextViewState? {
get { return ao_get(pkey: &ViewAssociatedKeys.labelViewState) as? RecoverableTextViewState }
set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.labelViewState) }
}
override func saveViewState() {
super.saveViewState()
textState = RecoverableTextViewState(view: self)
}
override func recoverViewState(forced: Bool) {
super.recoverViewState(forced: forced)
startTransition { [weak self] in
self?.textColor = self?.textState?.textColor
self?.text = self?.textState?.text
}
}
}
extension UIImageView {
var imageState: RecoverableImageViewState? {
get { return ao_get(pkey: &ViewAssociatedKeys.imageViewState) as? RecoverableImageViewState }
set { ao_setOptional(newValue, pkey: &ViewAssociatedKeys.imageViewState) }
}
override func saveViewState() {
super.saveViewState()
imageState = RecoverableImageViewState(view: self)
}
override func recoverViewState(forced: Bool) {
super.recoverViewState(forced: forced)
startTransition { [weak self] in
self?.image = self?.image == nil || forced ? self?.imageState?.image : self?.image
}
}
}
| 31.377551 | 101 | 0.654959 |
01af51b9b6c32e55d1e855107ccb2ec7b67d6549 | 379 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import AWSCore
import Amplify
public protocol AWSAuthServiceBehavior: class {
func getCredentialsProvider() -> AWSCredentialsProvider
func getIdentityId() -> Result<String, AuthError>
func getToken() -> Result<String, AuthError>
}
| 19.947368 | 59 | 0.728232 |
46aceb8c12dd0516ed6849da8feebdb020a81545 | 8,594 | /**
* Copyright IBM Corporation 2017
*
* 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 Foundation
import Dispatch
public enum State {
case open
case halfopen
case closed
}
public enum BreakerError {
case timeout
case fastFail
}
/// CircuitBreaker class
///
/// A - Parameter types used in the arguments for the command closure.
/// B - Return type from the execution of the command closure.
/// C - Parameter type used as the second argument for the fallback closure.
public class CircuitBreaker<A, B, C> {
// Closure aliases
public typealias AnyFunction<A, B> = (A) -> (B)
public typealias AnyContextFunction<A, B> = (Invocation<A, B, C>) -> B
public typealias AnyFallback<C> = (BreakerError, C) -> Void
private(set) var state: State = State.closed
private let failures: FailureQueue
private let command: AnyFunction<A, B>?
private let fallback: AnyFallback<C>
private let contextCommand: AnyContextFunction<A, B>?
private let bulkhead: Bulkhead?
public let timeout: Int
public let resetTimeout: Int
public let maxFailures: Int
public let rollingWindow: Int
public let breakerStats: Stats = Stats()
private var resetTimer: DispatchSourceTimer?
private let semaphoreCompleted = DispatchSemaphore(value: 1)
private let semaphoreCircuit = DispatchSemaphore(value: 1)
private let queue = DispatchQueue(label: "Circuit Breaker Queue", attributes: .concurrent)
private init(timeout: Int, resetTimeout: Int, maxFailures: Int, rollingWindow: Int, bulkhead: Int, command: (AnyFunction<A, B>)?, contextCommand: (AnyContextFunction<A, B>)?, fallback: @escaping AnyFallback<C>) {
self.timeout = timeout
self.resetTimeout = resetTimeout
self.maxFailures = maxFailures
self.rollingWindow = rollingWindow
self.fallback = fallback
self.command = command
self.contextCommand = contextCommand
self.failures = FailureQueue(size: maxFailures)
self.bulkhead = (bulkhead > 0) ? Bulkhead.init(limit: bulkhead) : nil
}
public convenience init(timeout: Int = 1000, resetTimeout: Int = 60000, maxFailures: Int = 5, rollingWindow: Int = 10000, bulkhead: Int = 0, command: @escaping AnyFunction<A, B>, fallback: @escaping AnyFallback<C>) {
self.init(timeout: timeout, resetTimeout: resetTimeout, maxFailures: maxFailures, rollingWindow: rollingWindow, bulkhead: bulkhead, command: command, contextCommand: nil, fallback: fallback)
}
public convenience init(timeout: Int = 1000, resetTimeout: Int = 60000, maxFailures: Int = 5, rollingWindow: Int = 10000, bulkhead: Int = 0, contextCommand: @escaping AnyContextFunction<A, B>, fallback: @escaping AnyFallback<C>) {
self.init(timeout: timeout, resetTimeout: resetTimeout, maxFailures: maxFailures, rollingWindow: rollingWindow, bulkhead: bulkhead, command: nil, contextCommand: contextCommand, fallback: fallback)
}
// Run
public func run(commandArgs: A, fallbackArgs: C) {
breakerStats.trackRequest()
if breakerState == State.open {
fastFail(fallbackArgs: fallbackArgs)
} else if breakerState == State.halfopen {
let startTime:Date = Date()
if let bulkhead = self.bulkhead {
bulkhead.enqueue(task: {
self.callFunction(commandArgs: commandArgs, fallbackArgs: fallbackArgs)
})
}
else {
callFunction(commandArgs: commandArgs, fallbackArgs: fallbackArgs)
}
self.breakerStats.trackLatency(latency: Int(Date().timeIntervalSince(startTime)))
} else {
let startTime:Date = Date()
if let bulkhead = self.bulkhead {
bulkhead.enqueue(task: {
self.callFunction(commandArgs: commandArgs, fallbackArgs: fallbackArgs)
})
}
else {
callFunction(commandArgs: commandArgs, fallbackArgs: fallbackArgs)
}
self.breakerStats.trackLatency(latency: Int(Date().timeIntervalSince(startTime)))
}
}
private func callFunction(commandArgs: A, fallbackArgs: C) {
var completed = false
func complete(error: Bool) -> () {
weak var _self = self
semaphoreCompleted.wait()
if completed {
semaphoreCompleted.signal()
} else {
completed = true
semaphoreCompleted.signal()
if error {
_self?.handleFailure()
//Note: fallback function is only invoked when failing fast OR when timing out
let _ = fallback(.timeout, fallbackArgs)
} else {
_self?.handleSuccess()
}
return
}
}
if let command = self.command {
setTimeout() {
complete(error: true)
}
let _ = command(commandArgs)
complete(error: false)
} else if let contextCommand = self.contextCommand {
let invocation = Invocation(breaker: self, commandArgs: commandArgs)
setTimeout() { [weak invocation] in
if invocation?.completed == false {
invocation?.setTimedOut()
complete(error: true)
}
}
let _ = contextCommand(invocation)
}
}
private func setTimeout(closure: @escaping () -> ()) {
queue.asyncAfter(deadline: .now() + .milliseconds(self.timeout)) { [weak self] in
self?.breakerStats.trackTimeouts()
closure()
}
}
// Print Current Stats Snapshot
public func snapshot() {
breakerStats.snapshot()
}
public func notifyFailure() {
handleFailure()
}
public func notifySuccess() {
handleSuccess()
}
// Get/Set functions
public private(set) var breakerState: State {
get {
return state
}
set {
state = newValue
}
}
var numberOfFailures: Int {
get {
return failures.count
}
}
private func handleFailure() {
semaphoreCircuit.wait()
Log.verbose("Handling failure...")
// Add a new failure
failures.add(Date.currentTimeMillis())
// Get time difference between oldest and newest failure
let timeWindow: UInt64? = failures.currentTimeWindow
defer {
breakerStats.trackFailedResponse()
semaphoreCircuit.signal()
}
if (state == State.halfopen) {
Log.verbose("Failed in halfopen state.")
open()
return
}
if let timeWindow = timeWindow {
if failures.count >= maxFailures && timeWindow <= UInt64(rollingWindow) {
Log.verbose("Reached maximum number of failures allowed before tripping circuit.")
open()
return
}
}
}
private func handleSuccess() {
semaphoreCircuit.wait()
Log.verbose("Handling success...")
if state == State.halfopen {
close()
}
breakerStats.trackSuccessfulResponse()
semaphoreCircuit.signal()
}
/**
* This function should be called within the boundaries of a semaphore.
* Otherwise, resulting behavior may be unexpected.
*/
private func close() {
// Remove all failures (i.e. reset failure counter to 0)
failures.clear()
breakerState = State.closed
}
/**
* This function should be called within the boundaries of a semaphore.
* Otherwise, resulting behavior may be unexpected.
*/
private func open() {
breakerState = State.open
startResetTimer(delay: .milliseconds(resetTimeout))
}
private func fastFail(fallbackArgs: C) {
Log.verbose("Breaker open... failing fast.")
breakerStats.trackRejected()
let _ = fallback(.fastFail, fallbackArgs)
}
public func forceOpen() {
semaphoreCircuit.wait()
open()
semaphoreCircuit.signal()
}
public func forceClosed() {
semaphoreCircuit.wait()
close()
semaphoreCircuit.signal()
}
public func forceHalfOpen() {
breakerState = State.halfopen
}
private func startResetTimer(delay: DispatchTimeInterval) {
// Cancel previous timer if any
resetTimer?.cancel()
resetTimer = DispatchSource.makeTimerSource(queue: queue)
resetTimer?.setEventHandler { [weak self] in
self?.forceHalfOpen()
}
#if swift(>=3.2)
resetTimer?.schedule(deadline: .now() + delay)
#else
resetTimer?.scheduleOneshot(deadline: .now() + delay)
#endif
resetTimer?.resume()
}
}
| 28.936027 | 232 | 0.676984 |
0e73cd3cf5cb81c01e86e7f07bd73f4932daabec | 1,550 | // Copyright © 2020 Fueled Digital Media, LLC
//
// 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.
#if canImport(Combine)
import Combine
private var cancellablesKey: UInt8 = 0
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
extension CombineExtensions {
public var cancellables: Set<AnyCancellable> {
get {
self.cancellablesHelper.map { Set($0.map(\.cancellable)) } ?? {
let cancellables = Set<AnyCancellable>()
self.cancellables = cancellables
return cancellables
}()
}
set {
self.cancellablesHelper = newValue.map { CancellableHolder($0) }
}
}
private final class CancellableHolder: NSObject {
let cancellable: AnyCancellable
init(_ cancellable: AnyCancellable) {
self.cancellable = cancellable
}
}
private var cancellablesHelper: [CancellableHolder]? {
get {
objc_getAssociatedObject(self.base, &cancellablesKey) as? [CancellableHolder]
}
set {
objc_setAssociatedObject(self.base, &cancellablesKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
}
}
#endif
| 28.703704 | 112 | 0.735484 |
1c9543e469b8c67a81a5e0d00313bd449200012a | 4,761 | public final class PerformerOfSpecificImplementationOfInteractionForVisibleElementImpl:
PerformerOfSpecificImplementationOfInteractionForVisibleElement
{
private let elementVisibilityChecker: ElementVisibilityChecker
private let elementSettings: ElementSettings
private let interactionFailureResultFactory: InteractionFailureResultFactory
private let scroller: Scroller
public init(
elementVisibilityChecker: ElementVisibilityChecker,
elementSettings: ElementSettings,
interactionFailureResultFactory: InteractionFailureResultFactory,
scroller: Scroller)
{
self.elementVisibilityChecker = elementVisibilityChecker
self.elementSettings = elementSettings
self.interactionFailureResultFactory = interactionFailureResultFactory
self.scroller = scroller
}
// TODO: Split function
// swiftlint:disable:next cyclomatic_complexity function_body_length
public func performInteractionForVisibleElement(
minimalPercentageOfVisibleArea: CGFloat,
resolvedElementQuery: ResolvedElementQuery,
interactionSpecificImplementation: InteractionSpecificImplementation,
interactionMarkableAsImpossibleToRetry: MarkableAsImpossibleToRetry)
-> InteractionResult
{
var resolvedElementQuery = resolvedElementQuery
let expectedIndexOfSnapshot: Int
switch elementSettings.interactionMode {
case .useUniqueElement:
expectedIndexOfSnapshot = 0
case .useElementAtIndexInHierarchy(let index):
expectedIndexOfSnapshot = index
}
if var snapshot = resolvedElementQuery.matchingSnapshots.mb_elementAtIndex(expectedIndexOfSnapshot) {
switch elementSettings.interactionMode {
case .useUniqueElement:
if resolvedElementQuery.matchingSnapshots.count > 1 {
return interactionFailureResultFactory.elementIsNotUniqueResult()
}
case .useElementAtIndexInHierarchy:
break
}
if snapshot.isDefinitelyHidden.valueIfAvailable == true {
return interactionFailureResultFactory.elementIsHiddenResult()
}
let scrollingResult = scroller.scrollIfNeeded(
snapshot: snapshot,
minimalPercentageOfVisibleArea: minimalPercentageOfVisibleArea,
expectedIndexOfSnapshotInResolvedElementQuery: expectedIndexOfSnapshot,
resolvedElementQuery: resolvedElementQuery
)
var scrollingFailureMessage: String?
var alreadyCalculatedPercentageOfVisibleArea: CGFloat?
snapshot = scrollingResult.updatedSnapshot
resolvedElementQuery = scrollingResult.updatedResolvedElementQuery
switch scrollingResult.status {
case .scrolled:
// Ok
break
case .alreadyVisible(let percentageOfVisibleArea):
alreadyCalculatedPercentageOfVisibleArea = percentageOfVisibleArea
case .elementWasLostAfterScroll:
scrollingFailureMessage = "ошибка при автоскролле - элемент пропал из иерархии после скролла"
case .internalError(let message):
scrollingFailureMessage = message
}
let percentageOfVisibleArea = alreadyCalculatedPercentageOfVisibleArea
?? elementVisibilityChecker.percentageOfVisibleArea(snapshot: snapshot)
let elementIsSufficientlyVisible = percentageOfVisibleArea >= minimalPercentageOfVisibleArea
if elementIsSufficientlyVisible {
let result = interactionSpecificImplementation.perform(
snapshot: snapshot
)
switch result {
case .success:
return .success
case .failure(let interactionFailure):
return interactionFailureResultFactory.failureResult(
interactionFailure: interactionFailure
)
}
} else {
return interactionFailureResultFactory.elementIsNotSufficientlyVisibleResult(
percentageOfVisibleArea: percentageOfVisibleArea,
minimalPercentageOfVisibleArea: minimalPercentageOfVisibleArea,
scrollingFailureMessage: scrollingFailureMessage
)
}
} else {
return interactionFailureResultFactory.elementIsNotFoundResult()
}
}
}
| 43.678899 | 109 | 0.655745 |
2081297b7b0240ef53e2b16fa86cf1bab9b75be5 | 3,043 | //
// QNNSearchBarTextField.swift
// QNN
//
// Created by wdy on 2018/9/3.
// Copyright © 2018年 qianshengqian. All rights reserved.
//
import UIKit
/**
* Internal UITextField subclass to be able to overwrite the *rect functions.
* This makes it possible to exactly control all margins.
*/
public class QNNSearchBarTextField: UITextField {
/// The SHSearchbarConfig that holds the configured raster size, which is important for rect calculation.
var config: QNNSearchBarConfig {
didSet {
setNeedsLayout()
}
}
/**
* The designated initializer to initialize the configuration object.
* - parameter config: The initial SHSearchBarConfig object that holds the raster size.
*/
init(config: QNNSearchBarConfig) {
self.config = config
super.init(frame: CGRect.zero)
translatesAutoresizingMaskIntoConstraints = false
leftView = config.leftView
}
/**
* The initializer for use with storyboards.
* - parameter coder: A NSCoder instance.
* - note: This initializer is not implementes and will raise an exception when called.
*/
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Overrides
override public func textRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.textRect(forBounds: bounds)
return rectForBounds(rect, originalBounds: bounds)
}
override public func editingRect(forBounds bounds: CGRect) -> CGRect {
let rect = super.editingRect(forBounds: bounds)
return rectForBounds(rect, originalBounds: bounds)
}
/**
* Calculates the text bounds depending on the visibility of left and right views.
* - parameter bounds: The bounds of the textField after subtracting margins for left and/or right views.
* - parameter originalBounds: The current bounds of the textField.
* - returns: The bounds inside the textField so that the text does not overlap with the left and right views.
*/
private func rectForBounds(_ bounds: CGRect, originalBounds: CGRect) -> CGRect {
var minX: CGFloat = 0
var width: CGFloat = 0
if bounds.width == originalBounds.width {
// no left and no right view
minX = config.rasterSize
width = bounds.width - config.rasterSize * 2
} else if bounds.minX > 0 && bounds.width == originalBounds.width - bounds.minX {
// only left view
minX = bounds.minX
width = bounds.width - config.rasterSize
} else if bounds.minX == 0 && bounds.width < originalBounds.width {
// only right view
minX = config.rasterSize
width = bounds.width - config.rasterSize
} else {
// left & right view
minX = bounds.minX
width = bounds.width
}
return CGRect(x: minX, y: 0.0, width: width, height: bounds.height)
}
}
| 33.811111 | 114 | 0.641144 |
de77fac2d9ea88f23f613f02ac787e013d9ef49b | 829 | //
// oldAlerts.swift
// oldAlerts
//
// Created by Edgar Nzokwe on 9/11/21.
//
import SwiftUI
struct oldAlerts: View {
@State private var showSubmitAlert = false;
var body: some View {
Button(action: {
self.showSubmitAlert=true
}){
Text("Submit")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.clipShape(Capsule())
}
.alert(isPresented: $showSubmitAlert ){
Alert(title: Text("Confirm Action"),
message: Text("Are you sure you want to submit the form"),
dismissButton: .default(Text("OK"))
)
}
}
}
struct oldAlerts_Previews: PreviewProvider {
static var previews: some View {
oldAlerts()
}
}
| 22.405405 | 76 | 0.529554 |
67ce5c50660d216705a874c7773ff5f82fd48927 | 1,962 | //
// MakeSectionModel.swift
// GitHubSearchApp
//
// Created by burt on 2018. 9. 26..
// Copyright © 2018년 Burt.K. All rights reserved.
//
import Foundation
import ReactComponentKit
import RxSwift
import ReactComponentKit
extension SearchViewModel {
func makeSectionModel(state: SearchState) -> SearchState {
let sectionModel: DefaultSectionModel
switch state.searchScope {
case .user:
guard !state.users.isEmpty else { return state }
sectionModel = makeUserSectionModel(users: state.users)
return state.copy {
$0.canLoadMore = ($0.users.count > 0 && $0.users.count % $0.perPage == 0)
if $0.canLoadMore {
let loadMoreSectionModel = DefaultSectionModel(items: [LoadMoreItemModel()])
$0.sections = [sectionModel, loadMoreSectionModel]
} else {
$0.sections = [sectionModel]
}
}
case .repo:
guard !state.repos.isEmpty else { return state }
sectionModel = makeRepoSectionModel(repos: state.repos)
return state.copy {
$0.canLoadMore = ($0.repos.count > 0 && $0.repos.count % $0.perPage == 0)
if $0.canLoadMore {
let loadMoreSectionModel = DefaultSectionModel(items: [LoadMoreItemModel()])
$0.sections = [sectionModel, loadMoreSectionModel]
} else {
$0.sections = [sectionModel]
}
}
}
}
private func makeUserSectionModel(users: [User]) -> DefaultSectionModel {
let items = users.map(UserItemModel.init)
return DefaultSectionModel(items: items)
}
private func makeRepoSectionModel(repos: [Repo]) -> DefaultSectionModel {
let items = repos.map(RepoItemModel.init)
return DefaultSectionModel(items: items)
}
}
| 35.035714 | 96 | 0.58104 |
23727b89ba1c02daeb89e361fe63b516bc437ff4 | 2,801 | //
// UIColor+.swift
// Grades
//
// Created by Jiří Zdvomka on 02/03/2019.
// Copyright © 2019 jiri.zdovmka. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
enum Theme {
static let background = UIColor.white
static let primary = UIColor(hex: 0x9776C1)
static let secondary = UIColor(hex: 0x6763CE)
static let secondaryDark = UIColor(hex: 0x8463CE)
static let text = UIColor(hex: 0x525252)
static let grayText = UIColor(hex: 0x8B8B8B)
static let borderGray = UIColor(hex: 0xD8D8D8)
static let lightGrayBackground = UIColor(hex: 0xFBFBFB)
static let tableHeaderBackground = UIColor(hex: 0xF3F3F3)
static let sectionGrayText = UIColor(hex: 0x7A7A7A)
static let success = UIColor(hex: 0x73C0A2)
static let danger = UIColor(hex: 0xCB544B)
static let info = UIColor(hex: 0x7BAFC6)
static let lightGreen = UIColor(hex: 0x45D75E)
static let yellow = UIColor(hex: 0xFFCC00)
static let orange = UIColor(hex: 0xFF9500)
static let darkOrange = UIColor(hex: 0xBA6D00)
static var primaryGradient: CAGradientLayer {
let gradient = CAGradientLayer()
let startColor = UIColor(hex: 0x8C72C4).cgColor
let endColor = UIColor(hex: 0x7468CA).cgColor
gradient.colors = [startColor, endColor]
gradient.startPoint = CGPoint(x: 0.0, y: 0.6)
gradient.endPoint = CGPoint(x: 0.75, y: 0.0)
return gradient
}
static func getGradeColor(forGrade grade: String, defaultColor: UIColor? = nil) -> UIColor {
let color: UIColor
switch grade {
case "A":
color = UIColor.Theme.lightGreen
case "B":
color = UIColor.Theme.success
case "C":
color = UIColor.Theme.yellow
case "D":
color = UIColor.Theme.orange
case "E":
color = UIColor.Theme.darkOrange
case "F":
color = UIColor.Theme.danger
default:
color = defaultColor ?? UIColor.Theme.text
}
return color
}
}
/// Create UIColor from RGB
convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
self.init(
red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: a
)
}
// Create UIColor from a hex value
convenience init(hex: Int, a: CGFloat = 1.0) {
self.init(
red: (hex >> 16) & 0xFF,
green: (hex >> 8) & 0xFF,
blue: hex & 0xFF,
a: a
)
}
}
| 31.122222 | 100 | 0.560514 |
89c14cc21a5d13f8f691316d265e851599207fdd | 21,852 | // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t
//
// Test code completion at the beginning of expr-postfix.
//
//===--- Helper types that are used in this test
struct FooStruct {
}
var fooObject : FooStruct
func fooFunc() -> FooStruct {
return fooObject
}
enum FooEnum {
}
class FooClass {
}
protocol FooProtocol {
}
typealias FooTypealias = Int
// COMMON: Begin completions
// Function parameter
// COMMON-DAG: Decl[LocalVar]/Local: fooParam[#FooStruct#]{{; name=.+$}}
// Global completions
// COMMON-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}}
// COMMON-DAG: Decl[Enum]/CurrModule: FooEnum[#FooEnum#]{{; name=.+$}}
// COMMON-DAG: Decl[Class]/CurrModule: FooClass[#FooClass#]{{; name=.+$}}
// COMMON-DAG: Decl[Protocol]/CurrModule/Flair[RareType]: FooProtocol[#FooProtocol#]{{; name=.+$}}
// COMMON-DAG: Decl[TypeAlias]/CurrModule{{(/TypeRelation\[Convertible\])?}}: FooTypealias[#Int#]{{; name=.+$}}
// COMMON-DAG: Decl[GlobalVar]/CurrModule: fooObject[#FooStruct#]{{; name=.+$}}
// COMMON-DAG: Keyword[try]/None: try{{; name=.+$}}
// COMMON-DAG: Literal[Boolean]/None: true[#Bool#]{{; name=.+$}}
// COMMON-DAG: Literal[Boolean]/None: false[#Bool#]{{; name=.+$}}
// COMMON-DAG: Literal[Nil]/None: nil{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int8[#Int8#]{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int16[#Int16#]{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int32[#Int32#]{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Int64[#Int64#]{{; name=.+$}}
// COMMON-DAG: Decl[Struct]/OtherModule[Swift]/IsSystem: Bool[#Bool#]{{; name=.+$}}
// COMMON-DAG: Keyword[#function]/None{{(/TypeRelation\[Convertible\])?}}: #function[#String#]{{; name=.+$}}
// COMMON-DAG: Keyword[#file]/None{{(/TypeRelation\[Convertible\])?}}: #file[#String#]{{; name=.+$}}
// COMMON-DAG: Keyword[#line]/None{{(/TypeRelation\[Convertible\])?}}: #line[#Int#]{{; name=.+$}}
// COMMON-DAG: Keyword[#column]/None{{(/TypeRelation\[Convertible\])?}}: #column[#Int#]{{; name=.+$}}
// COMMON: End completions
// NO_SELF-NOT: {{[[:<:]][Ss]elf[[:>:]]}}
//===--- Test that we can code complete at the beginning of expr-postfix.
func testExprPostfixBegin1(fooParam: FooStruct) {
#^EXPR_POSTFIX_BEGIN_1?check=COMMON^#
}
func testExprPostfixBegin2(fooParam: FooStruct) {
1 + #^EXPR_POSTFIX_BEGIN_2?check=COMMON^#
}
func testExprPostfixBegin3(fooParam: FooStruct) {
fooFunc()
1 + #^EXPR_POSTFIX_BEGIN_3?check=COMMON^#
}
func testExprPostfixBegin4(fooParam: FooStruct) {
"\(#^EXPR_POSTFIX_BEGIN_4?xfail=FIXME-64812321;check=COMMON^#)"
}
func testExprPostfixBegin5(fooParam: FooStruct) {
1+#^EXPR_POSTFIX_BEGIN_5?check=COMMON^#
}
func testExprPostfixBegin6(fooParam: FooStruct) {
for i in 1...#^EXPR_POSTFIX_BEGIN_6?check=COMMON^#
}
//===--- Test that we sometimes ignore the expr-postfix.
// In these cases, displaying '.instance*' completion results is technically
// valid, but would be extremely surprising.
func testExprPostfixBeginIgnored1(fooParam: FooStruct) {
fooFunc()
#^EXPR_POSTFIX_BEGIN_IGNORED_1?check=COMMON^#
}
func testExprPostfixBeginIgnored2(fooParam: FooStruct) {
123456789
#^EXPR_POSTFIX_BEGIN_IGNORED_2?check=COMMON^#
}
func testExprPostfixBeginIgnored3(fooParam: FooStruct) {
123456789 +
fooFunc()
#^EXPR_POSTFIX_BEGIN_IGNORED_3?check=COMMON^#
}
//===--- Test that we include function parameters in completion results.
func testFindFuncParam1(fooParam: FooStruct, a: Int, b: Float, c: inout Double, d: inout Double) {
#^FIND_FUNC_PARAM_1?check=FIND_FUNC_PARAM_1;check=COMMON;check=NO_SELF^#
// FIND_FUNC_PARAM_1: Begin completions
// FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: c[#inout Double#]{{; name=.+$}}
// FIND_FUNC_PARAM_1-DAG: Decl[LocalVar]/Local: d[#inout Double#]{{; name=.+$}}
// FIND_FUNC_PARAM_1: End completions
}
func testFindFuncParam2<Foo : FooProtocol>(fooParam: FooStruct, foo: Foo) {
#^FIND_FUNC_PARAM_2?check=FIND_FUNC_PARAM_2;check=COMMON;check=NO_SELF^#
// FIND_FUNC_PARAM_2: Begin completions
// FIND_FUNC_PARAM_2-DAG: Decl[GenericTypeParam]/Local: Foo[#Foo#]{{; name=.+$}}
// FIND_FUNC_PARAM_2-DAG: Decl[LocalVar]/Local: foo[#FooProtocol#]{{; name=.+$}}
// FIND_FUNC_PARAM_2: End completions
}
struct TestFindFuncParam3_4 {
func testFindFuncParam3(a: Int, b: Float, c: Double) {
#^FIND_FUNC_PARAM_3^#
// FIND_FUNC_PARAM_3: Begin completions
// FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam3_4#]{{; name=.+$}}
// FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_FUNC_PARAM_3-DAG: Decl[LocalVar]/Local: c[#Double#]{{; name=.+$}}
// FIND_FUNC_PARAM_3: End completions
}
func testFindFuncParam4<U>(a: Int, b: U) {
#^FIND_FUNC_PARAM_4^#
// FIND_FUNC_PARAM_4: Begin completions
// FIND_FUNC_PARAM_4-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}}
// FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam3_4#]{{; name=.+$}}
// FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_4-DAG: Decl[LocalVar]/Local: b[#U#]{{; name=.+$}}
// FIND_FUNC_PARAM_4: End completions
}
}
struct TestFindFuncParam5_6<T> {
func testFindFuncParam5(a: Int, b: T) {
#^FIND_FUNC_PARAM_5^#
// FIND_FUNC_PARAM_5: Begin completions
// FIND_FUNC_PARAM_5-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}}
// FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam5_6<T>#]{{; name=.+$}}
// FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_5-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}}
// FIND_FUNC_PARAM_5: End completions
}
func testFindFuncParam6<U>(a: Int, b: T, c: U) {
#^FIND_FUNC_PARAM_6^#
// FIND_FUNC_PARAM_6: Begin completions
// FIND_FUNC_PARAM_6-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam5_6<T>#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}}
// FIND_FUNC_PARAM_6-DAG: Decl[LocalVar]/Local: c[#U#]{{; name=.+$}}
// FIND_FUNC_PARAM_6: End completions
}
}
class TestFindFuncParam7 {
func testFindFuncParam7(a: Int, b: Float, c: Double) {
#^FIND_FUNC_PARAM_7^#
// FIND_FUNC_PARAM_7: Begin completions
// FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: self[#TestFindFuncParam7#]{{; name=.+$}}
// FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_FUNC_PARAM_7-DAG: Decl[LocalVar]/Local: c[#Double#]{{; name=.+$}}
// FIND_FUNC_PARAM_7: End completions
}
}
func testFindFuncParamSelector1(a: Int, b x: Float, foo fooParam: FooStruct, bar barParam: inout FooStruct) {
#^FIND_FUNC_PARAM_SELECTOR_1?check=FIND_FUNC_PARAM_SELECTOR_1;check=COMMON;check=NO_SELF^#
// FIND_FUNC_PARAM_SELECTOR_1: Begin completions
// FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: x[#Float#]{{; name=.+$}}
// FIND_FUNC_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: barParam[#inout FooStruct#]{{; name=.+$}}
// FIND_FUNC_PARAM_SELECTOR_1: End completions
}
//===--- Test that we include constructor parameters in completion results.
class TestFindConstructorParam1 {
init(a: Int, b: Float) {
#^FIND_CONSTRUCTOR_PARAM_1^#
// FIND_CONSTRUCTOR_PARAM_1: Begin completions
// FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam1#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_1: End completions
}
}
struct TestFindConstructorParam2 {
init(a: Int, b: Float) {
#^FIND_CONSTRUCTOR_PARAM_2^#
// FIND_CONSTRUCTOR_PARAM_2: Begin completions
// FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam2#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: b[#Float#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_2: End completions
}
}
class TestFindConstructorParam3 {
init<U>(a: Int, b: U) {
#^FIND_CONSTRUCTOR_PARAM_3^#
// FIND_CONSTRUCTOR_PARAM_3: Begin completions
// FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam3#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_3-DAG: Decl[LocalVar]/Local: b[#U#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_3: End completions
}
}
class TestFindConstructorParam4<T> {
init(a: Int, b: T) {
#^FIND_CONSTRUCTOR_PARAM_4^#
// FIND_CONSTRUCTOR_PARAM_4: Begin completions
// FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam4<T>#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_4-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_4: End completions
}
}
class TestFindConstructorParam5<T> {
init<U>(a: Int, b: T, c: U) {
#^FIND_CONSTRUCTOR_PARAM_5^#
// FIND_CONSTRUCTOR_PARAM_5: Begin completions
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[GenericTypeParam]/Local: U[#U#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParam5<T>#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: a[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: b[#T#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5-DAG: Decl[LocalVar]/Local: c[#U#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_5: End completions
}
}
class TestFindConstructorParamSelector1 {
init(a x: Int, b y: Float) {
#^FIND_CONSTRUCTOR_PARAM_SELECTOR_1^#
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1: Begin completions
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: self[#TestFindConstructorParamSelector1#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: x[#Int#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1-DAG: Decl[LocalVar]/Local: y[#Float#]{{; name=.+$}}
// FIND_CONSTRUCTOR_PARAM_SELECTOR_1: End completions
}
}
//===--- Test that we include destructor's 'self' in completion results.
class TestFindDestructorParam1 {
deinit {
#^FIND_DESTRUCTOR_PARAM_1^#
// FIND_DESTRUCTOR_PARAM_1: Begin completions
// FIND_DESTRUCTOR_PARAM_1-DAG: Decl[LocalVar]/Local: self[#TestFindDestructorParam1#]{{; name=.+$}}
// FIND_DESTRUCTOR_PARAM_1: End completions
}
}
class TestFindDestructorParam2<T> {
deinit {
#^FIND_DESTRUCTOR_PARAM_2^#
// FIND_DESTRUCTOR_PARAM_2: Begin completions
// FIND_DESTRUCTOR_PARAM_2-DAG: Decl[GenericTypeParam]/Local: T[#T#]{{; name=.+$}}
// FIND_DESTRUCTOR_PARAM_2-DAG: Decl[LocalVar]/Local: self[#TestFindDestructorParam2<T>#]{{; name=.+$}}
// FIND_DESTRUCTOR_PARAM_2: End completions
}
}
struct TestPlaceholdersInNames {
var <#placeholder_in_name1#>: FooStruct
func test() {
var <#placeholder_in_name2#>: FooStruct
#^NO_PLACEHOLDER_NAMES_1^#
}
// NO_PLACEHOLDER_NAMES_1-NOT: placeholder_in_name
}
//===--- Test that we don't crash in constructors and destructors in contexts
//===--- where they are not allowed.
init() {
var fooParam = FooStruct()
#^IN_INVALID_1?check=COMMON^#
}
init { // Missing parameters
var fooParam = FooStruct()
#^IN_INVALID_2?check=COMMON^#
}
deinit {
var fooParam = FooStruct()
#^IN_INVALID_3?check=COMMON^#
}
func testInInvalid5() {
var fooParam = FooStruct()
init() {
#^IN_INVALID_5?check=COMMON^#
}
}
func testInInvalid6() {
deinit {
var fooParam = FooStruct()
#^IN_INVALID_6?check=COMMON^#
}
}
struct TestInInvalid7 {
deinit {
var fooParam = FooStruct()
#^IN_INVALID_7?check=COMMON^#
}
}
func foo() -> Undeclared {
var fooParam = FooStruct()
#^IN_INVALID_8?check=COMMON^#
}
// MY_ALIAS_1: Begin completions
// MY_ALIAS_1-DAG: Decl[TypeAlias]/Local: MyAlias[#(T, T)#];
// MY_ALIAS_1-DAG: Decl[LocalVar]/Local/TypeRelation[Convertible]: x[#MyAlias<Int>#]; name=x
// MY_ALIAS_1-DAG: Decl[LocalVar]/Local/TypeRelation[Convertible]: y[#(Int, Int)#]; name=y
// MY_ALIAS_1: End completions
func testGenericTypealias1() {
typealias MyAlias<T> = (T, T)
let x: MyAlias<Int> = (1, 2)
var y: (Int, Int)
y = #^GENERIC_TYPEALIAS_1?check=MY_ALIAS_1^#
}
// MY_ALIAS_2: Begin completions
// MY_ALIAS_2-DAG: Decl[TypeAlias]/Local: MyAlias[#(T, T)#];
// MY_ALIAS_2-DAG: Decl[LocalVar]/Local/TypeRelation[Convertible]: x[#(Int, Int)#]; name=x
// MY_ALIAS_2-DAG: Decl[LocalVar]/Local/TypeRelation[Convertible]: y[#MyAlias<Int>#]; name=y
// MY_ALIAS_2: End completions
func testGenericTypealias2() {
typealias MyAlias<T> = (T, T)
let x: (Int, Int) = (1, 2)
var y: MyAlias<Int>
y = #^GENERIC_TYPEALIAS_2?check=MY_ALIAS_2^#
}
func testInForEach1(arg: Int) {
let local = 2
for index in #^IN_FOR_EACH_1^# {
let inBody = 3
}
let after = 4
// IN_FOR_EACH_1-NOT: Decl[LocalVar]
// IN_FOR_EACH_1: Decl[LocalVar]/Local: local[#Int#];
// IN_FOR_EACH_1-NOT: after
// IN_FOR_EACH_1: Decl[LocalVar]/Local: arg[#Int#];
// IN_FOR_EACH_1-NOT: Decl[LocalVar]
}
func testInForEach2(arg: Int) {
let local = 2
for index in 1 ... #^IN_FOR_EACH_2^# {
let inBody = 3
}
let after = 4
// IN_FOR_EACH_2-NOT: Decl[LocalVar]
// IN_FOR_EACH_2: Decl[LocalVar]/Local/TypeRelation[Convertible]: local[#Int#];
// IN_FOR_EACH_2-NOT: after
// IN_FOR_EACH_2: Decl[LocalVar]/Local/TypeRelation[Convertible]: arg[#Int#];
// IN_FOR_EACH_2-NOT: Decl[LocalVar]
}
func testInForEach3(arg: Int) {
let local = 2
for index: Int in 1 ... 2 where #^IN_FOR_EACH_3^# {
let inBody = 3
}
let after = 4
// IN_FOR_EACH_3-NOT: Decl[LocalVar]
// IN_FOR_EACH_3: Decl[LocalVar]/Local: index[#Int#];
// IN_FOR_EACH_3-NOT: Decl[LocalVar]
// IN_FOR_EACH_3: Decl[LocalVar]/Local: local[#Int#];
// IN_FOR_EACH_3-NOT: after
// IN_FOR_EACH_3: Decl[LocalVar]/Local: arg[#Int#];
// IN_FOR_EACH_3-NOT: Decl[LocalVar]
}
func testInForEach4(arg: Int) {
let local = 2
for index in 1 ... 2 {
#^IN_FOR_EACH_4?check=IN_FOR_EACH_3^#
}
let after = 4
}
func testInForEach5(arg: Int) {
let local = 2
for index in [#^IN_FOR_EACH_5?check=IN_FOR_EACH_1^#] {}
let after = 4
}
func testInForEach6(arg: Int) {
let local = 2
for index in [1,#^IN_FOR_EACH_6?check=IN_FOR_EACH_2^#] {}
let after = 4
}
func testInForEach7(arg: Int) {
let local = 2
for index in [1:#^IN_FOR_EACH_7?check=IN_FOR_EACH_1^#] {}
let after = 4
}
func testInForEach8(arg: Int) {
let local = 2
for index in [#^IN_FOR_EACH_8?check=IN_FOR_EACH_4^#:] {}
let after = 4
}
func testInForEach9(arg: Int) {
let local = 2
for index in [#^IN_FOR_EACH_9?check=IN_FOR_EACH_4^#:2] {}
let after = 4
// NOTE: [Convertible] to AnyHashable.
// IN_FOR_EACH_4-NOT: Decl[LocalVar]
// IN_FOR_EACH_4: Decl[LocalVar]/Local/TypeRelation[Convertible]: local[#Int#];
// IN_FOR_EACH_4-NOT: after
// IN_FOR_EACH_4: Decl[LocalVar]/Local/TypeRelation[Convertible]: arg[#Int#];
// IN_FOR_EACH_4-NOT: Decl[LocalVar]
}
func testInForEach10(arg: Int) {
let local = 2
for index in [1:2, #^IN_FOR_EACH_10^#] {}
let after = 4
}
// IN_FOR_EACH_10-NOT: Decl[LocalVar]
// IN_FOR_EACH_10: Decl[LocalVar]/Local/TypeRelation[Convertible]: local[#Int#];
// IN_FOR_EACH_10-NOT: after
// IN_FOR_EACH_10: Decl[LocalVar]/Local/TypeRelation[Convertible]: arg[#Int#];
// IN_FOR_EACH_10-NOT: Decl[LocalVar]
func testInForEach11(arg: Int) {
let local = 2
for index in [1:2, #^IN_FOR_EACH_11?check=IN_FOR_EACH_2^#:] {}
let after = 4
}
func testInForEach12(arg: Int) {
let local = 2
for index in [1:2, #^IN_FOR_EACH_12?check=IN_FOR_EACH_2^#:2] {}
let after = 4
}
@available(*, deprecated)
struct Deprecated {
@available(*, deprecated)
func testDeprecated() {
@available(*, deprecated) let local = 1
@available(*, deprecated) func f() {}
#^DEPRECATED_1^#
}
}
// DEPRECATED_1: Begin completions
// DEPRECATED_1-DAG: Decl[LocalVar]/Local/NotRecommended: local[#Int#];
// DEPRECATED_1-DAG: Decl[FreeFunction]/Local/NotRecommended: f()[#Void#];
// DEPRECATED_1-DAG: Decl[InstanceMethod]/CurrNominal/NotRecommended: testDeprecated()[#Void#];
// DEPRECATED_1-DAG: Decl[Struct]/CurrModule/NotRecommended: Deprecated[#Deprecated#];
// DEPRECATED_1: End completions
func testTuple(localInt: Int) {
let localStr: String = "foo"
let _: (Int, String) = (1, #^IN_TUPLE_1^#)
let _: (Int, String) = (#^IN_TUPLE_2^#, "foo")
}
// IN_TUPLE_1: Begin completions
// IN_TUPLE_1-DAG: Decl[LocalVar]/Local/TypeRelation[Convertible]: localStr[#String#]; name=localStr
// IN_TUPLE_1-DAG: Decl[LocalVar]/Local: localInt[#Int#]; name=localInt
// IN_TUPLE_1: End completions
// IN_TUPLE_2: Begin completions
// IN_TUPLE_2-DAG: Decl[LocalVar]/Local: localStr[#String#]; name=localStr
// IN_TUPLE_2-DAG: Decl[LocalVar]/Local/TypeRelation[Convertible]: localInt[#Int#]; name=localInt
// IN_TUPLE_2: End completions
var ownInit1: Int = #^OWN_INIT_1^#
// OWN_INIT_1: Begin completions
// OWN_INIT_1-NOT: ownInit1
func sync() {}
var ownInit2: () -> Void = { #^OWN_INIT_2^# }
// OWN_INIT_2: Begin completions
// OWN_INIT_2-NOT: ownInit2
var ownInit8: Int = "\(#^OWN_INIT_8^#)"
// OWN_INIT_8: Begin completions
// OWN_INIT_8-NOT: ownInit8
struct OwnInitTester {
var ownInit3: Int = #^OWN_INIT_3^#
// OWN_INIT_3: Begin completions
// OWN_INIT_3-NOT: ownInit3
var ownInit4: () -> Void = { #^OWN_INIT_4^# }
// OWN_INIT_4: Begin completions
// OWN_INIT_4-NOT: ownInit4
var ownInit9: String = "\(#^OWN_INIT_9^#)"
// OWN_INIT_9: Begin completions
// OWN_INIT_9-NOT: ownInit9
}
func ownInitTesting() {
var ownInit5: Int = #^OWN_INIT_5^#
// OWN_INIT_5: Begin completions
// OWN_INIT_5-NOT: ownInit5
var ownInit6: () -> Void = { #^OWN_INIT_6^# }
// OWN_INIT_6: Begin completions
// OWN_INIT_6-NOT: ownInit6
var ownInit10: String = "\(#^OWN_INIT_10^#)"
// OWN_INIT_10: Begin completions
// OWN_INIT_10-NOT: ownInit10
}
func ownInitTestingParam(ownInit11: Int = #^OWN_INIT_11^#) {
// OWN_INIT_11: Begin completions
// OWN_INIT_11-NOT: Decl[LocalVar]{{.*}}ownInit11
}
func ownInitTestingParamInterp(ownInit12: String = "\(#^OWN_INIT_12^#)") {
// OWN_INIT_12: Begin completions
// OWN_INIT_12-NOT: Decl[LocalVar]{{.*}}ownInit12
}
func ownInitTestingShadow(ownInit7: Int) {
var ownInit7: Int = #^OWN_INIT_7^#
// OWN_INIT_7: Begin completions
// OWN_INIT_7: Decl[LocalVar]/Local/TypeRelation[Convertible]: ownInit7[#Int#];
}
var inAccessor1: Int {
get { #^OWN_ACCESSOR_1^# }
// OWN_ACCESSOR_1: Begin completions
// OWN_ACCESSOR_1: Decl[GlobalVar]/CurrModule/NotRecommended/TypeRelation[Convertible]: inAccessor1[#Int#];
set { #^OWN_ACCESSOR_2^# }
// OWN_ACCESSOR_2: Begin completions
// OWN_ACCESSOR_2: Decl[GlobalVar]/CurrModule: inAccessor1[#Int#];
}
var inAccessor2: Int = 1 {
didSet { #^OWN_ACCESSOR_3^# }
// OWN_ACCESSOR_3: Begin completions
// OWN_ACCESSOR_3: Decl[GlobalVar]/CurrModule: inAccessor2[#Int#];
willSet { #^OWN_ACCESSOR_4?check=OWN_ACCESSOR_3^# }
}
class InAccessorTest {
var inAccessor3: Int {
get { #^OWN_ACCESSOR_5^# }
// OWN_ACCESSOR_5: Begin completions
// OWN_ACCESSOR_5: Decl[InstanceVar]/CurrNominal/NotRecommended/TypeRelation[Convertible]: inAccessor3[#Int#];
set { #^OWN_ACCESSOR_6^# }
// OWN_ACCESSOR_6: Begin completions
// OWN_ACCESSOR_6: Decl[InstanceVar]/CurrNominal: inAccessor3[#Int#];
}
var inAccessor4: Int = 1 {
didSet { #^OWN_ACCESSOR_7^# }
// OWN_ACCESSOR_7: Begin completions
// OWN_ACCESSOR_7: Decl[InstanceVar]/CurrNominal: inAccessor4[#Int#];
willSet { #^OWN_ACCESSOR_8?check=OWN_ACCESSOR_7^# }
}
}
func inAccessorTest() {
var inAccessor5: Int {
get { #^OWN_ACCESSOR_9^# }
// OWN_ACCESSOR_9: Begin completions
// OWN_ACCESSOR_9: Decl[LocalVar]/Local/NotRecommended/TypeRelation[Convertible]: inAccessor5[#Int#];
set { #^OWN_ACCESSOR_10^# }
// OWN_ACCESSOR_10: Begin completions
// OWN_ACCESSOR_10: Decl[LocalVar]/Local: inAccessor5[#Int#];
}
var inAccessor6: Int = 1 {
didSet { #^OWN_ACCESSOR_11^# }
// OWN_ACCESSOR_11: Begin completions
// OWN_ACCESSOR_11: Decl[LocalVar]/Local: inAccessor6[#Int#];
willSet { #^OWN_ACCESSOR_12?check=OWN_ACCESSOR_11^# }
}
}
class InAccessorTestQualified {
var inAccessorProp: Int {
get {
let _ = self.#^OWN_ACCESSOR_13^#
// OWN_ACCESSOR_13: Begin completions
// OWN_ACCESSOR_13: Decl[InstanceVar]/CurrNominal: inAccessorProp[#Int#];
let _ = \InAccessorTestQualified.#^OWN_ACCESSOR_14?check=OWN_ACCESSOR_13^#
}
set {
let _ = self.#^OWN_ACCESSOR_15?check=OWN_ACCESSOR_13^#
let _ = \InAccessorTestQualified.#^OWN_ACCESSOR_16?check=OWN_ACCESSOR_13^#
}
}
}
| 36.72605 | 125 | 0.691882 |
8fe80a2a865b1bdd206b4aed0c2cf533ced8fdaf | 8,621 | //
// Notifications.swift
// Capable
//
// Created by Christoph Wendt on 30.03.18.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#endif
#if os(watchOS)
import WatchKit
#endif
class Notifications: NotificationsProtocol {
var statusesModule: StatusesProtocol
var notificationCenter: NotificationCenter
required init(statusesModule: StatusesProtocol, notificationCenter: NotificationCenter = NotificationCenter.default) {
self.statusesModule = statusesModule
self.notificationCenter = notificationCenter
}
func postNotification(withFeature feature: CapableFeature, statusString: String) {
fatalError("Capable.Notifications.postNotification: Function needs to be implemented by its subclass.")
}
}
// MARK: Register Observers
extension Notifications {
// swiftlint:disable cyclomatic_complexity
func enableNotifications(forFeatures features: [CapableFeature]) {
#if os(iOS)
if features.contains(.assistiveTouch) {
addObserver(for: .UIAccessibilityAssistiveTouchStatusDidChange, selector: #selector(self.assistiveTouchStatusChanged))
}
if features.contains(.darkerSystemColors) {
addObserver(for: .UIAccessibilityDarkerSystemColorsStatusDidChange, selector: #selector(self.darkerSystemColorsStatusChanged))
}
if features.contains(.guidedAccess) {
addObserver(for: .UIAccessibilityGuidedAccessStatusDidChange, selector: #selector(self.guidedAccessStatusChanged))
}
if features.contains(.largerText) {
addObserver(for: .UIContentSizeCategoryDidChange, selector: #selector(self.largerTextStatusChanged))
}
if features.contains(.shakeToUndo) {
addObserver(for: .UIAccessibilityShakeToUndoDidChange, selector: #selector(self.shakeToUndoStatusChanged))
}
if features.contains(.speakScreen) {
addObserver(for: .UIAccessibilitySpeakScreenStatusDidChange, selector: #selector(self.speakScreenStatusChanged))
}
if features.contains(.speakSelection) {
addObserver(for: .UIAccessibilitySpeakSelectionStatusDidChange, selector: #selector(self.speakSelectionStatusChanged))
}
#endif
#if os(iOS) || os(tvOS)
if features.contains(.boldText) {
addObserver(for: .UIAccessibilityBoldTextStatusDidChange, selector: #selector(self.boldTextStatusChanged))
}
if features.contains(.closedCaptioning) {
addObserver(for: .UIAccessibilityClosedCaptioningStatusDidChange, selector: #selector(self.closedCaptioningStatusChanged))
}
if features.contains(.grayscale) {
addObserver(for: .UIAccessibilityGrayscaleStatusDidChange, selector: #selector(self.grayscaleStatusChanged))
}
if features.contains(.invertColors) {
addObserver(for: .UIAccessibilityInvertColorsStatusDidChange, selector: #selector(self.invertColorsStatusChanged))
}
if features.contains(.monoAudio) {
addObserver(for: .UIAccessibilityMonoAudioStatusDidChange, selector: #selector(self.monoAudioStatusChanged))
}
if features.contains(.switchControl) {
addObserver(for: .UIAccessibilitySwitchControlStatusDidChange, selector: #selector(self.switchControlStatusChanged))
}
if features.contains(.reduceMotion) {
addObserver(for: .UIAccessibilityReduceMotionStatusDidChange, selector: #selector(self.reduceMotionStatusChanged))
}
if features.contains(.reduceTransparency) {
addObserver(for: .UIAccessibilityReduceTransparencyStatusDidChange, selector: #selector(self.reduceTransparencyStatusChanged))
}
if features.contains(.voiceOver) {
if #available(iOS 11.0, tvOS 11.0, *) {
addObserver(for: .UIAccessibilityVoiceOverStatusDidChange, selector: #selector(self.voiceOverStatusChanged))
} else {
addObserver(for: Notification.Name(UIAccessibilityVoiceOverStatusChanged), selector: #selector(self.voiceOverStatusChanged))
}
}
#endif
#if os(watchOS)
if #available(watchOS 4.0, *), features.contains(.reduceMotion) {
addObserver(for: .WKAccessibilityReduceMotionStatusDidChange, selector: #selector(self.reduceMotionStatusChanged))
}
if features.contains(.voiceOver) {
addObserver(for: NSNotification.Name(rawValue: WKAccessibilityVoiceOverStatusChanged), selector: #selector(self.voiceOverStatusChanged))
}
#endif
}
// swiftlint:enable cyclomatic_complexity
}
// MARK: Handle notifications
extension Notifications {
func addObserver(for notificationName: NSNotification.Name, selector: Selector) {
self.notificationCenter.addObserver(
self,
selector: selector,
name: notificationName,
object: nil)
}
#if os(iOS)
@objc func assistiveTouchStatusChanged(notification: NSNotification) {
postNotification(withFeature: .assistiveTouch, statusString: self.statusesModule.isAssistiveTouchEnabled.statusString)
}
@objc func darkerSystemColorsStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .darkerSystemColors, statusString: self.statusesModule.isDarkerSystemColorsEnabled.statusString)
}
@objc func guidedAccessStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .guidedAccess, statusString: self.statusesModule.isGuidedAccessEnabled.statusString)
}
@objc func largerTextStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .largerText, statusString: self.statusesModule.largerTextCatagory.stringValue)
}
@objc func shakeToUndoStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .shakeToUndo, statusString: self.statusesModule.isShakeToUndoEnabled.statusString)
}
@objc func speakScreenStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .speakScreen, statusString: self.statusesModule.isSpeakScreenEnabled.statusString)
}
@objc func speakSelectionStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .speakSelection, statusString: self.statusesModule.isSpeakSelectionEnabled.statusString)
}
#endif
#if os(iOS) || os(tvOS)
@objc func boldTextStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .boldText, statusString: self.statusesModule.isBoldTextEnabled.statusString)
}
@objc func closedCaptioningStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .closedCaptioning, statusString: self.statusesModule.isClosedCaptioningEnabled.statusString)
}
@objc func grayscaleStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .grayscale, statusString: self.statusesModule.isGrayscaleEnabled.statusString)
}
@objc func invertColorsStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .invertColors, statusString: self.statusesModule.isInvertColorsEnabled.statusString)
}
@objc func monoAudioStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .monoAudio, statusString: self.statusesModule.isMonoAudioEnabled.statusString)
}
@objc func switchControlStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .switchControl, statusString: self.statusesModule.isSwitchControlEnabled.statusString)
}
@objc func reduceTransparencyStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .reduceTransparency, statusString: self.statusesModule.isReduceTransparencyEnabled.statusString)
}
#endif
@objc func reduceMotionStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .reduceMotion, statusString: self.statusesModule.isReduceMotionEnabled.statusString)
}
@objc func voiceOverStatusChanged(notification: NSNotification) {
self.postNotification(withFeature: .voiceOver, statusString: self.statusesModule.isVoiceOverEnabled.statusString)
}
}
| 46.6 | 152 | 0.717666 |
231b74f392fdc267c7d5ef1a775b88ebb66d8d7e | 656 | //
// Dictionary+HttpBodyConvertible.swift
// NetworkLayer
//
// Created by Ihor Yarovyi on 11/18/21.
//
import Foundation
extension Dictionary: HttpBodyConvertible where Key == String, Value == CustomStringConvertible {
public func buildHttpBodyPart(boundary: String) -> Data {
let httpBody = NSMutableData()
forEach { (name, value) in
httpBody.appendString("--\(boundary)\r\n")
httpBody.appendString("Content-Disposition: form-data; name=\"\(name)\"\r\n\r\n")
httpBody.appendString(value.description)
httpBody.appendString("\r\n")
}
return httpBody as Data
}
}
| 29.818182 | 97 | 0.644817 |
de8cf7dac450aec0adb39724d9129432e321b478 | 10,532 | //
// PeripheralManagerViewController.swift
// BlueCapUI
//
// Created by Troy Stribling on 6/5/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
import CoreBluetooth
class PeripheralManagerViewController : UITableViewController, UITextFieldDelegate {
@IBOutlet var nameTextField : UITextField!
@IBOutlet var advertiseSwitch : UISwitch!
@IBOutlet var advertisedBeaconSwitch : UISwitch!
@IBOutlet var advertisedBeaconLabel : UILabel!
@IBOutlet var advertisedServicesLabel : UILabel!
@IBOutlet var servicesLabel : UILabel!
@IBOutlet var beaconLabel : UILabel!
struct MainStoryboard {
static let peripheralManagerServicesSegue = "PeripheralManagerServices"
static let peripheralManagerAdvertisedServicesSegue = "PeripheralManagerAdvertisedServices"
static let peripheralManagerBeaconsSegue = "PeripheralManagerBeacons"
}
var peripheral : String?
override func viewDidLoad() {
super.viewDidLoad()
if let peripheral = self.peripheral {
self.nameTextField.text = peripheral
}
}
override func viewWillAppear(animated:Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "Peripheral"
if let peripheral = self.peripheral {
if let advertisedBeacon = PeripheralStore.getAdvertisedBeacon(peripheral) {
self.advertisedBeaconLabel.text = advertisedBeacon
} else {
self.advertisedBeaconLabel.text = "None"
}
PeripheralManager.sharedInstance.powerOn().onSuccess {
self.setPeripheralManagerServices()
}
self.setUIState()
}
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil)
}
override func viewWillDisappear(animated: Bool) {
self.navigationItem.title = ""
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) {
if segue.identifier == MainStoryboard.peripheralManagerServicesSegue {
let viewController = segue.destinationViewController as! PeripheralManagerServicesViewController
viewController.peripheral = self.peripheral
viewController.peripheralManagerViewController = self
} else if segue.identifier == MainStoryboard.peripheralManagerAdvertisedServicesSegue {
let viewController = segue.destinationViewController as! PeripheralManagerAdvertisedServicesViewController
viewController.peripheral = self.peripheral
viewController.peripheralManagerViewController = self
} else if segue.identifier == MainStoryboard.peripheralManagerBeaconsSegue {
let viewController = segue.destinationViewController as! PeripheralManagerBeaconsViewController
viewController.peripheral = self.peripheral
viewController.peripheralManagerViewController = self
}
}
override func shouldPerformSegueWithIdentifier(identifier:String?, sender:AnyObject?) -> Bool {
if let peripheral = self.peripheral {
if let identifier = identifier {
if identifier != MainStoryboard.peripheralManagerServicesSegue {
return !PeripheralManager.sharedInstance.isAdvertising
} else {
return true
}
} else {
return true
}
} else {
return false
}
}
@IBAction func toggleAdvertise(sender:AnyObject) {
let manager = PeripheralManager.sharedInstance
if manager.isAdvertising {
manager.stopAdvertising().onSuccess {
self.setUIState()
}
} else {
if let peripheral = self.peripheral {
let afterAdvertisingStarted = {
self.setUIState()
}
let afterAdvertisingStartFailed:(error:NSError)->() = {(error) in
self.setUIState()
self.presentViewController(UIAlertController.alertOnError(error), animated:true, completion:nil)
}
let advertisedServices = PeripheralStore.getAdvertisedPeripheralServicesForPeripheral(peripheral)
if PeripheralStore.getBeaconEnabled(peripheral) {
if let name = self.advertisedBeaconLabel.text {
if let uuid = PeripheralStore.getBeacon(name) {
let beaconConfig = PeripheralStore.getBeaconConfig(name)
let beaconRegion = BeaconRegion(proximityUUID:uuid, identifier:name, major:beaconConfig[1], minor:beaconConfig[0])
let future = manager.startAdvertising(beaconRegion)
future.onSuccess(afterAdvertisingStarted)
future.onFailure(afterAdvertisingStartFailed)
}
}
} else if advertisedServices.count > 0 {
let future = manager.startAdvertising(peripheral, uuids:advertisedServices)
future.onSuccess(afterAdvertisingStarted)
future.onFailure(afterAdvertisingStartFailed)
} else {
let future = manager.startAdvertising(peripheral)
future.onSuccess(afterAdvertisingStarted)
future.onFailure(afterAdvertisingStartFailed)
}
}
}
}
@IBAction func toggleBeacon(sender:AnyObject) {
if let peripheral = self.peripheral {
if PeripheralStore.getBeaconEnabled(peripheral) {
PeripheralStore.setBeaconEnabled(peripheral, enabled:false)
} else {
if let name = self.advertisedBeaconLabel.text {
if let uuid = PeripheralStore.getBeacon(name) {
PeripheralStore.setBeaconEnabled(peripheral, enabled:true)
} else {
self.presentViewController(UIAlertController.alertWithMessage("iBeacon is invalid"), animated:true, completion:nil)
}
}
}
self.setUIState()
}
}
func setPeripheralManagerServices() {
if !PeripheralManager.sharedInstance.isAdvertising {
let future = PeripheralManager.sharedInstance.removeAllServices()
future.onSuccess {
if let peripheral = self.peripheral {
self.loadPeripheralServicesFromConfig()
} else {
self.setUIState()
}
}
future.onFailure {error in
self.presentViewController(UIAlertController.alertOnError(error), animated:true, completion:nil)
}
}
}
func loadPeripheralServicesFromConfig() {
if let peripheral = self.peripheral {
let peripheralManager = PeripheralManager.sharedInstance
let serviceUUIDs = PeripheralStore.getPeripheralServicesForPeripheral(peripheral)
let services = serviceUUIDs.reduce([MutableService]()){(services, uuid) in
if let serviceProfile = ProfileManager.sharedInstance.service[uuid] {
let service = MutableService(profile:serviceProfile)
service.characteristicsFromProfiles(serviceProfile.characteristics)
return services + [service]
} else {
return services
}
}
let future = peripheralManager.addServices(services)
future.onSuccess {
self.setUIState()
}
future.onFailure {(error) in
self.setUIState()
self.presentViewController(UIAlertController.alertOnError(error), animated:true, completion:nil)
}
}
}
func setUIState() {
if let peripheral = self.peripheral {
let peripheralManager = PeripheralManager.sharedInstance
self.advertisedBeaconSwitch.on = PeripheralStore.getBeaconEnabled(peripheral)
if peripheralManager.isAdvertising {
self.navigationItem.setHidesBackButton(true, animated:true)
self.advertiseSwitch.on = true
self.nameTextField.enabled = false
self.beaconLabel.textColor = UIColor(red:0.7, green:0.7, blue:0.7, alpha:1.0)
self.advertisedServicesLabel.textColor = UIColor(red:0.7, green:0.7, blue:0.7, alpha:1.0)
} else {
self.advertiseSwitch.on = false
self.beaconLabel.textColor = UIColor.blackColor()
self.advertisedServicesLabel.textColor = UIColor.blackColor()
self.navigationItem.setHidesBackButton(false, animated:true)
self.nameTextField.enabled = true
}
}
}
func didResignActive() {
Logger.debug()
}
func didBecomeActive() {
Logger.debug()
}
// UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.nameTextField.resignFirstResponder()
if let enteredName = self.nameTextField.text {
if !enteredName.isEmpty {
if let oldname = self.peripheral {
let services = PeripheralStore.getPeripheralServicesForPeripheral(oldname)
PeripheralStore.removePeripheral(oldname)
PeripheralStore.addPeripheralName(enteredName)
PeripheralStore.addPeripheralServices(enteredName, services:services)
self.peripheral = enteredName
} else {
self.peripheral = enteredName
PeripheralStore.addPeripheralName(enteredName)
}
}
self.setUIState()
}
return true
}
}
| 43.341564 | 144 | 0.612419 |
1c43c368bb84c14e9a67f062c6142746d0d426fd | 319 | //
// SECropError.swift
// CropView
//
// Created by Никита Разумный on 2/3/18.
//
import UIKit
public enum SECropError: Error {
case missingSuperview
case missingImageOnImageView
case invalidNumberOfCorners
case nonConvexRect
case missingImageWhileCropping
case unknown
case noImage
}
| 16.789474 | 41 | 0.724138 |
0addc3af3021aea740255ccc63f6789cb3b9579c | 285 | //
// Statement.swift
// Billbook-Swfit (iOS)
//
// Created by Chao Feng on 12/28/20.
//
import Foundation
struct Statement: Identifiable, Decodable {
let id: Int
let username: String
let balance: String
let notes: String
let createdAt: String
let updatedAt: String
}
| 15.833333 | 43 | 0.694737 |
26ce0421a74b0aa521775a41f1a2ba683c628c9f | 20,159 | //
// RSSelectionMenuController.swift
// RSSelectionMenu
//
// Copyright (c) 2019 Rushi Sangani
//
// 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
/// RSSelectionMenuController
open class RSSelectionMenu<T: Equatable>: UIViewController, UIPopoverPresentationControllerDelegate, UIGestureRecognizerDelegate {
// MARK: - Views
public var tableView: RSSelectionTableView<T>?
/// SearchBar
public var searchBar: UISearchBar? {
return tableView?.searchControllerDelegate?.searchBar
}
/// NavigationBar
public var navigationBar: UINavigationBar? {
return self.navigationController?.navigationBar
}
// MARK: - Properties
/// dismiss: for Single selection only
public var dismissAutomatically: Bool = true
/// Barbuttons titles
public var leftBarButtonTitle: String?
public var rightBarButtonTitle: String?
/// cell selection style
public var cellSelectionStyle: CellSelectionStyle = .tickmark {
didSet {
self.tableView?.setCellSelectionStyle(cellSelectionStyle)
}
}
/// maximum selection limit
public var maxSelectionLimit: UInt? = nil {
didSet {
self.tableView?.selectionDelegate?.maxSelectedLimit = maxSelectionLimit
}
}
/// Selection menu willAppear handler
public var onWillAppear:(() -> ())?
/// Selection menu dismissal handler
public var onDismiss:((_ selectedItems: DataSource<T>) -> ())?
/// RightBarButton Tap handler - Only for Multiple Selection & Push, Present - Styles
/// Note: This is override the default dismiss behaviour of the menu.
/// onDismiss will not be called if this is implemeted. (dismiss manually in this completion block)
public var onRightBarButtonTapped:((_ selectedItems: DataSource<T>) -> ())?
// MARK: - Private
/// store reference view controller
fileprivate weak var parentController: UIViewController?
/// presentation style
fileprivate var menuPresentationStyle: PresentationStyle = .present
/// navigationbar theme
fileprivate var navigationBarTheme: NavigationBarTheme?
/// backgroundView
fileprivate var backgroundView = UIView()
// MARK: - Init
convenience public init(
dataSource: DataSource<T>,
tableViewStyle: UITableView.Style = .plain,
cellConfiguration configuration: @escaping UITableViewCellConfiguration<T>) {
self.init(
selectionStyle: .single,
dataSource: dataSource,
tableViewStyle: tableViewStyle,
cellConfiguration: configuration
)
}
convenience public init(
selectionStyle: SelectionStyle,
dataSource: DataSource<T>,
tableViewStyle: UITableView.Style = .plain,
cellConfiguration configuration: @escaping UITableViewCellConfiguration<T>) {
self.init(
selectionStyle: selectionStyle,
dataSource: dataSource,
tableViewStyle: tableViewStyle,
cellType: .basic,
cellConfiguration: configuration
)
}
convenience public init(
selectionStyle: SelectionStyle,
dataSource: DataSource<T>,
tableViewStyle: UITableView.Style = .plain,
cellType: CellType,
cellConfiguration configuration: @escaping UITableViewCellConfiguration<T>) {
self.init()
// data source
let selectionDataSource = RSSelectionMenuDataSource<T>(
dataSource: dataSource,
forCellType: cellType,
cellConfiguration: configuration
)
// delegate
let selectionDelegate = RSSelectionMenuDelegate<T>(selectedItems: [])
// initilize tableview
self.tableView = RSSelectionTableView<T>(
selectionStyle: selectionStyle,
tableViewStyle: tableViewStyle,
cellType: cellType,
dataSource: selectionDataSource,
delegate: selectionDelegate,
from: self
)
}
// MARK: - Life Cycle
override open func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupLayout()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView?.reload()
if let handler = onWillAppear { handler() }
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
view.endEditing(true)
/// on dimiss not called in iPad for multi select popover
if tableView?.selectionStyle == .multiple, popoverPresentationController != nil {
self.menuWillDismiss()
}
}
// MARK: - Setup Views
fileprivate func setupViews() {
backgroundView.backgroundColor = UIColor.clear
if case .formSheet = menuPresentationStyle {
backgroundView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
addTapGesture()
}
backgroundView.addSubview(tableView!)
view.addSubview(backgroundView)
// rightBarButton
if showRightBarButton() {
setRightBarButton()
}
// leftBarButton
if showLeftBarButton() {
setLeftBarButton()
}
}
// MARK: - Setup Layout
fileprivate func setupLayout() {
if let frame = parentController?.view.bounds {
self.view.frame = frame
}
// navigation bar theme
setNavigationBarTheme()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setTableViewFrame()
}
/// tableView frame
fileprivate func setTableViewFrame() {
let window = UIApplication.shared.delegate?.window
// change border style for formsheet
if case let .formSheet(size) = menuPresentationStyle {
tableView?.layer.cornerRadius = 8
self.backgroundView.frame = (window??.bounds)!
var tableViewSize = CGSize.zero
// set size directly if provided
if let size = size {
tableViewSize = size
}
else {
// set size according to device and orientation
if UIDevice.current.userInterfaceIdiom == .phone {
if UIApplication.shared.statusBarOrientation == .portrait {
tableViewSize = CGSize(width: backgroundView.frame.size.width - 80, height: backgroundView.frame.size.height - 260)
}else {
tableViewSize = CGSize(width: backgroundView.frame.size.width - 200, height: backgroundView.frame.size.height - 100)
}
}else {
tableViewSize = CGSize(width: backgroundView.frame.size.width - 300, height: backgroundView.frame.size.height - 400)
}
}
self.tableView?.frame.size = tableViewSize
self.tableView?.center = self.backgroundView.center
}else {
self.backgroundView.frame = self.view.bounds
self.tableView?.frame = backgroundView.frame
}
}
/// Tap gesture
fileprivate func addTapGesture() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onBackgroundTapped(sender:)))
tapGesture.numberOfTapsRequired = 1
tapGesture.delegate = self
backgroundView.addGestureRecognizer(tapGesture)
}
@objc func onBackgroundTapped(sender: UITapGestureRecognizer){
self.dismiss()
}
// MARK: - Bar Buttons
/// left bar button
fileprivate func setLeftBarButton() {
let title = (self.leftBarButtonTitle != nil) ? self.leftBarButtonTitle! : cancelButtonTitle
let leftBarButton = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(leftBarButtonTapped))
navigationItem.leftBarButtonItem = leftBarButton
}
/// Right bar button
fileprivate func setRightBarButton() {
let title = (self.rightBarButtonTitle != nil) ? self.rightBarButtonTitle! : doneButtonTitle
let rightBarButton = UIBarButtonItem(title: title, style: .done, target: self, action: #selector(rightBarButtonTapped))
navigationItem.rightBarButtonItem = rightBarButton
}
@objc func leftBarButtonTapped() {
self.dismiss()
}
@objc func rightBarButtonTapped() {
if let rightButtonHandler = onRightBarButtonTapped {
rightButtonHandler(self.tableView?.selectionDelegate?.selectedItems ?? [])
return
}
self.dismiss()
}
// MARK: - UIPopoverPresentationControllerDelegate
public func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
public func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
let shouldDismiss = !showRightBarButton()
if shouldDismiss {
self.menuWillDismiss()
}
return shouldDismiss
}
// MARK: - UIGestureRecognizerDelegate
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if (touch.view?.isDescendant(of: tableView!))! { return false }
return true
}
}
// MARK:- Public
extension RSSelectionMenu {
/// Set all items and selection event
public func setAllSelectedItems(items: DataSource<T>) {
self.tableView?.setAllSelectedItems(items: items)
}
/// Set selected items and selection event
public func setSelectedItems(items: DataSource<T>, maxSelected: UInt? = nil, onDidSelectRow delegate: @escaping UITableViewCellSelection<T>) {
let maxLimit = maxSelected ?? maxSelectionLimit
self.tableView?.setSelectedItems(items: items, maxSelected: maxLimit, onDidSelectRow: delegate)
}
/// First row type and selection
public func addFirstRowAs(rowType: FirstRowType, showSelected: Bool, onDidSelectFirstRow completion: @escaping FirstRowSelection) {
self.tableView?.addFirstRowAs(rowType: rowType, showSelected: showSelected, onDidSelectFirstRow: completion)
}
/// Searchbar
public func showSearchBar(onTextDidSearch completion: @escaping UISearchBarResult<T>) {
self.showSearchBar(withPlaceHolder: defaultPlaceHolder, barTintColor: defaultSearchBarTintColor, onTextDidSearch: completion)
}
public func showSearchBar(withPlaceHolder: String, barTintColor: UIColor, onTextDidSearch completion: @escaping UISearchBarResult<T>) {
self.tableView?.addSearchBar(placeHolder: withPlaceHolder, barTintColor: barTintColor, completion: completion)
}
/// Navigationbar title and color
public func setNavigationBar(title: String, attributes:[NSAttributedString.Key: Any]? = nil, barTintColor: UIColor? = nil, tintColor: UIColor? = nil) {
self.navigationBarTheme = NavigationBarTheme(title: title, titleAttributes: attributes, tintColor: tintColor, barTintColor: barTintColor)
}
/// Right Barbutton title and action handler
public func setRightBarButton(title: String, handler: @escaping (DataSource<T>) -> ()) {
self.rightBarButtonTitle = title
self.onRightBarButtonTapped = handler
}
/// Empty Data Label
public func showEmptyDataLabel(text: String = defaultEmptyDataString, attributes: [NSAttributedString.Key: Any]? = nil) {
self.tableView?.showEmptyDataLabel(text: text, attributes: attributes)
}
/// Show
public func show(from: UIViewController) {
self.show(style: .present, from: from)
}
public func show(style: PresentationStyle, from: UIViewController) {
self.showMenu(with: style, from: from)
}
/// dismiss
public func dismiss(animated: Bool? = true) {
DispatchQueue.main.async { [weak self] in
// perform on dimiss operations
self?.menuWillDismiss()
switch self?.menuPresentationStyle {
case .push?:
self?.navigationController?.popViewController(animated: animated!)
case .present?, .popover?, .formSheet?, .alert?, .actionSheet?, .bottomSheet?:
self?.dismiss(animated: animated!, completion: nil)
case .none:
break
}
}
}
}
//MARK:- Private
extension RSSelectionMenu {
// check if show rightBarButton
fileprivate func showRightBarButton() -> Bool {
switch menuPresentationStyle {
case .present, .push:
return (tableView?.selectionStyle == .multiple || !self.dismissAutomatically)
default:
return false
}
}
// check if show leftBarButton
fileprivate func showLeftBarButton() -> Bool {
if case .present = menuPresentationStyle {
return tableView?.selectionStyle == .single && self.dismissAutomatically
}
return false
}
// perform operation on dismiss
fileprivate func menuWillDismiss() {
// dismiss search
if let searchBar = self.tableView?.searchControllerDelegate?.searchBar {
if searchBar.isFirstResponder { searchBar.resignFirstResponder() }
}
// on menu dismiss
if let dismissHandler = self.onDismiss {
dismissHandler(self.tableView?.selectionDelegate?.selectedItems ?? [])
}
}
// show
fileprivate func showMenu(with: PresentationStyle, from: UIViewController) {
parentController = from
menuPresentationStyle = with
if case .push = with {
from.navigationController?.pushViewController(self, animated: true)
return
}
var tobePresentController: UIViewController = self
if case .present = with {
tobePresentController = UINavigationController(rootViewController: self)
}
else if case let .popover(sourceView, size, arrowDirection, hideNavBar) = with {
tobePresentController = UINavigationController(rootViewController: self)
(tobePresentController as! UINavigationController).setNavigationBarHidden(hideNavBar, animated: false)
tobePresentController.modalPresentationStyle = .popover
if size != nil { tobePresentController.preferredContentSize = size! }
let popover = tobePresentController.popoverPresentationController!
popover.delegate = self
popover.permittedArrowDirections = arrowDirection
popover.sourceView = sourceView
popover.sourceRect = sourceView.bounds
}
else if case .formSheet = with {
tobePresentController.modalPresentationStyle = .overCurrentContext
tobePresentController.modalTransitionStyle = .crossDissolve
}
else if case let .alert(title, action, height) = with {
tobePresentController = getAlertViewController(style: .alert, title: title, action: action, height: height)
tobePresentController.setValue(self, forKey: contentViewController)
}
else if case let .actionSheet(title, action, height) = with {
tobePresentController = getAlertViewController(style: .actionSheet, title: title, action: action, height: height)
tobePresentController.setValue(self, forKey: contentViewController)
// present as popover for iPad
if let popoverController = tobePresentController.popoverPresentationController {
popoverController.sourceView = from.view
popoverController.permittedArrowDirections = []
popoverController.sourceRect = CGRect(x: from.view.bounds.midX, y: from.view.bounds.midY, width: 0, height: 0)
}
}
else if case let .bottomSheet(barButton, height) = with {
tobePresentController = getAlertViewController(style: .actionSheet, title: nil, action: nil, height: height)
tobePresentController.setValue(self, forKey: contentViewController)
// present as popover for iPad
if let popoverController = tobePresentController.popoverPresentationController {
popoverController.barButtonItem = barButton
popoverController.permittedArrowDirections = .any
}
}
from.present(tobePresentController, animated: true, completion: nil)
}
// get alert controller
fileprivate func getAlertViewController(style: UIAlertController.Style, title: String?, action: String?, height: Double?) -> UIAlertController {
let alertController = UIAlertController(title: title, message: nil, preferredStyle: style)
let actionTitle = action ?? doneButtonTitle
let doneAction = UIAlertAction(title: actionTitle, style: .default) { [weak self] (doneButton) in
self?.menuWillDismiss()
}
// add done action
if (tableView?.selectionStyle == .multiple || !self.dismissAutomatically) {
alertController.addAction(doneAction)
}
let viewHeight = height ?? 350
alertController.preferredContentSize.height = CGFloat(viewHeight)
self.preferredContentSize.height = alertController.preferredContentSize.height
return alertController
}
// navigation bar
fileprivate func setNavigationBarTheme() {
guard let navigationBar = self.navigationBar else { return }
guard let theme = self.navigationBarTheme else {
// hide navigationbar for popover, if no title present
if case .popover = self.menuPresentationStyle {
navigationBar.isHidden = true
}
// check for present style
else if case .present = self.menuPresentationStyle, let parentNavigationBar = self.parentController?.navigationController?.navigationBar {
navigationBar.titleTextAttributes = parentNavigationBar.titleTextAttributes
navigationBar.barTintColor = parentNavigationBar.barTintColor
navigationBar.tintColor = parentNavigationBar.tintColor
}
return
}
navigationItem.title = theme.title
navigationBar.titleTextAttributes = theme.titleAttributes
navigationBar.barTintColor = theme.barTintColor
navigationBar.tintColor = theme.tintColor
}
}
| 37.892857 | 155 | 0.645022 |
33b7a0e944c86a1ae80717206985c67bf0205a99 | 572 | //
// TestTryCatchViewController.swift
// Neves
//
// Created by 周健平 on 2021/2/17.
//
import UIKit
class TestTryCatchViewController: TestBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
var ooo = 3
do {
JPrint("111")
ooo = try abc(true)
JPrint("222")
} catch {
JPrint("错了")
}
JPrint("333 \(ooo)")
}
func abc(_ isThrow: Bool) throws -> Int {
if isThrow {
throw NSError()
}
return 5
}
}
| 16.823529 | 58 | 0.491259 |
3ac03b6077c3f616fae88d28549f5c246db08fd3 | 12,577 | //
// AssociatingPackageInstallerTests.swift
// KeymanEngineTests
//
// Created by Joshua Horton on 8/6/20.
// Copyright © 2020 SIL International. All rights reserved.
//
import XCTest
@testable import KeymanEngine
class AssociatingPackageInstallerTests: XCTestCase {
var mockedURLSession: TestUtils.Downloading.URLSessionMock!
var downloadManager: ResourceDownloadManager!
let mockedSearchCallback: LanguagePickAssociator.AssociationSearcher = { lgCodes, callback in
var searchResult: [String: (KeymanPackage.Key, URL)?] = [:]
// We aren't downloading these models, so a placeholder URL is fine.
let placeholderURL = URL.init(string: "http://place.holder.com")!
lgCodes.forEach { lgCode in
switch lgCode {
case "en":
searchResult["en"] = (TestUtils.Packages.Keys.nrc_en_mtnt, placeholderURL)
case "str":
searchResult["str"] = (TestUtils.Packages.Keys.nrc_str_sencoten, placeholderURL)
default:
searchResult[lgCode] = nil
}
}
callback(searchResult)
}
override func setUp() {
// Resets resource directories for a clean slate.
// We'll be testing against actually-installed packages.
TestUtils.standardTearDown()
mockedURLSession = TestUtils.Downloading.URLSessionMock()
downloadManager = ResourceDownloadManager(session: mockedURLSession!, autoExecute: true)
}
override func tearDownWithError() throws {
TestUtils.standardTearDown()
let queueWasCleared = mockedURLSession!.queueIsEmpty
mockedURLSession = nil
if !queueWasCleared {
throw NSError(domain: "Keyman",
code: 4,
userInfo: [NSLocalizedDescriptionKey: "A test did not fully utilize its queued mock results!"])
}
}
func testKeyboardNoAssociations() throws {
guard let package = try ResourceFileManager.shared.prepareKMPInstall(from: TestUtils.Keyboards.silEuroLatinKMP) as? KeyboardKeymanPackage else {
XCTFail()
return
}
let startExpectation = XCTestExpectation()
let completeExpectation = XCTestExpectation()
let installer = AssociatingPackageInstaller(for: package,
defaultLanguageCode: "en",
downloadManager: downloadManager) { status in
if status == .starting {
startExpectation.fulfill()
} else if status == .complete {
completeExpectation.fulfill()
} else if status == .cancelled {
XCTFail()
}
}
installer.pickLanguages(withCodes: Set(["en"]))
wait(for: [startExpectation, completeExpectation], timeout: 5)
guard let userKeyboards = Storage.active.userDefaults.userKeyboards else {
XCTFail()
return
}
XCTAssertTrue(userKeyboards.contains { $0.fullID == TestUtils.Keyboards.sil_euro_latin.fullID })
XCTAssertNil(Storage.active.userDefaults.userLexicalModels)
XCTAssertEqual(ResourceFileManager.shared.installState(forPackage: TestUtils.Packages.Keys.sil_euro_latin), .installed)
XCTAssertEqual(ResourceFileManager.shared.installState(forPackage: TestUtils.Packages.Keys.nrc_en_mtnt), .none)
}
func testLexicalModelNoAssociations() throws {
guard let package = try ResourceFileManager.shared.prepareKMPInstall(from: TestUtils.LexicalModels.mtntKMP) as? LexicalModelKeymanPackage else {
XCTFail()
return
}
let startExpectation = XCTestExpectation()
let completeExpectation = XCTestExpectation()
let installer = AssociatingPackageInstaller(for: package,
defaultLanguageCode: "en",
downloadManager: downloadManager) { status in
if status == .starting {
startExpectation.fulfill()
} else if status == .complete {
completeExpectation.fulfill()
} else if status == .cancelled {
XCTFail()
}
}
installer.pickLanguages(withCodes: Set(["en"]))
wait(for: [startExpectation, completeExpectation], timeout: 5)
guard let userLexicalModels = Storage.active.userDefaults.userLexicalModels else {
XCTFail()
return
}
XCTAssertTrue(userLexicalModels.contains { $0.fullID == TestUtils.LexicalModels.mtnt.fullID })
XCTAssertNil(Storage.active.userDefaults.userKeyboards)
XCTAssertEqual(ResourceFileManager.shared.installState(forPackage: TestUtils.Packages.Keys.nrc_en_mtnt), .installed)
XCTAssertEqual(ResourceFileManager.shared.installState(forPackage: TestUtils.Packages.Keys.sil_euro_latin), .none)
}
func testKeyboardWithAssociatedLexicalModels() throws {
let mockedQuery = TestUtils.Downloading.MockResult(location: TestUtils.Queries.model_case_en, error: nil)
let mockedDownload = TestUtils.Downloading.MockResult(location: TestUtils.LexicalModels.mtntKMP, error: nil)
mockedURLSession.queueMockResult(.data(mockedQuery))
mockedURLSession.queueMockResult(.download(mockedDownload))
guard let package = try ResourceFileManager.shared.prepareKMPInstall(from: TestUtils.Keyboards.silEuroLatinKMP) as? KeyboardKeymanPackage else {
XCTFail()
return
}
let startExpectation = XCTestExpectation()
let completeExpectation = XCTestExpectation()
let installer = AssociatingPackageInstaller(for: package,
defaultLanguageCode: "en",
downloadManager: downloadManager,
withAssociators: [ .lexicalModels ]) { status in
if status == .starting {
startExpectation.fulfill()
} else if status == .complete {
completeExpectation.fulfill()
} else if status == .cancelled {
XCTFail()
}
}
installer.pickLanguages(withCodes: Set(["en"]))
wait(for: [startExpectation, completeExpectation], timeout: 5)
guard let userKeyboards = Storage.active.userDefaults.userKeyboards,
let userLexicalModels = Storage.active.userDefaults.userLexicalModels else {
XCTFail()
return
}
XCTAssertTrue(userKeyboards.contains { $0.fullID == TestUtils.Keyboards.sil_euro_latin.fullID })
XCTAssertTrue(userLexicalModels.contains { $0.fullID == TestUtils.LexicalModels.mtnt.fullID} )
XCTAssertEqual(ResourceFileManager.shared.installState(forPackage: TestUtils.Packages.Keys.sil_euro_latin), .installed)
XCTAssertEqual(ResourceFileManager.shared.installState(forPackage: TestUtils.Packages.Keys.nrc_en_mtnt), .installed)
}
func testCancellationNoAssociations() throws {
guard let package = try ResourceFileManager.shared.prepareKMPInstall(from: TestUtils.Keyboards.silEuroLatinKMP) as? KeyboardKeymanPackage else {
XCTFail()
return
}
let cancelExpectation = XCTestExpectation()
let installer = AssociatingPackageInstaller(for: package,
defaultLanguageCode: "en",
downloadManager: downloadManager) { status in
if status == .cancelled {
// When the user 'cancels' language selection, this installer should also
// signal cancellation.
cancelExpectation.fulfill()
} else {
XCTFail()
}
}
// A bit of white-box testing - sets up the closure framework
installer.initializeSynchronizationGroups()
// And the install closure, which we'll send a 'cancel' signal to.
let installClosure = installer.coreInstallationClosure()
installClosure(nil)
wait(for: [cancelExpectation], timeout: 5)
XCTAssertNil(Storage.active.userDefaults.userKeyboards)
XCTAssertNil(Storage.active.userDefaults.userLexicalModels)
}
func testCancellationWithAssociations() throws {
guard let package = try ResourceFileManager.shared.prepareKMPInstall(from: TestUtils.Keyboards.silEuroLatinKMP) as? KeyboardKeymanPackage else {
XCTFail()
return
}
// While the query should occur, the installation phase should never be reached.
// So, we don't mock the download.
let mockedQuery = TestUtils.Downloading.MockResult(location: TestUtils.Queries.model_case_en, error: nil)
mockedURLSession.queueMockResult(.data(mockedQuery))
let cancelExpectation = XCTestExpectation()
let installer = AssociatingPackageInstaller(for: package,
defaultLanguageCode: "en",
downloadManager: downloadManager,
withAssociators: [.lexicalModels]) { status in
if status == .cancelled {
// When the user 'cancels' language selection, this installer should also
// signal cancellation.
cancelExpectation.fulfill()
} else {
XCTFail()
}
}
// Heavier white-box testing this time.
installer.initializeSynchronizationGroups()
installer.constructAssociationPickers()
installer.associationQueriers?.forEach {
$0.pickerInitialized()
$0.selectLanguages(Set(["en"])) // calls the expected query
// And, since we're modeling cancellation...
$0.pickerDismissed()
}
// Finally, the install closure, which we'll send a 'cancel' signal to.
let installClosure = installer.coreInstallationClosure()
installClosure(nil)
wait(for: [cancelExpectation], timeout: 5)
XCTAssertNil(Storage.active.userDefaults.userKeyboards)
XCTAssertNil(Storage.active.userDefaults.userLexicalModels)
}
func testDeinitConstructiveCancellation() throws {
guard let package = try ResourceFileManager.shared.prepareKMPInstall(from: TestUtils.Keyboards.silEuroLatinKMP) as? KeyboardKeymanPackage else {
XCTFail()
return
}
// While the query should occur, the installation phase should never be reached.
// So, we don't mock the download.
let mockedQuery = TestUtils.Downloading.MockResult(location: TestUtils.Queries.model_case_en, error: nil)
let queryExpectation = XCTestExpectation()
mockedURLSession.queueMockResult(.data(mockedQuery), expectation: queryExpectation)
let cancelExpectation = XCTestExpectation()
do {
let installer = AssociatingPackageInstaller(for: package,
defaultLanguageCode: "en",
downloadManager: downloadManager,
withAssociators: [.lexicalModels]) { status in
// When the user 'cancels' language selection, this installer should also
// signal cancellation.
if status == .cancelled {
// First, wait to ensure that the standard query did launch.
// Otherwise, we might accidentally skip the mocked query!
self.wait(for: [queryExpectation], timeout: 4)
cancelExpectation.fulfill()
} else {
XCTFail()
}
}
// Heavier white-box testing this time.
installer.initializeSynchronizationGroups()
installer.constructAssociationPickers()
installer.associationQueriers?.forEach {
$0.pickerInitialized()
$0.selectLanguages(Set(["en"])) // calls the expected query
// De-init will trigger the 'dismiss' signal.
}
}
wait(for: [cancelExpectation], timeout: 5)
XCTAssertNil(Storage.active.userDefaults.userKeyboards)
XCTAssertNil(Storage.active.userDefaults.userLexicalModels)
}
func testDeinitUnstarted() throws {
guard let package = try ResourceFileManager.shared.prepareKMPInstall(from: TestUtils.Keyboards.silEuroLatinKMP) as? KeyboardKeymanPackage else {
XCTFail()
return
}
let cancelExpectation = XCTestExpectation()
do {
let _ = AssociatingPackageInstaller(for: package,
defaultLanguageCode: "en",
downloadManager: downloadManager,
withAssociators: [.lexicalModels]) { status in
// Since language-picking never began, no "cancelled" signal should occur.
if status == .cancelled {
cancelExpectation.fulfill()
} else {
XCTFail()
}
}
}
wait(for: [cancelExpectation], timeout: 1)
XCTAssertNil(Storage.active.userDefaults.userKeyboards)
XCTAssertNil(Storage.active.userDefaults.userLexicalModels)
}
}
| 38.227964 | 148 | 0.667727 |
46080e27395fec370ca6176886a461bcdb17cd52 | 907 | //
// AppDelegate.swift
// UILabel-LineBreak-Bug
//
// Created by Anisimov Aleksandr on 28.12.2021.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
}
| 34.884615 | 179 | 0.747519 |
398c6a7936f2d65bc114431575abd1f3ca0bee8b | 380 | //
// MKCoordinateRegion.swift
// NewDriver
//
// Created by Maxime Princelle on 18/02/2022.
//
import Foundation
import MapKit
extension MKCoordinateRegion {
static var defaultRegion: MKCoordinateRegion {
MKCoordinateRegion(center: CLLocationCoordinate2D.init(latitude: 29.726819, longitude: -95.393692), latitudinalMeters: 100, longitudinalMeters: 100)
}
}
| 23.75 | 156 | 0.75 |
287652376a69fee5a94c526a4375722280b8046c | 3,022 | //
// File.swift
//
//
// Created by Rob Jonson on 05/11/2021.
//
import Foundation
class PreferenceSync {
static var canSync:Bool = false {
didSet {
if !canSync && oldValue != canSync {
print("Zaphod unable to synchronise keys via iCloud")
}
}
}
struct Notif {
static let changed = NSNotification.Name.init(rawValue: "ZaphodPreferenceSyncChange")
}
@objc class func updateToiCloud(_ notificationObject: Notification?) {
let dict = UserDefaults.standard.dictionaryRepresentation()
dict.forEach { (key: String, value: Any) in
if let prefKey = ZPreference.Key(rawValue: key), prefKey.shouldSync {
NSUbiquitousKeyValueStore.default.set(value, forKey: key)
}
}
canSync = NSUbiquitousKeyValueStore.default.synchronize()
}
@objc class func updateFromiCloud(_ notificationObject: Notification?) {
let iCloudStore = NSUbiquitousKeyValueStore.default
let dict = iCloudStore.dictionaryRepresentation
var newSyncRequired = false
// prevent NSUserDefaultsDidChangeNotification from being posted while we update from iCloud
NotificationCenter.default.removeObserver(
self,
name: UserDefaults.didChangeNotification,
object: nil)
dict.forEach { (key: String, value: Any) in
if let prefKey = ZPreference.Key(rawValue: key), prefKey.shouldSync {
let needsSync = ZPreference.synchronisePref(object: value, for: prefKey)
if needsSync {
newSyncRequired = true
}
}
}
UserDefaults.standard.synchronize()
if newSyncRequired {
updateToiCloud(nil)
}
// enable NSUserDefaultsDidChangeNotification notifications again
NotificationCenter.default.addObserver(
self,
selector: #selector(updateToiCloud(_:)),
name: UserDefaults.didChangeNotification,
object: nil)
NotificationCenter.default.post(name: Notif.changed, object: nil)
}
class func start() {
NotificationCenter.default.addObserver(
self,
selector: #selector(updateFromiCloud(_:)),
name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
object: nil)
NotificationCenter.default.addObserver(
self,
selector: #selector(updateToiCloud(_:)),
name: UserDefaults.didChangeNotification,
object: nil)
}
class func dealloc() {
NotificationCenter.default.removeObserver(
self,
name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
object: nil)
NotificationCenter.default.removeObserver(
self,
name: UserDefaults.didChangeNotification,
object: nil)
}
}
| 29.339806 | 100 | 0.609861 |
7170b645c7f25fe4532daaa14733b27377cf8cd2 | 2,498 | import Foundation
public struct Triad {
public enum Error: Swift.Error {
case numberOfCards
case uniqueCards
case numberAttribute
case fillAttribute
case colorAttribute
case shapeAttribute
}
public static let cardsRequired: Int = 3
public static func triads(in cards: [Card]) -> [Triad] {
var triads = [Triad]()
guard cards.count >= Triad.cardsRequired else {
return triads
}
// [***_______] through [_______***]
for i in 0..<(cards.count - 2) {
for j in (i + 1)..<(cards.count - 1) {
for k in (j + 1)..<cards.count {
if let triad = try? Triad(cards[i], cards[j], cards[k]) {
triads.append(triad)
}
}
}
}
return triads
}
public static func validate(cards: [Card]) throws {
guard cards.count == Self.cardsRequired else {
throw Error.numberOfCards
}
guard Set(cards).count == Self.cardsRequired else {
throw Error.uniqueCards
}
let numbers = cards.map({ $0.number.rawValue })
guard [numbers.allEqual, numbers.allUnique].contains(true) else {
throw Error.numberAttribute
}
let fills = cards.map({ $0.fill.rawValue })
guard [fills.allEqual, fills.allUnique].contains(true) else {
throw Error.fillAttribute
}
let colors = cards.map({ $0.color.rawValue })
guard [colors.allEqual, colors.allUnique].contains(true) else {
throw Error.colorAttribute
}
let shapes = cards.map({ $0.shape.rawValue })
guard [shapes.allEqual, shapes.allUnique].contains(true) else {
throw Error.shapeAttribute
}
}
public let cards: [Card]
public var first: Card { cards[0] }
public var second: Card { cards[1] }
public var third: Card { cards[2] }
public init(_ cards: [Card]) throws {
try Self.validate(cards: cards)
self.cards = cards
}
public init(_ cards: Card...) throws {
try Self.validate(cards: cards)
self.cards = cards
}
}
private extension Array where Element == String {
var allEqual: Bool { Set(self).count == 1 }
var allUnique: Bool { Set(self).count == count }
}
| 28.386364 | 77 | 0.534428 |
0ad03a2dc146ff01415708c8cb4b9f63e7ec5d19 | 3,927 | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
import UIKit
import SwiftyDropbox
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if (TestData.fullDropboxAppKey.range(of:"<") != nil || TestData.teamMemberFileAccessAppKey.range(of:"<") != nil || TestData.teamMemberManagementAppKey.range(of:"<") != nil) {
print("\n\n\nMust set test data (in TestData.swift) before launching app.\n\n\nTerminating.....\n\n")
exit(0);
}
switch(appPermission) {
case .fullDropbox:
DropboxClientsManager.setupWithAppKey(TestData.fullDropboxAppKey)
case .teamMemberFileAccess:
DropboxClientsManager.setupWithTeamAppKey(TestData.teamMemberFileAccessAppKey)
case .teamMemberManagement:
DropboxClientsManager.setupWithTeamAppKey(TestData.teamMemberManagementAppKey)
}
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
let oauthCompletion: DropboxOAuthCompletion = {
if let authResult = $0 {
switch authResult {
case .success:
print("Success! User is logged into DropboxClientsManager.")
case .cancel:
print("Authorization flow was manually canceled by user!")
case .error(_, let description):
print("Error: \(String(describing: description))")
}
}
(self.window?.rootViewController as? ViewController)?.checkButtons()
}
switch(appPermission) {
case .fullDropbox:
DropboxClientsManager.handleRedirectURL(url, completion: oauthCompletion)
case .teamMemberFileAccess:
DropboxClientsManager.handleRedirectURLTeam(url, completion: oauthCompletion)
case .teamMemberManagement:
DropboxClientsManager.handleRedirectURLTeam(url, completion: oauthCompletion)
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 51.671053 | 285 | 0.69697 |
ff9a2151b34fb9dfea7bf566e30dc817a3bae2a0 | 1,028 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwizzleTest",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "SwizzleTest",
targets: ["SwizzleTest"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "SwizzleTest",
dependencies: []),
.testTarget(
name: "SwizzleTestTests",
dependencies: ["SwizzleTest"]),
]
)
| 35.448276 | 117 | 0.623541 |
e869f011177fa0cba01a25c67795aae3848e52f6 | 981 | //
// Noise.swift
// Noisily
//
// Created by Adam Ahrens on 3/11/15.
// Copyright (c) 2015 Appsbyahrens. All rights reserved.
//
import UIKit
import Realm
class Noise: RLMObject {
dynamic var name = ""
dynamic var imageName = ""
dynamic var fileName = ""
dynamic var fileType = ""
override var hashValue: Int {
return name.hashValue & imageName.hashValue & fileName.hashValue & fileType.hashValue
}
func soundFilePath() -> NSURL {
return NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(fileName, ofType: fileType)!)
}
}
func ==(lhs: Noise, rhs: Noise) -> Bool {
let sameName = lhs.name == rhs.name
let sameImageName = lhs.imageName == rhs.imageName
let sameFileName = lhs.fileName == rhs.fileName
let sameFileType = lhs.fileType == rhs.fileType
return sameName && sameImageName && sameFileName && sameFileType
}
func !=(lhs: Noise, rhs: Noise) -> Bool {
return !(lhs == rhs)
}
| 25.815789 | 105 | 0.655454 |
69437c2781c770e7af9eecba051f16442b12a1c5 | 544 | //
// MenuTableViewCell.swift
// OptionsMenuDemo
//
// Created by Niklas Fahl on 9/2/15.
// Copyright © 2015 CAPS. All rights reserved.
//
import UIKit
class MenuTableViewCell: UITableViewCell {
@IBOutlet weak var menuTitleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 20.148148 | 63 | 0.663603 |
16ed2249fd3c2c23090a7cff6661ef83db359267 | 374 | //
// FirstVC.swift
// Demo
//
// Created by Jan Dammshäuser on 26.09.16.
// Copyright © 2016 Jan Dammshäuser. All rights reserved.
//
import UIKit
import JDTransition
class FirstVC: UIViewController {
@IBAction func pushVC(sender _: UIButton) {
let VC = SecondViewController()
navigationController?.pushViewController(VC, animated: true)
}
}
| 19.684211 | 68 | 0.68984 |
d9a85caf68fa44d534e163c94dd738197813480b | 13,982 | //
// ArleneDemoVC.swift
// Arlene Demo
//
// Created by Macbook on 12/15/19.
// Copyright © 2019 Macbook. All rights reserved.
//
import UIKit
import ARKit
import Arlene
class ArleneDemoVC: UIViewController, ARSCNViewDelegate {
var sceneView: ARSCNView!
enum cameraFacing {
case front
case back
}
var activeCam: cameraFacing = .back
// placements dictionary
var placementsList: [Dictionary<String, String>]?
var activePlacementIds: Dictionary<String,Bool> = [:]
let adNodeRoot: SCNNode = SCNNode()
var removeAdsBtn: UIButton!
var rearCamPlacementBtns: [UIButton] = []
var frontCamPlacementBtns: [UIButton] = []
var faceNodes: [SCNNode] = []
let debug : Bool = false
private var planes = [UUID: Plane]()
// [Arlene] declare session
lazy var arleneSession = Arlene.create(withSceneView: sceneView, viewController: self)
// MARK: VC Events
override func loadView() {
super.loadView()
self.view.backgroundColor = UIColor.black // set the background color
// Setup sceneview
let sceneView = ARSCNView() //instantiate scene view
self.view.insertSubview(sceneView, at: 0)
//add sceneView layout contstraints
sceneView.translatesAutoresizingMaskIntoConstraints = false
sceneView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
sceneView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
sceneView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
sceneView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
sceneView.automaticallyUpdatesLighting = true
sceneView.autoenablesDefaultLighting = true
// set reference to sceneView
self.sceneView = sceneView
// back button
let backBtn = UIButton()
backBtn.frame = CGRect(x: self.view.frame.minX+20, y: self.view.frame.minY + 20, width: 45, height: 45)
backBtn.layer.cornerRadius = 10
if let backIcon = UIImage(named: "arlene-brandmark") {
backBtn.setImage(backIcon, for: .normal)
} else {
backBtn.setTitle("back", for: .normal)
backBtn.setTitleColor(.white, for: .normal)
}
backBtn.addTarget(self, action: #selector(popView), for: .touchUpInside)
self.view.insertSubview(backBtn, at: 2)
// flip camera button
if ARFaceTrackingConfiguration.isSupported {
let flipCamBtn = UIButton()
flipCamBtn.frame = CGRect(x:self.view.frame.maxX-65, y:self.view.frame.minY+25, width: 40, height: 40)
if let flipCamIcon = UIImage(named: "flip-camera") {
flipCamBtn.setImage(flipCamIcon, for: .normal)
} else {
flipCamBtn.setTitle("^v", for: .normal)
flipCamBtn.setTitleColor(.white, for: .normal)
}
flipCamBtn.addTarget(self, action: #selector(cameraFlipBtnTap), for: .touchDown)
self.view.insertSubview(flipCamBtn, at: 2)
}
//placement buttons
guard let placemnts = self.placementsList else { return }
for (index, placement) in placemnts.enumerated() {
if debug {
print(placement)
}
let placementBtn = UIButton()
var offset: Int
if placement["CAM"] == "back" {
rearCamPlacementBtns.append(placementBtn)
offset = rearCamPlacementBtns.count-1
} else if placement["CAM"] == "front" {
frontCamPlacementBtns.append(placementBtn)
placementBtn.isHidden = true
offset = frontCamPlacementBtns.count-1
} else {
return
}
placementBtn.frame = CGRect(x: (self.view.frame.maxX-75)-CGFloat(offset*60), y: (self.view.frame.maxY-75), width: 55, height: 55)
if let placementIcon = UIImage(named: placement["ICON"]!) {
placementBtn.setImage(placementIcon, for: .normal)
} else {
placementBtn.setTitle( placement["NAME"]!, for: .normal)
placementBtn.setTitleColor(.white, for: .normal)
}
placementBtn.tag = index
placementBtn.addTarget(self, action: #selector(placementButtonTap(sender:)), for: .touchUpInside)
self.view.insertSubview(placementBtn, at: 3)
}
// waste bin
let removeAdsBtn = UIButton()
removeAdsBtn.frame = CGRect(x: self.view.bounds.minX + 35, y: self.view.bounds.maxY - 75, width: 40, height: 40)
if let wasteBin = UIImage(named: "waste-bin") {
removeAdsBtn.setImage(wasteBin, for: .normal)
} else {
removeAdsBtn.setTitle("remove", for: .normal)
removeAdsBtn.setTitleColor(.white, for: .normal)
}
removeAdsBtn.addTarget(self, action: #selector(removeAds), for: .touchUpInside)
self.view.insertSubview(removeAdsBtn, at: 2)
// set reference to removeMojiBtn
self.removeAdsBtn = removeAdsBtn
self.removeAdsBtn.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
// MARK: Initialize Arlene Session
let appKey = getValueFromFile(withKey: "APP_ID", within: "keys")
Arlene.setAppKey(appKey)
arleneSession.initialise { (result, error) in
if let error = error {
print ("Failed to initialise Arlene: \(error)")
}
else {
if result {
print("Successfully initialized Arlene SDK")
self.arleneSession.developmentMode = false
}
}
}
if debug {
sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin , ARSCNDebugOptions.showFeaturePoints]
sceneView.showsStatistics = true
}
let configuration = ARWorldTrackingConfiguration()
// configuration.planeDetection = [.horizontal, .vertical]
configuration.planeDetection = [.horizontal]
configuration.isLightEstimationEnabled = true
sceneView.session.run(configuration)
sceneView.delegate = self
// add the adRootNode to the scene
self.sceneView.scene.rootNode.addChildNode(self.adNodeRoot)
}
// MARK: Hide status bar
override var prefersStatusBarHidden: Bool {
return true
}
// MARK: Render Delegate
func renderer(_ renderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: TimeInterval) {
// must call Arlene during render
arleneSession.render()
}
// plane detection
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
if self.activeCam == .back {
// we only care about planes
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
if debug {
NSLog("Found plane: \(planeAnchor)") }
} else if self.activeCam == .front {
guard let sceneView = renderer as? ARSCNView, anchor is ARFaceAnchor else { return }
/*
Write depth but not color and render before other objects.
This causes the geometry to occlude other SceneKit content
while showing the camera view beneath, creating the illusion
that real-world objects are obscuring virtual 3D objects.
*/
let faceGeometry = ARSCNFaceGeometry(device: sceneView.device!)!
faceGeometry.firstMaterial!.colorBufferWriteMask = []
let occlusionNode = SCNNode(geometry: faceGeometry)
occlusionNode.renderingOrder = -1
let contentNode = SCNNode()
contentNode.addChildNode(occlusionNode)
node.addChildNode(contentNode)
faceNodes.append(node)
}
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
guard let planeAnchor = anchor as? ARPlaneAnchor else { return }
if let plane = planes[planeAnchor.identifier] {
plane.updateWith(anchor: planeAnchor)
}
}
func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) {
//print("Anchor removed \(anchor)")
planes.removeValue(forKey: anchor.identifier)
}
// MARK: Button Events
@IBAction func popView() {
self.dismiss(animated: true, completion: nil)
}
@IBAction func placementButtonTap(sender: UIButton) {
print(sender.tag)
let placement = self.placementsList![sender.tag]
guard let placementId = placement["KEY"] else { return }
self.arleneSession.fetchPlacement(withID: placementId, { (placementId, result, error) in
print("fetchPlacement \(placementId) \(result)")
})
// set up parent node
let adNodeParent = SCNNode()
// Call immediately. The load operation will be queued
self.arleneSession.loadPlacement(withID: placementId, toNode: adNodeParent, autoRemove: false, { (placementId, result, error) in
print("loadPlacement \(placementId) \(result)")
if result == .success {
// upon successful load, add the advertisement to the scene as a child of the adRootNode
if placement["CAM"] == "back" {
var xPos = 0.25 + (0.5 * Double(sender.tag))
let halfList = self.placementsList!.count/2
if sender.tag >= halfList {
xPos = -1 * (0.25 + (0.25 * Double(sender.tag % halfList)))
}
adNodeParent.position = SCNVector3(xPos, -0.25, -1)
self.adNodeRoot.addChildNode(adNodeParent)
} else if placement["CAM"] == "front" {
if placement["NAME"] == "Baseball Cap" {
adNodeParent.position = SCNVector3(0, 0.07, -0.075)
adNodeParent.eulerAngles = SCNVector3(0, 180.degreesToRadians, 0)
} else if placement["NAME"] == "Sunglasses" {
adNodeParent.scale = SCNVector3(12.75,12.75,12.75)
adNodeParent.position = SCNVector3(0, 0, 0.055)
}
for (index, node) in self.faceNodes.enumerated() {
if index == 0 {
node.addChildNode(adNodeParent)
} else {
let parentClone = adNodeParent.clone()
node.addChildNode(parentClone)
}
}
} else {
return
}
// keep track of the active placements
if self.activePlacementIds[placementId] == nil {
self.activePlacementIds[placementId] = true
}
}
})
// show the remove ads icon
if self.removeAdsBtn.isHidden {
self.removeAdsBtn.isHidden = false
}
}
@IBAction func removeAds() {
self.removeAdsBtn.isHidden = true // hide button
for (key, _) in self.activePlacementIds {
print("remove placement: \(key)")
self.arleneSession.removePlacement(withID: key, {(_) in
print("removed placement: \(key)")
})
self.activePlacementIds.removeValue(forKey: key)
}
if activeCam == .back {
for adChild in self.adNodeRoot.childNodes {
adChild.removeFromParentNode()
}
} else {
for faceNode in faceNodes {
for adNode in faceNode.childNodes {
adNode.removeFromParentNode()
}
}
}
}
// MARK: Camera Flip
@objc func cameraFlipBtnTap() {
if self.activeCam == .back {
// switch to front config
let configuration = ARFaceTrackingConfiguration()
configuration.isLightEstimationEnabled = true
//clean up the scene
for childNode in self.sceneView.scene.rootNode.childNodes {
childNode.removeFromParentNode()
}
for btn in rearCamPlacementBtns {
btn.isHidden = true
}
for btn in frontCamPlacementBtns {
btn.isHidden = false
}
// run the config to swap the camera
self.sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
self.activeCam = .front
} else {
// switch to back cam config
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = [.horizontal, .vertical]
configuration.isLightEstimationEnabled = true
// clean up the scene
for childNode in self.sceneView.scene.rootNode.childNodes {
childNode.removeFromParentNode()
}
for btn in rearCamPlacementBtns {
btn.isHidden = false
}
for btn in frontCamPlacementBtns {
btn.isHidden = true
}
// run the config to swap the camera
self.sceneView.session.run(configuration, options: [.resetTracking, .removeExistingAnchors])
self.activeCam = .back
}
}
}
| 40.063037 | 141 | 0.571449 |
e2573f2f4058c9942f60b31dcba36f075ad48f9d | 1,308 | //
// UIColorExtensions.swift
// ArtsyChallenge
//
// Created by Mithran Natarajan on 5/13/19.
// Copyright © 2019 Mithran Natarajan. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
static var random: UIColor {
return UIColor(red: .random(in: 0 ... 1),
green: .random(in: 0 ... 1),
blue: .random(in: 0 ... 1),
alpha: 1.0)
}
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
static var lightBlack: UIColor {
return UIColor(rgb: 0x354052)
}
static var transparentBlack: UIColor {
return self.init(red: CGFloat(0) / 255.0, green: CGFloat(0) / 255.0, blue: CGFloat(0) / 255.0, alpha: 0.2)
}
class var blue: UIColor { return UIColor(rgb: 0x354052) }
}
| 29.066667 | 116 | 0.551988 |
22be006d2a4b9e352ebcad53bc8c0ce6f8308b0a | 609 | //
// FileTableViewCell.swift
// FilesBrowser
//
// Copyright © 2018 Mousavian. All rights reserved.
//
import UIKit
class FileTableViewCell: UITableViewCell {
@IBOutlet weak var fileImageView: UIImageView!
@IBOutlet weak var fileName: UILabel!
@IBOutlet weak var fileDescription: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 21 | 65 | 0.671593 |
461ea5166628d7ff204ad07142d724e9f6a804e8 | 231 | import Foundation
extension Date {
func listStyle() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM YYYY, HH:mm"
return dateFormatter.string(from: self)
}
}
| 19.25 | 55 | 0.632035 |
7933e531bb3d6e47f52a89c4a8a556a249d4332c | 1,416 | //
// DYBaseViewModel.swift
// DYZB
//
// Created by ma c on 16/11/7.
// Copyright © 2016年 shifei. All rights reserved.
//
import UIKit
class DYBaseViewModel {
lazy var anchorGroups = [DYAnchorGroupItem]()
}
extension DYBaseViewModel {
func loadAnchorsData(isGroupData : Bool, URLString : String, params : [String : Any]? = nil, finishedCallback : @escaping () -> ()) {
DYNetWorksTools.requestJsonData(type: .get, URLString: URLString, params: params) { (json) in
// 1.获取数据
guard let jsonArray = json as? [String : Any] else { return }
guard let dataArray = jsonArray["data"] as? [[String : Any]] else { return }
// 2.判断是否是分组数据
if isGroupData {
// 2.1遍历数组转模型
for dict in dataArray {
self.anchorGroups.append(DYAnchorGroupItem(dict: dict))
}
} else {
// 2.1创建组
let group = DYAnchorGroupItem()
// 2.2遍历dataArray中所有的字典
for dict in dataArray {
group.anchors.append(DYAnchorItem(dict : dict))
}
// 2.3讲group添加到anchorGroup
self.anchorGroups.append(group)
}
// 3.回调
finishedCallback()
}
}
}
| 27.764706 | 137 | 0.499294 |
9b2a84353b9cf6f5e00502c73ad49c6923c9004a | 1,405 | //
// AppDelegate.swift
// AppleMap
//
// Created by Tong Yi on 7/2/20.
// Copyright © 2020 Tong Yi. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.973684 | 179 | 0.745196 |
08bdfecbd85c2201551fdd552b16b1c60e9d6a15 | 4,477 | //
// ABIRawType+Static.swift
// web3swift
//
// Created by Matt Marshall on 10/04/2018.
// Copyright © 2018 Argent Labs Limited. All rights reserved.
//
import Foundation
import BigInt
public protocol ABIType { }
extension String: ABIType { }
extension Bool: ABIType { }
extension EthereumAddress: ABIType { }
extension BigInt: ABIType { }
extension BigUInt: ABIType { }
extension Data: ABIType { }
// TODO (U)Double. Function. Array. Other Int sizes
extension Array: ABIType { }
extension UInt8: ABIType { }
extension UInt16: ABIType { }
extension UInt32: ABIType { }
extension UInt64: ABIType { }
public protocol ABIFixedSizeDataType: ABIType {
static var fixedSize: Int { get }
}
public struct Data1: ABIFixedSizeDataType {
public static let fixedSize: Int = 1
}
public struct Data2: ABIFixedSizeDataType {
public static let fixedSize: Int = 2
}
public struct Data3: ABIFixedSizeDataType {
public static let fixedSize: Int = 3
}
public struct Data4: ABIFixedSizeDataType {
public static let fixedSize: Int = 4
}
public struct Data5: ABIFixedSizeDataType {
public static let fixedSize: Int = 5
}
public struct Data6: ABIFixedSizeDataType {
public static let fixedSize: Int = 6
}
public struct Data7: ABIFixedSizeDataType {
public static let fixedSize: Int = 7
}
public struct Data8: ABIFixedSizeDataType {
public static let fixedSize: Int = 8
}
public struct Data9: ABIFixedSizeDataType {
public static let fixedSize: Int = 9
}
public struct Data10: ABIFixedSizeDataType {
public static let fixedSize: Int = 10
}
public struct Data11: ABIFixedSizeDataType {
public static let fixedSize: Int = 11
}
public struct Data12: ABIFixedSizeDataType {
public static let fixedSize: Int = 12
}
public struct Data13: ABIFixedSizeDataType {
public static let fixedSize: Int = 13
}
public struct Data14: ABIFixedSizeDataType {
public static let fixedSize: Int = 14
}
public struct Data15: ABIFixedSizeDataType {
public static let fixedSize: Int = 15
}
public struct Data16: ABIFixedSizeDataType {
public static let fixedSize: Int = 16
}
public struct Data17: ABIFixedSizeDataType {
public static let fixedSize: Int = 17
}
public struct Data18: ABIFixedSizeDataType {
public static let fixedSize: Int = 18
}
public struct Data19: ABIFixedSizeDataType {
public static let fixedSize: Int = 19
}
public struct Data20: ABIFixedSizeDataType {
public static let fixedSize: Int = 20
}
public struct Data21: ABIFixedSizeDataType {
public static let fixedSize: Int = 21
}
public struct Data22: ABIFixedSizeDataType {
public static let fixedSize: Int = 22
}
public struct Data23: ABIFixedSizeDataType {
public static let fixedSize: Int = 23
}
public struct Data24: ABIFixedSizeDataType {
public static let fixedSize: Int = 24
}
public struct Data25: ABIFixedSizeDataType {
public static let fixedSize: Int = 25
}
public struct Data26: ABIFixedSizeDataType {
public static let fixedSize: Int = 26
}
public struct Data27: ABIFixedSizeDataType {
public static let fixedSize: Int = 27
}
public struct Data28: ABIFixedSizeDataType {
public static let fixedSize: Int = 28
}
public struct Data29: ABIFixedSizeDataType {
public static let fixedSize: Int = 29
}
public struct Data30: ABIFixedSizeDataType {
public static let fixedSize: Int = 30
}
public struct Data31: ABIFixedSizeDataType {
public static let fixedSize: Int = 31
}
public struct Data32: ABIFixedSizeDataType {
public static let fixedSize: Int = 32
}
extension ABIRawType {
init?(type: ABIType.Type) {
switch type {
case is String.Type: self = ABIRawType.DynamicString
case is Bool.Type: self = ABIRawType.FixedBool
case is EthereumAddress.Type: self = ABIRawType.FixedAddress
case is BigInt.Type: self = ABIRawType.FixedInt(256)
case is BigUInt.Type: self = ABIRawType.FixedUInt(256)
case is UInt8.Type: self = ABIRawType.FixedUInt(8)
case is UInt16.Type: self = ABIRawType.FixedUInt(16)
case is UInt32.Type: self = ABIRawType.FixedUInt(32)
case is UInt64.Type: self = ABIRawType.FixedUInt(64)
case is Data.Type: self = ABIRawType.DynamicBytes
case is ABIFixedSizeDataType.Type:
guard let fixed = type as? ABIFixedSizeDataType.Type else { return nil }
self = ABIRawType.FixedBytes(fixed.fixedSize)
default: return nil
}
}
}
| 25.011173 | 84 | 0.722805 |
3a7ecb24d60fecbb8f1ea8b65bec8aeea06513c7 | 13,906 | //
// NewCardTableViewController.swift
// Flist
//
// Created by Роман Широков on 30.03.18.
// Copyright © 2018 Flist. All rights reserved.
//
import UIKit
class NewCardTableViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {
// Data from the previous view.
// It shows whether we in the proccess of modifying existing card or in the creating new one.
public var cardToEdit: CardElement? // Var is assigned during the segue if it must be modified
public var groups: [CardGroup]? // Existing card groups
private var isModifying: Bool { // Checks what proccess is now (editing or creating)
return cardToEdit != nil
}
// Data from the Link Account View (template or custom)
var customIconImg: UIImage? {
willSet(customIcon) {
cardIconImg.image = (customIcon == nil) ? ServiceModel.services[0].icon : customIcon
}
}
var cardType: String! = "none" {
willSet(newValue) { // If willSet var, then also set corresponding iconImg (if it isn't custom)
let service = ServiceModel.getTypeByShortcut(newValue)
cardIconImg.image = service.icon
cardNameField.text = service.name
}
}
var linkToService: String? {
willSet(newValue) { cardLinkLabel.text = newValue } // If willSet var, then also set link field
}
var usernameToService: String? {
willSet(newValue) { cardUsernameField.text = newValue }
}
//Data of the current view
let model = ProfileManageModel()
var selectedRowInGroupPicker: Int = 0 {
willSet(row) {
if row == 0 {
groupPickerField.text = "None"
} else if groups![0].id == "0" {
groupPickerField.text = groups![row].name
} else {
groupPickerField.text = groups![row-1].name
}
}
}
var isIconUploading: Bool = false
// MARK: Card Creation Outlets
@IBOutlet weak var cardIconImg: UIImageView! // Icon that represents card (social network icon)
@IBOutlet weak var cardLinkLabel: UILabel! // Link to the account
@IBOutlet weak var cardUsernameField: UITextField! // Specify username for the account for card
@IBOutlet weak var cardNameField: UITextField! // Name of the card
@IBOutlet weak var cardDescriptionField: UITextView! // Description of the card
@IBOutlet weak var cardPrivacyPicker: UISegmentedControl! // Privacy setting (0 - public; 1 - friends; 2 - custom)
@IBOutlet weak var groupPickerField: UITextField! // TextField for group name
@IBOutlet weak var cardUploadBtn: UIButton! // Button to start uploading of the card to server
private var cardUploadIndView: UIActivityIndicatorView? // Indicator that will show the card upload proccess
public func InitializeController(card: CardElement? = nil, groups: [CardGroup]? = nil) {
if let crd = card { self.cardToEdit = crd }
self.groups = groups
}
override func viewDidLoad() {
super.viewDidLoad()
SetupGroupPicker() // Group picker setup
SetupViewTitle ()
SetupUIElements()
SetupUploadCardIndicator()
}
private func SetupViewTitle () {
if isModifying, let card = cardToEdit {
self.navigationItem.title = "Edit Card"
cardUploadBtn.setTitle("Save", for: .normal)
cardIconImg.image = card.img
cardType = card.type
cardLinkLabel.text = card.url
cardNameField.text = card.name
cardUsernameField.text = card.username
cardDescriptionField.text = card.desc
selectedRowInGroupPicker = GetRowByGroupID(id: card.group_id)
} else { groupPickerField.text = "None" }
self.tableView.tableFooterView = UIView()
}
private func SetupUIElements() {
if let crdType = cardType, let lnk = linkToService, let usrn = usernameToService {
cardIconImg.image = ServiceModel.getTypeByShortcut(crdType).icon
cardLinkLabel.text = lnk
cardUsernameField.text = usrn
}
}
private func SetupGroupPicker () {
let toolBar = UIToolbar(frame: CGRect(x: 0, y: self.view.frame.size.height/6, width: self.view.frame.size.width, height: 40.0))
toolBar.layer.position = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height-20.0)
toolBar.barStyle = UIBarStyle.blackTranslucent
toolBar.tintColor = UIColor.white
toolBar.backgroundColor = UIColor.lightGray
let doneBarBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(self.GroupPicked))
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil)
let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width / 3, height: self.view.frame.size.height))
label.font = UIFont(name: "Helvetica", size: 12)
label.backgroundColor = UIColor.clear
label.textColor = UIColor.white
label.text = "Select a group"
label.textAlignment = NSTextAlignment.center
let textBtn = UIBarButtonItem(customView: label)
toolBar.setItems([flexSpace,textBtn,flexSpace,doneBarBtn], animated: true)
groupPickerField.inputAccessoryView = toolBar
}
private func SetupUploadCardIndicator() {
let indicator = UIActivityIndicatorView(style: .whiteLarge)
indicator.color = UIColor.mainColorTheme
indicator.center = cardUploadBtn.center
cardUploadIndView = indicator
self.cardUploadBtn.superview?.addSubview(cardUploadIndView!)
}
private func SetActivityIndicatorState(_ state: Bool) {
cardUploadBtn.isHidden = state
if state { cardUploadIndView?.startAnimating() }
else { cardUploadIndView?.stopAnimating() }
self.navigationItem.leftBarButtonItem?.isEnabled = false
// Disable all interactable elements, while uploading
cardLinkLabel.isUserInteractionEnabled = !state
cardNameField.isUserInteractionEnabled = !state
cardUsernameField.isUserInteractionEnabled = !state
cardPrivacyPicker.isUserInteractionEnabled = !state
cardDescriptionField.isUserInteractionEnabled = !state
}
// MARK: GROUP PICKER
@IBAction func GroupFieldAction(_ sender: UITextField) {
let pickerView: UIPickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
if let card = cardToEdit // If we're editing existing card, select it's group
{
pickerView.selectRow(GetRowByGroupID(id: card.group_id), inComponent: 0, animated: false)
}
else // Otherwise, select empty group
{
pickerView.selectRow(0, inComponent: 0, animated: false)
}
groupPickerField.inputView = pickerView
}
func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 }
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if let gr = groups, gr.count > 0 {
// In the picker we need to have an empty group
if gr[0].id == "0" { return gr.count } // If there is already one in the array of groups, then return its count
else { return gr.count+1 } // Otherwise, return count with one extra.
} else { return 1 } // If groups array is empty, in the picker will be just one empty group to choose from
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if row == 0 { return "None" } // The first row of picker is an empty ("none") group
else // Other groups are named from the groups' array
{
// If the 1st group is an empty group, then count as it is
// Otherwise, the array's actual count is lesser by 1, than we need (there is one extra row for empty group).
let rw = groups?[0].id == "0" ? row : row-1
return groups?[rw].name
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// groupPickerField.text = self.pickerView(pickerView, titleForRow: row, forComponent: component)
selectedRowInGroupPicker = row
}
@objc func GroupPicked(sender: UIBarButtonItem) {
groupPickerField.resignFirstResponder()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
private func GetGroupIDByRow(row: Int) -> String {
if let gr = groups, row > 0 {
if gr[0].id == "0" { return gr[row].id }
else { return gr[row-1].id }
}
return "0"
}
private func GetRowByGroupID(id: String) -> Int {
if let grs = groups, id != "0" {
for i in 0...grs.count-1 {
if id == grs[i].id { return i+1 }
}
}
return 0
}
// MARK: UPLOAD LOGIC
@IBAction func CreateCardAction(_ sender: Any) {
SetActivityIndicatorState(true)
var data = [String: Any]() // Data Array that will be uploaded to the server
var card_id: String
if ( CheckFieldsOnEmptyness() ) { return }
if isModifying, let card = cardToEdit {
// Read all fields' values
let name = cardNameField.text
let username = cardUsernameField.text
let desctipt = cardDescriptionField.text
let url = cardLinkLabel.text
let group_id = GetGroupIDByRow(row: selectedRowInGroupPicker)
// If any field is modified, insert it to the data array
if cardType != card.type { data["type"] = cardType }
if name != card.name { data["name"] = name }
if username != card.username { data["username"] = username }
if desctipt != card.desc { data["description"] = desctipt }
if url != card.url { data["url"] = url }
if group_id != card.group_id { data["group_id"] = group_id }
card_id = card.id
// If any field is modified (data != empty), update corresponding card on the server
if data.count > 0 { model.updateCard(data, id: card.id) }
} else {
data["type"] = cardType
data["group_id"] = GetGroupIDByRow(row: selectedRowInGroupPicker)
data["name"] = cardNameField.text
data["username"] = cardUsernameField.text
data["privacy"] = cardPrivacyPicker.selectedSegmentIndex
data["url"] = cardLinkLabel.text
data["description"] = cardDescriptionField.text.isEmpty ? cardNameField.text : cardDescriptionField.text
card_id = model.addCard(data) // Add new card to the server
}
if cardType == "none", let img = customIconImg {
isIconUploading = true
let reseizedImg = ProfileManageModel.ResizeImage(image: img, targetSize: CGSize(width: 225, height: 225))
model.uploadCustomCardIcon(card_id: card_id, img: reseizedImg, completionHandler: {
self.ReloadPreviousTableView()
self.navigationController?.popViewController(animated: true)
})
}
if !isIconUploading {
if data.count > 0 { ReloadPreviousTableView() }
self.navigationController?.popViewController(animated: true)
}
}
private func CheckFieldsOnEmptyness() -> Bool {
if (cardNameField.text?.isEmpty)! ||
(cardUsernameField.text?.isEmpty)! ||
(cardLinkLabel.text?.isEmpty)!
{
SetActivityIndicatorState(false)
self.navigationItem.leftBarButtonItem?.isEnabled = true
self.ShowAlert(msg: "All of the input fields must be filled!")
return true
}
return false
}
private func ReloadPreviousTableView () {
if let viewControllers = self.navigationController?.viewControllers {
let count = viewControllers.count
if count > 1 {
if let vc = viewControllers[count - 2] as? MyProfileViewController {
vc.TableViewLoadData()
}
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "NewCardToCustomLink" {
if isModifying && cardToEdit?.type == "none" {
let cell = segue.destination as! CardCustomLinkTableViewController
cell.customExistingIcon = cardToEdit?.img
cell.customExistingLink = cardToEdit?.url
}
}
}
}
| 35.205063 | 145 | 0.586869 |
4b270cc69967261089ae25f09790fd8c83c564ee | 5,644 | //
// APIClient.swift
// MyInfo
//
// Created by Li Hao Lai on 14/12/20.
//
import Foundation
typealias Route = APIRoutable
protocol APIClientType {
func request(route: Route, completionHandler: @escaping (Result<Data, Error>) -> Void)
func request<T>(route: Route, for type: T.Type, completionHandler: @escaping (Result<T, Error>) -> Void) where T: Decodable
}
final class APIClient: APIClientType {
let utils: APIUtils
private let storage: MyInfoStorage
/// Initialise with optional `URLSessionConfiguration`, if this value is not set, `URLSessionConfiguration.default` will be used.
init(configuration: URLSessionConfiguration = .default, utils: APIUtils, storage: MyInfoStorage) {
urlSession = URLSession(configuration: configuration)
self.utils = utils
self.storage = storage
}
/// Default URLSession for API client
let urlSession: URLSession
///
/// Request from the internet based on information retrieved from `APIRoutable`.
///
/// - Parameters:
/// - route: An `APIRoutable` instance which contains host, path, HTTP Method, Parameters and etc.
/// - Returns: Response data
///
func request(route: Route, completionHandler: @escaping (Result<Data, Error>) -> Void) {
do {
var request = try route.asURLRequest()
logger.debug("URL request: \(request.curlString)")
if route.shouldAuthenticate {
guard storage.isAuthorized else {
completionHandler(.failure(APIClientError.unableToAuthenticate))
return
}
storage.authState?.performAction(freshTokens: { [weak self] accessToken, _, error in
guard error == nil,
let self = self,
let accessToken = accessToken,
let url = URL(string: route.urlHost + route.path)
else {
completionHandler(.failure(error ?? APIClientError.unknown(message: "Failed to authenticate without error")))
return
}
guard self.utils.oAuth2Config.environment != .sandbox else {
request.addValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
self.performDataTask(with: request, completionHandler: completionHandler)
return
}
do {
let sign = try self.utils.getAuthorizationHeader(method: route.method,
url: url,
additionalParams: route.parameters as? [String: String]
?? route.query ?? [:])
request.addValue("\(sign),Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
self.performDataTask(with: request, completionHandler: completionHandler)
} catch {
completionHandler(.failure(error))
}
})
} else {
performDataTask(with: request, completionHandler: completionHandler)
}
} catch {
completionHandler(.failure(error))
}
}
private func performDataTask(with request: URLRequest, completionHandler: @escaping (Result<Data, Error>) -> Void) {
urlSession.dataTask(with: request) { [weak self] data, response, error in
guard let self = self else {
completionHandler(.failure(APIClientError.unknown(message: "APIClient has deallocated.")))
return
}
do {
completionHandler(.success(try self.validate(data: data, response: response, error: error)))
} catch {
completionHandler(.failure(error))
}
}.resume()
}
private func validate(data: Data?, response: URLResponse?, error: Error?) throws -> Data {
guard let response = response, let data = data else {
throw error ?? APIClientError.unknown(message: "Cannot retrieve response or error.")
}
guard let httpResponse = response as? HTTPURLResponse else {
throw APIClientError.nonHTTPResponse
}
guard 200..<300 ~= httpResponse.statusCode else {
var message: String?
if let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] {
message = json["message"] as? String
}
guard let reason = APIClientError.RequestFailureReason(code: httpResponse.statusCode, message: message) else {
throw APIClientError.unknown(message: "Unknows HTTP status code.")
}
throw APIClientError.requestFailure(reason: reason)
}
return data
}
}
extension APIClient {
///
/// Request from the internet based on information retrieved from `APIRoutable`.
///
/// - Parameters:
/// - route: An `APIRoutable` instance which contains host, path, HTTP Method, Parameters and etc.
/// - forType: An ouput object that conforms the Decodable protocol.
/// - Returns: Object observable
///
func request<T>(route: Route, for type: T.Type, completionHandler: @escaping (Result<T, Error>) -> Void) where T: Decodable {
request(route: route) { result in
switch result {
case let .success(data):
do {
logger.debug("Request successful, response: \(String(describing: (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) ?? [:]))")
completionHandler(.success(try JSONDecoder().decode(type, from: data)))
} catch {
logger.error("Failed deserialising response: \(error)")
completionHandler(.failure(error))
}
case let .failure(error):
logger.error("Request failed with error: \(error)")
completionHandler(.failure(error))
}
}
}
}
| 36.649351 | 159 | 0.634656 |
564de04f9fdda34e121756bb0e97f81878d9f13d | 2,167 | //
// AppDelegate.swift
// LayerTest
//
// Created by suckerl on 2017/5/17.
// Copyright © 2017年 suckerl. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.106383 | 285 | 0.755422 |
61384b6217a7fab09946e965fa4e79f2fb85570c | 1,282 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.0.1-9346c8cc45
// Copyright 2020 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
/**
The purpose of the Claim: predetermination, preauthorization, claim.
URL: http://hl7.org/fhir/claim-use
ValueSet: http://hl7.org/fhir/ValueSet/claim-use
*/
public enum Use: String, FHIRPrimitiveType {
/// The treatment is complete and this represents a Claim for the services.
case claim = "claim"
/// The treatment is proposed and this represents a Pre-authorization for the services.
case preauthorization = "preauthorization"
/// The treatment is proposed and this represents a Pre-determination for the services.
case predetermination = "predetermination"
}
| 32.871795 | 88 | 0.74025 |
1e97e0477600bfd4b03ab0e0943f3a98d69baf8d | 923 | //
// TimeCodeQuarterFrame.swift
// Swimi
//
// Created by Kainosuke OBATA on 2019/10/05.
// Copyright © 2019 kai. All rights reserved.
//
import Foundation
public struct TimeCodeQuarterFrame: Equatable {
/// Message Type
public var messageType: TimeCodeQuarterFrameMessageType
/// Value: 0 ~ 15
public var value: UInt8
public var bytes: [UInt8] {
[
StatusType.timecodeQuarterFrame.statusByte,
messageType.rawValue << 4 | value,
]
}
public init(messageType: TimeCodeQuarterFrameMessageType, value: UInt8) {
self.messageType = messageType
self.value = value
}
static func fromData(_ data: [UInt8]) -> TimeCodeQuarterFrame {
assert(data.count == 2)
return TimeCodeQuarterFrame(
messageType: .fromByte(data[1]),
value: data[1] & 0b00001111
)
}
}
| 23.075 | 77 | 0.608884 |
3880d84ea7f93624e01c30bf598511c415bc681c | 2,741 | /*
* Copyright (c) 2019 Razeware LLC
*
* 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 Cocoa
class ViewController: NSViewController {
@IBOutlet weak var beforeImageView: NSImageView!
@IBOutlet weak var afterImageView: NSImageView!
@IBOutlet weak var kernelSizeSlider: NSSlider!
@IBOutlet weak var spatialSigmaSlider: NSSlider!
@IBOutlet weak var rangeSigmaSlider: NSSlider!
@IBOutlet weak var kernelSizeLabel: NSTextField!
@IBOutlet weak var spatialSigmaLabel: NSTextField!
@IBOutlet weak var rangeSigmaLabel: NSTextField!
@IBAction func handleNewImage(_ sender: NSImageView) {
processImage()
}
@IBAction func handleSliderMoved(_ sender: Any) {
imageProcessor.kernelRadius = kernelSizeSlider.integerValue
imageProcessor.sigmaRange = rangeSigmaSlider.floatValue
imageProcessor.sigmaSpatial = spatialSigmaSlider.floatValue
updateLabels()
processImage()
}
let imageProcessor = BilateralFilerImageProcessor()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
kernelSizeSlider.integerValue = imageProcessor.kernelRadius
spatialSigmaSlider.floatValue = imageProcessor.sigmaSpatial
rangeSigmaSlider.floatValue = imageProcessor.sigmaRange
updateLabels()
}
private func updateLabels() {
kernelSizeLabel.stringValue = "\(kernelSizeSlider.integerValue)"
spatialSigmaLabel.stringValue = spatialSigmaSlider.stringValue
rangeSigmaLabel.stringValue = rangeSigmaSlider.stringValue
}
private func processImage() {
guard let image = beforeImageView.image else { return }
afterImageView.image = imageProcessor.process(image: image)
}
}
| 37.547945 | 80 | 0.76432 |
6466e84f51998a32452c1ddf7abb96cf73b803c1 | 441 | //
// AppDelegate.swift
// Desktop
//
// Created by Michael on 8/4/19.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 16.961538 | 71 | 0.705215 |
29cf19814b6b1a83d69cfeed7ae3e4a6f5abc0df | 41 |
int i;
for i in [1,2,3] {
print(i);
}
| 5.857143 | 18 | 0.463415 |