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
|
---|---|---|---|---|---|
33b87d47af2db6ef52c5711f431eab175ad0a787 | 4,491 | //
// Statistics.swift
// HealthKitReporter
//
// Created by Victor on 25.09.20.
//
import Foundation
import HealthKit
public struct Statistics: Identifiable, Sample {
public struct Harmonized: Codable {
public let summary: Double?
public let average: Double?
public let recent: Double?
public let min: Double?
public let max: Double?
public let unit: String
public init(
summary: Double?,
average: Double?,
recent: Double?,
min: Double?,
max: Double?,
unit: String
) {
self.summary = summary
self.average = average
self.recent = recent
self.min = min
self.max = max
self.unit = unit
}
public func copyWith(
summary: Double? = nil,
average: Double? = nil,
recent: Double? = nil,
min: Double? = nil,
max: Double? = nil,
unit: String? = nil
) -> Harmonized {
return Harmonized(
summary: summary ?? self.summary,
average: average ?? self.average,
recent: recent ?? self.recent,
min: min ?? self.min,
max: max ?? self.max,
unit: unit ?? self.unit
)
}
}
public let identifier: String
public let startTimestamp: Double
public let endTimestamp: Double
public let harmonized: Harmonized
public let sources: [Source]?
init(statistics: HKStatistics, unit: HKUnit) throws {
self.identifier = statistics.quantityType.identifier
self.startTimestamp = statistics.startDate.timeIntervalSince1970
self.endTimestamp = statistics.endDate.timeIntervalSince1970
self.sources = statistics.sources?.map { Source(source: $0) }
if #available(iOS 12.0, *) {
self.harmonized = Harmonized(
summary: statistics.sumQuantity()?.doubleValue(for: unit),
average: statistics.averageQuantity()?.doubleValue(for: unit),
recent: statistics.mostRecentQuantity()?.doubleValue(for: unit),
min: statistics.minimumQuantity()?.doubleValue(for: unit),
max: statistics.maximumQuantity()?.doubleValue(for: unit),
unit: unit.unitString
)
} else {
self.harmonized = Harmonized(
summary: statistics.sumQuantity()?.doubleValue(for: unit),
average: statistics.averageQuantity()?.doubleValue(for: unit),
recent: nil,
min: statistics.minimumQuantity()?.doubleValue(for: unit),
max: statistics.maximumQuantity()?.doubleValue(for: unit),
unit: unit.unitString
)
}
}
init(statistics: HKStatistics) throws {
self.identifier = statistics.quantityType.identifier
self.startTimestamp = statistics.startDate.timeIntervalSince1970
self.endTimestamp = statistics.endDate.timeIntervalSince1970
self.sources = statistics.sources?.map { Source(source: $0) }
self.harmonized = try statistics.harmonize()
}
private init(
identifier: String,
startTimestamp: Double,
endTimestamp: Double,
harmonized: Harmonized,
sources: [Source]?
) {
self.identifier = identifier
self.startTimestamp = startTimestamp
self.endTimestamp = endTimestamp
self.harmonized = harmonized
self.sources = sources
}
public func copyWith(
identifier: String? = nil,
startTimestamp: Double? = nil,
endTimestamp: Double? = nil,
harmonized: Harmonized? = nil,
sources: [Source]? = nil
) -> Statistics {
return Statistics(
identifier: identifier ?? self.identifier,
startTimestamp: startTimestamp ?? self.startTimestamp,
endTimestamp: endTimestamp ?? self.endTimestamp,
harmonized: harmonized ?? self.harmonized,
sources: sources ?? self.sources
)
}
}
// MARK: - UnitConvertable
extension Statistics: UnitConvertable {
public func converted(to unit: String) throws -> Statistics {
guard harmonized.unit != unit else {
return self
}
return copyWith(harmonized: harmonized.copyWith(unit: unit))
}
}
| 33.766917 | 80 | 0.579158 |
f9e73e6ea280b9a333b488e1d6db078875c5cb09 | 4,248 | // Copyright (c) 2015 Kevin Lundberg.
import UIKit
import KRLCollectionViewGridLayout
private let reuseIdentifier = "Cell"
private let headerFooterIdentifier = "headerFooter"
class GridLayoutCollectionViewController: UICollectionViewController {
var layout: KRLCollectionViewGridLayout {
return self.collectionView?.collectionViewLayout as! KRLCollectionViewGridLayout
}
override func viewDidLoad() {
super.viewDidLoad()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
collectionView?.register(HeaderFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerFooterIdentifier)
collectionView?.register(HeaderFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: headerFooterIdentifier)
}
@IBAction func changeColumnsTapped(_ sender: AnyObject?) {
let alert = UIAlertController(title: "Choose how many columns", message: nil, preferredStyle: .actionSheet)
for num in 1...6 {
alert.addAction(UIAlertAction(title: num.description, style: .default, handler: { action in
self.layout.numberOfItemsPerLine = num
}))
}
present(alert, animated: true, completion: nil)
}
// MARK: - UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 25
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath)
// Configure the cell
if indexPath.section % 2 == 1 {
cell.contentView.backgroundColor = .blue
} else {
cell.contentView.backgroundColor = .red
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerFooterIdentifier, for: indexPath as IndexPath) as! HeaderFooterView
view.label.text = kind
return view
}
}
extension GridLayoutCollectionViewController: KRLCollectionViewDelegateGridLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let inset = CGFloat((section + 1) * 10)
return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, interitemSpacingForSectionAt section: Int) -> CGFloat {
return CGFloat((section + 1) * 10)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, lineSpacingForSectionAt section: Int) -> CGFloat {
return CGFloat((section + 1) * 10)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceLengthForHeaderInSection section: Int) -> CGFloat {
return CGFloat((section + 1) * 20)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceLengthForFooterInSection section: Int) -> CGFloat {
return CGFloat((section + 1) * 20)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, numberItemsPerLineForSectionAt section: Int) -> Int {
return self.layout.numberOfItemsPerLine + (section * 1)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, aspectRatioForItemsInSectionAt section: Int) -> CGFloat {
return CGFloat(1 + section)
}
}
| 41.647059 | 175 | 0.737994 |
87ac088f2abaf6d4b807089d710057b8251528af | 393 | import PhoenixKitsuCore
import Requestable
public class StreamingLink: KitsuObject<StreamingLinkAttributes>, Requestable {
public static var requestURLString = "streaming-links"
}
public class StreamingLinkAttributes: KitsuObjectAttributes {
public let createdAt: String?
public let updatedAt: String?
public let url: String
public let subs: [String]
public let dubs: [String]
}
| 26.2 | 79 | 0.793893 |
2095aeb1ba0a06dc3891103e482dc41608592785 | 824 | //
// RequestHeaderFields.swift
// BaseAPI
//
// Created by Serhii Londar on 1/5/18.
//
import Foundation
enum RequestHeaderFields: String {
case acceptCharset = "Accept-Charset"
case acceptEncoding = "Accept-Encoding"
case acceptLanguage = "Accept-Language"
case authorization = "Authorization"
case contentType = "Content-Type"
case expect = "Expect"
case from = "From"
case host = "Host"
case ifMatch = "If-Match"
case ifModifiedSince = "If-Modified-Since"
case ifNoneMatch = "If-None-Match"
case ifRange = "If-Range"
case ifUnmodifiedSince = "If-Unmodified-Since"
case maxForwards = "Max-Forwards"
case proxyAuthorization = "Proxy-Authorization"
case range = "Range"
case referer = "Referer"
case te = "TE"
case userAgent = "User-Agent"
}
| 26.580645 | 51 | 0.673544 |
7ac39a8445752b11af645995345b0cc063321d69 | 64,813 | // RUN: %target-typecheck-verify-swift -swift-version 5
// See test/Compatibility/tuple_arguments_4.swift for some
// Swift 4-specific tests.
func concrete(_ x: Int) {}
func concreteLabeled(x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
do {
concrete(3)
concrete((3))
concreteLabeled(x: 3)
concreteLabeled(x: (3))
concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}}
// expected-error@-1 {{cannot convert value of type '(x: Int)' to expected argument type 'Int'}}
concreteTwo(3, 4)
concreteTwo((3, 4)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
concreteTuple(3, 4) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
concreteTwo(d) // expected-error {{global function 'concreteTwo' expects 2 separate arguments}}
concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((a, b))
concreteTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
concreteTwo(d) // expected-error {{global function 'concreteTwo' expects 2 separate arguments}}
concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((a, b))
concreteTuple(d)
}
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
do {
generic(3)
generic(3, 4) // expected-error {{extra argument in call}}
generic((3))
generic((3, 4))
genericLabeled(x: 3)
genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
genericLabeled(x: (3))
genericLabeled(x: (3, 4))
genericTwo(3, 4)
genericTwo((3, 4)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}}
genericTuple(3, 4) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}}
genericTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
generic(a)
generic(a, b) // expected-error {{extra argument in call}}
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}}
genericTwo(d) // expected-error {{global function 'genericTwo' expects 2 separate arguments}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
generic(a)
generic(a, b) // expected-error {{extra argument in call}}
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}}
genericTwo(d) // expected-error {{global function 'genericTwo' expects 2 separate arguments}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
var function: (Int) -> ()
var functionTwo: (Int, Int) -> () // expected-note 5 {{'functionTwo' declared here}}
var functionTuple: ((Int, Int)) -> ()
do {
function(3)
function((3))
functionTwo(3, 4)
functionTwo((3, 4)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
functionTuple(3, 4) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
functionTwo(d) // expected-error {{var 'functionTwo' expects 2 separate arguments}}
functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((a, b))
functionTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
functionTwo(d) // expected-error {{var 'functionTwo' expects 2 separate arguments}}
functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((a, b))
functionTuple(d)
}
struct Concrete {}
extension Concrete {
func concrete(_ x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
}
do {
let s = Concrete()
s.concrete(3)
s.concrete((3))
s.concreteTwo(3, 4)
s.concreteTwo((3, 4)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.concreteTuple(3, 4) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.concreteTwo(d) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments}}
s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.concreteTwo(d) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments}}
s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
extension Concrete {
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
}
do {
let s = Concrete()
s.generic(3)
s.generic(3, 4) // expected-error {{extra argument in call}}
s.generic((3))
s.generic((3, 4))
s.genericLabeled(x: 3)
s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.genericLabeled(x: (3))
s.genericLabeled(x: (3, 4))
s.genericTwo(3, 4)
s.genericTwo((3, 4)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTuple(3, 4) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}}
s.genericTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.generic(a)
s.generic(a, b) // expected-error {{extra argument in call}}
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTwo(d) // expected-error {{instance method 'genericTwo' expects 2 separate arguments}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.generic(a)
s.generic(a, b) // expected-error {{extra argument in call}}
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTwo(d) // expected-error {{instance method 'genericTwo' expects 2 separate arguments}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
extension Concrete {
mutating func mutatingConcrete(_ x: Int) {}
mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'mutatingConcreteTwo' declared here}}
mutating func mutatingConcreteTuple(_ x: (Int, Int)) {}
}
do {
var s = Concrete()
s.mutatingConcrete(3)
s.mutatingConcrete((3))
s.mutatingConcreteTwo(3, 4)
s.mutatingConcreteTwo((3, 4)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}}
s.mutatingConcreteTuple(3, 4) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}}
s.mutatingConcreteTwo(d) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments}}
s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}}
s.mutatingConcreteTwo(d) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments}}
s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
extension Concrete {
mutating func mutatingGeneric<T>(_ x: T) {}
mutating func mutatingGenericLabeled<T>(x: T) {}
mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {}
}
do {
var s = Concrete()
s.mutatingGeneric(3)
s.mutatingGeneric(3, 4) // expected-error {{extra argument in call}}
s.mutatingGeneric((3))
s.mutatingGeneric((3, 4))
s.mutatingGenericLabeled(x: 3)
s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.mutatingGenericLabeled(x: (3))
s.mutatingGenericLabeled(x: (3, 4))
s.mutatingGenericTwo(3, 4)
s.mutatingGenericTwo((3, 4)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.mutatingGenericTuple(3, 4) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b) // expected-error {{extra argument in call}}
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.mutatingGenericTwo(d) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b) // expected-error {{extra argument in call}}
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.mutatingGenericTwo(d) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
extension Concrete {
var function: (Int) -> () { return concrete }
var functionTwo: (Int, Int) -> () { return concreteTwo } // expected-note 5 {{'functionTwo' declared here}}
var functionTuple: ((Int, Int)) -> () { return concreteTuple }
}
do {
let s = Concrete()
s.function(3)
s.function((3))
s.functionTwo(3, 4)
s.functionTwo((3, 4)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.functionTuple(3, 4) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.functionTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.functionTwo(d) // expected-error {{property 'functionTwo' expects 2 separate arguments}}
s.functionTuple(a, b) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.functionTuple((a, b))
s.functionTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.functionTwo(d) // expected-error {{property 'functionTwo' expects 2 separate arguments}}
s.functionTuple(a, b) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.functionTuple((a, b))
s.functionTuple(d)
}
struct InitTwo {
init(_ x: Int, _ y: Int) {} // expected-note 5 {{'init(_:_:)' declared here}}
}
struct InitTuple {
init(_ x: (Int, Int)) {}
}
struct InitLabeledTuple {
init(x: (Int, Int)) {}
}
do {
_ = InitTwo(3, 4)
_ = InitTwo((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
_ = InitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((3, 4))
_ = InitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = InitLabeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
_ = InitTwo(c) // expected-error {{initializer expects 2 separate arguments}}
_ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
_ = InitTwo(c) // expected-error {{initializer expects 2 separate arguments}}
_ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
struct SubscriptTwo {
subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}}
}
struct SubscriptTuple {
subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } }
}
struct SubscriptLabeledTuple {
subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } }
}
do {
let s1 = SubscriptTwo()
_ = s1[3, 4]
_ = s1[(3, 4)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
let s2 = SubscriptTuple()
_ = s2[3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(3, 4)]
}
do {
let a = 3
let b = 4
let d = (a, b)
let s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
_ = s1[d] // expected-error {{subscript expects 2 separate arguments}}
let s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(a, b)]
_ = s2[d]
let s3 = SubscriptLabeledTuple()
_ = s3[x: 3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}}
_ = s3[x: (3, 4)]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
_ = s1[d] // expected-error {{subscript expects 2 separate arguments}}
var s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(a, b)]
_ = s2[d]
}
enum Enum {
case two(Int, Int) // expected-note 6 {{'two' declared here}}
case tuple((Int, Int))
case labeledTuple(x: (Int, Int))
}
do {
_ = Enum.two(3, 4)
_ = Enum.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
_ = Enum.two(3 > 4 ? 3 : 4) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((3, 4))
_ = Enum.labeledTuple(x: 3, 4) // expected-error {{enum case 'labeledTuple' expects a single parameter of type '(Int, Int)'}}
_ = Enum.labeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
_ = Enum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
_ = Enum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
struct Generic<T> {}
extension Generic {
func generic(_ x: T) {}
func genericLabeled(x: T) {}
func genericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'genericTwo' declared here}}
func genericTuple(_ x: (T, T)) {}
}
do {
let s = Generic<Double>()
s.generic(3.0)
s.generic((3.0))
s.genericLabeled(x: 3.0)
s.genericLabeled(x: (3.0))
s.genericTwo(3.0, 4.0)
s.genericTwo((3.0, 4.0)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{25-26=}}
s.genericTuple(3.0, 4.0) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{26-26=)}}
s.genericTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(3.0, 4.0) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{24-24=)}}
sTwo.generic((3.0, 4.0))
sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'genericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.genericLabeled(x: (3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}}
sTwo.generic((a, b))
sTwo.generic(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}}
sTwo.generic((a, b))
sTwo.generic(d)
}
extension Generic {
mutating func mutatingGeneric(_ x: T) {}
mutating func mutatingGenericLabeled(x: T) {}
mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple(_ x: (T, T)) {}
}
do {
var s = Generic<Double>()
s.mutatingGeneric(3.0)
s.mutatingGeneric((3.0))
s.mutatingGenericLabeled(x: 3.0)
s.mutatingGenericLabeled(x: (3.0))
s.mutatingGenericTwo(3.0, 4.0)
s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {24-25=}} {{33-34=}}
s.mutatingGenericTuple(3.0, 4.0) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}}
s.mutatingGenericTuple((3.0, 4.0))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}}
sTwo.mutatingGeneric((3.0, 4.0))
sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'mutatingGenericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.mutatingGenericLabeled(x: (3.0, 4.0))
}
do {
var s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {24-25=}} {{29-30=}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
extension Generic {
var genericFunction: (T) -> () { return generic }
var genericFunctionTwo: (T, T) -> () { return genericTwo } // expected-note 3 {{'genericFunctionTwo' declared here}}
var genericFunctionTuple: ((T, T)) -> () { return genericTuple }
}
do {
let s = Generic<Double>()
s.genericFunction(3.0)
s.genericFunction((3.0))
s.genericFunctionTwo(3.0, 4.0)
s.genericFunctionTwo((3.0, 4.0)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{33-34=}}
s.genericFunctionTuple(3.0, 4.0) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}}
s.genericFunctionTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(3.0, 4.0) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}}
sTwo.genericFunction((3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.genericFunctionTuple(a, b) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.genericFunctionTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.genericFunction((a, b))
sTwo.genericFunction(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.genericFunctionTuple(a, b) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.genericFunctionTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.genericFunction((a, b))
sTwo.genericFunction(d)
}
struct GenericInit<T> {
init(_ x: T) {}
}
struct GenericInitLabeled<T> {
init(x: T) {}
}
struct GenericInitTwo<T> {
init(_ x: T, _ y: T) {} // expected-note 10 {{'init(_:_:)' declared here}}
}
struct GenericInitTuple<T> {
init(_ x: (T, T)) {}
}
struct GenericInitLabeledTuple<T> {
init(x: (T, T)) {}
}
do {
_ = GenericInit(3, 4) // expected-error {{extra argument in call}}
_ = GenericInit((3, 4))
_ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled(x: (3, 4))
_ = GenericInitTwo(3, 4)
_ = GenericInitTwo((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}}
_ = GenericInitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((3, 4))
_ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}}
_ = GenericInitLabeledTuple(x: (3, 4))
}
do {
_ = GenericInit<(Int, Int)>(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInit<(Int, Int)>((3, 4))
_ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInitLabeled<(Int, Int)>(x: (3, 4))
_ = GenericInitTwo<Int>(3, 4)
_ = GenericInitTwo<Int>((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}}
_ = GenericInitTuple<Int>(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((3, 4))
_ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInitLabeledTuple<Int>(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}}
_ = GenericInitTwo(c) // expected-error {{initializer expects 2 separate arguments}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit<(Int, Int)>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}}
_ = GenericInitTwo<Int>(c) // expected-error {{initializer expects 2 separate arguments}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}}
_ = GenericInitTwo(c) // expected-error {{initializer expects 2 separate arguments}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit<(Int, Int)>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}}
_ = GenericInitTwo<Int>(c) // expected-error {{initializer expects 2 separate arguments}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
struct GenericSubscript<T> {
subscript(_ x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptLabeled<T> {
subscript(x x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTwo<T> {
subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}}
}
struct GenericSubscriptLabeledTuple<T> {
subscript(x x: (T, T)) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTuple<T> {
subscript(_ x: (T, T)) -> Int { get { return 0 } set { } }
}
do {
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{18-18=)}}
_ = s1[(3.0, 4.0)]
let s1a = GenericSubscriptLabeled<(Double, Double)>()
_ = s1a [x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{14-14=(}} {{23-23=)}}
_ = s1a [x: (3.0, 4.0)]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[3.0, 4.0]
_ = s2[(3.0, 4.0)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{19-20=}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{18-18=)}}
_ = s3[(3.0, 4.0)]
let s3a = GenericSubscriptLabeledTuple<Double>()
_ = s3a[x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{13-13=(}} {{22-22=)}}
_ = s3a[x: (3.0, 4.0)]
}
do {
let a = 3.0
let b = 4.0
let d = (a, b)
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}}
_ = s1[(a, b)]
_ = s1[d]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
_ = s2[d] // expected-error {{subscript expects 2 separate arguments}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}}
_ = s3[(a, b)]
_ = s3[d]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3.0 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4.0 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}}
_ = s1[(a, b)]
_ = s1[d]
var s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
_ = s2[d] // expected-error {{subscript expects 2 separate arguments}}
var s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}}
_ = s3[(a, b)]
_ = s3[d]
}
enum GenericEnum<T> {
case one(T)
case labeled(x: T)
case two(T, T) // expected-note 10 {{'two' declared here}}
case tuple((T, T))
}
do {
_ = GenericEnum.one(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.one((3, 4))
_ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled(x: (3, 4))
_ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum.two(3, 4)
_ = GenericEnum.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}}
_ = GenericEnum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((3, 4))
}
do {
_ = GenericEnum<(Int, Int)>.one(3, 4) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((3, 4))
_ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled(x: (3, 4))
_ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum<Int>.two(3, 4)
_ = GenericEnum<Int>.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}}
_ = GenericEnum<Int>.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum.one(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}}
_ = GenericEnum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}}
_ = GenericEnum<Int>.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericEnum.one(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}}
_ = GenericEnum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}}
_ = GenericEnum<Int>.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
protocol Protocol {
associatedtype Element
}
extension Protocol {
func requirement(_ x: Element) {}
func requirementLabeled(x: Element) {}
func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 3 {{'requirementTwo' declared here}}
func requirementTuple(_ x: (Element, Element)) {}
}
struct GenericConforms<T> : Protocol {
typealias Element = T
}
do {
let s = GenericConforms<Double>()
s.requirement(3.0)
s.requirement((3.0))
s.requirementLabeled(x: 3.0)
s.requirementLabeled(x: (3.0))
s.requirementTwo(3.0, 4.0)
s.requirementTwo((3.0, 4.0)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{29-30=}}
s.requirementTuple(3.0, 4.0) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{30-30=)}}
s.requirementTuple((3.0, 4.0))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(3.0, 4.0) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{28-28=)}}
sTwo.requirement((3.0, 4.0))
sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{instance method 'requirementLabeled' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{29-29=(}} {{38-38=)}}
sTwo.requirementLabeled(x: (3.0, 4.0))
}
do {
let s = GenericConforms<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{25-26=}}
s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{26-26=)}}
s.requirementTuple((a, b))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{24-24=)}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
do {
var s = GenericConforms<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{25-26=}}
s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{26-26=)}}
s.requirementTuple((a, b))
var sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{24-24=)}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
extension Protocol {
func takesClosure(_ fn: (Element) -> ()) {}
func takesClosureTwo(_ fn: (Element, Element) -> ()) {}
func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {}
}
do {
let s = GenericConforms<Double>()
s.takesClosure({ _ = $0 })
s.takesClosure({ x in })
s.takesClosure({ (x: Double) in })
s.takesClosureTwo({ _ = $0 }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ x in }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ (x: (Double, Double)) in }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ _ = $0; _ = $1 })
s.takesClosureTwo({ (x, y) in })
s.takesClosureTwo({ (x: Double, y:Double) in })
s.takesClosureTuple({ _ = $0 })
s.takesClosureTuple({ x in })
s.takesClosureTuple({ (x: (Double, Double)) in })
s.takesClosureTuple({ _ = $0; _ = $1 })
s.takesClosureTuple({ (x, y) in })
s.takesClosureTuple({ (x: Double, y:Double) in })
let sTwo = GenericConforms<(Double, Double)>()
sTwo.takesClosure({ _ = $0 })
sTwo.takesClosure({ x in })
sTwo.takesClosure({ (x: (Double, Double)) in })
sTwo.takesClosure({ _ = $0; _ = $1 })
sTwo.takesClosure({ (x, y) in })
sTwo.takesClosure({ (x: Double, y: Double) in })
}
do {
let _: ((Int, Int)) -> () = { _ = $0 }
let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) }
let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) }
let _: ((Int, Int)) -> () = { _ = ($0, $1) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}}
let _: ((Int, Int)) -> () = { t, u in _ = (t, u) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{41-41=let (t, u) = arg; }}
let _: (Int, Int) -> () = { _ = $0 } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { _ = ($0.0, $0.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { t in _ = (t.0, t.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { _ = ($0, $1) }
let _: (Int, Int) -> () = { t, u in _ = (t, u) }
}
// rdar://problem/28952837 - argument labels ignored when calling function
// with single 'Any' parameter
func takesAny(_: Any) {}
enum HasAnyCase {
case any(_: Any)
}
do {
let fn: (Any) -> () = { _ in }
fn(123)
fn(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
takesAny(123)
takesAny(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
_ = HasAnyCase.any(123)
_ = HasAnyCase.any(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
}
// rdar://problem/29739905 - protocol extension methods on Array had
// ParenType sugar stripped off the element type
func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()],
f2: [(Bool, Bool) -> ()],
c: Bool) {
let p = (c, c)
f1.forEach { block in
block(p)
block((c, c))
block(c, c) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}} {{11-11=(}} {{15-15=)}}
}
f2.forEach { block in
// expected-note@-1 2{{'block' declared here}}
block(p) // expected-error {{parameter 'block' expects 2 separate arguments}}
block((c, c)) // expected-error {{parameter 'block' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{11-12=}} {{16-17=}}
block(c, c)
}
f2.forEach { (block: ((Bool, Bool)) -> ()) in
// expected-error@-1 {{cannot convert value of type '(((Bool, Bool)) -> ()) -> ()' to expected argument type '(@escaping (Bool, Bool) -> ()) throws -> Void'}}
block(p)
block((c, c))
block(c, c)
}
f2.forEach { (block: (Bool, Bool) -> ()) in
// expected-note@-1 2{{'block' declared here}}
block(p) // expected-error {{parameter 'block' expects 2 separate arguments}}
block((c, c)) // expected-error {{parameter 'block' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{11-12=}} {{16-17=}}
block(c, c)
}
}
// expected-error@+1 {{cannot create a single-element tuple with an element label}}
func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) {
// TODO: Error could be improved.
// expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}}
completion((didAdjust: true))
}
// SR-4378
final public class MutableProperty<Value> {
public init(_ initialValue: Value) {}
}
enum DataSourcePage<T> {
case notLoaded
}
let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: .notLoaded,
totalCount: 0
))
let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: DataSourcePage.notLoaded,
totalCount: 0
))
let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: DataSourcePage<Int>.notLoaded,
totalCount: 0
))
// SR-4745
let sr4745 = [1, 2]
let _ = sr4745.enumerated().map { (count, element) in "\(count): \(element)" }
// SR-4738
let sr4738 = (1, (2, 3))
[sr4738].map { (x, (y, z)) -> Int in x + y + z }
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{20-26=arg1}} {{38-38=let (y, z) = arg1; }}
// expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{20-20=_: }}
// expected-error@-3 {{use of undeclared type 'y'}}
// expected-error@-4 {{use of undeclared type 'z'}}
// rdar://problem/31892961
let r31892961_1 = [1: 1, 2: 2]
r31892961_1.forEach { (k, v) in print(k + v) }
let r31892961_2 = [1, 2, 3]
let _: [Int] = r31892961_2.enumerated().map { ((index, val)) in
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{48-60=arg0}} {{3-3=\n let (index, val) = arg0\n }}
// expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{48-48=_: }}
// expected-error@-3 {{use of undeclared type 'index'}}
// expected-error@-4 {{use of undeclared type 'val'}}
val + 1
}
let r31892961_3 = (x: 1, y: 42)
_ = [r31892961_3].map { (x: Int, y: Int) in x + y }
_ = [r31892961_3].map { (x, y: Int) in x + y }
let r31892961_4 = (1, 2)
_ = [r31892961_4].map { x, y in x + y }
let r31892961_5 = (x: 1, (y: 2, (w: 3, z: 4)))
[r31892961_5].map { (x: Int, (y: Int, (w: Int, z: Int))) in x + y } // expected-note {{'x' declared here}}
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-56=arg1}} {{61-61=let (y, (w, z)) = arg1; }}
// expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{30-30=_: }}
// expected-error@-3{{use of unresolved identifier 'y'; did you mean 'x'?}}
let r31892961_6 = (x: 1, (y: 2, z: 4))
[r31892961_6].map { (x: Int, (y: Int, z: Int)) in x + y } // expected-note {{'x' declared here}}
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-46=arg1}} {{51-51=let (y, z) = arg1; }}
// expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{30-30=_: }}
// expected-error@-3{{use of unresolved identifier 'y'; did you mean 'x'?}}
// rdar://problem/32214649 -- these regressed in Swift 4 mode
// with SE-0110 because of a problem in associated type inference
func r32214649_1<X,Y>(_ a: [X], _ f: (X)->Y) -> [Y] {
return a.map(f)
}
func r32214649_2<X>(_ a: [X], _ f: (X) -> Bool) -> [X] {
return a.filter(f)
}
func r32214649_3<X>(_ a: [X]) -> [X] {
return a.filter { _ in return true }
}
// rdar://problem/32301091 - [SE-0110] causes errors when passing a closure with a single underscore to a block accepting multiple parameters
func rdar32301091_1(_ :((Int, Int) -> ())!) {}
rdar32301091_1 { _ in }
// expected-error@-1 {{cannot convert value of type '(_) -> ()' to expected argument type '((Int, Int) -> ())?'}}
func rdar32301091_2(_ :(Int, Int) -> ()) {}
rdar32301091_2 { _ in }
// expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }}
rdar32301091_2 { x in }
// expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,<#arg#> }}
func rdar32875953() {
let myDictionary = ["hi":1]
myDictionary.forEach {
print("\($0) -> \($1)")
}
myDictionary.forEach { key, value in
print("\(key) -> \(value)")
}
myDictionary.forEach { (key, value) in
print("\(key) -> \(value)")
}
let array1 = [1]
let array2 = [2]
_ = zip(array1, array2).map(+)
}
struct SR_5199 {}
extension Sequence where Iterator.Element == (key: String, value: String?) {
func f() -> [SR_5199] {
return self.map { (key, value) in
SR_5199() // Ok
}
}
}
func rdar33043106(_ records: [(Int)], _ other: [((Int))]) -> [Int] {
let x: [Int] = records.map { _ in
let i = 1
return i
}
let y: [Int] = other.map { _ in
let i = 1
return i
}
return x + y
}
func itsFalse(_: Int) -> Bool? {
return false
}
func rdar33159366(s: AnySequence<Int>) {
_ = s.compactMap(itsFalse)
let a = Array(s)
_ = a.compactMap(itsFalse)
}
func sr5429<T>(t: T) {
_ = AnySequence([t]).first(where: { (t: T) in true })
}
extension Concrete {
typealias T = (Int, Int)
typealias F = (T) -> ()
func opt1(_ fn: (((Int, Int)) -> ())?) {}
func opt2(_ fn: (((Int, Int)) -> ())??) {}
func opt3(_ fn: (((Int, Int)) -> ())???) {}
func optAliasT(_ fn: ((T) -> ())?) {}
func optAliasF(_ fn: F?) {}
}
extension Generic {
typealias F = (T) -> ()
func opt1(_ fn: (((Int, Int)) -> ())?) {}
func opt2(_ fn: (((Int, Int)) -> ())??) {}
func opt3(_ fn: (((Int, Int)) -> ())???) {}
func optAliasT(_ fn: ((T) -> ())?) {}
func optAliasF(_ fn: F?) {}
}
func rdar33239714() {
Concrete().opt1 { x, y in }
Concrete().opt1 { (x, y) in }
Concrete().opt2 { x, y in }
Concrete().opt2 { (x, y) in }
Concrete().opt3 { x, y in }
Concrete().opt3 { (x, y) in }
Concrete().optAliasT { x, y in }
Concrete().optAliasT { (x, y) in }
Concrete().optAliasF { x, y in }
Concrete().optAliasF { (x, y) in }
Generic<(Int, Int)>().opt1 { x, y in }
Generic<(Int, Int)>().opt1 { (x, y) in }
Generic<(Int, Int)>().opt2 { x, y in }
Generic<(Int, Int)>().opt2 { (x, y) in }
Generic<(Int, Int)>().opt3 { x, y in }
Generic<(Int, Int)>().opt3 { (x, y) in }
Generic<(Int, Int)>().optAliasT { x, y in }
Generic<(Int, Int)>().optAliasT { (x, y) in }
Generic<(Int, Int)>().optAliasF { x, y in }
Generic<(Int, Int)>().optAliasF { (x, y) in }
}
// rdar://problem/35198459 - source-compat-suite failure: Moya (toType->hasUnresolvedType() && "Should have handled this above"
do {
func foo(_: (() -> Void)?) {}
func bar() -> ((()) -> Void)? { return nil }
foo(bar()) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}}
}
// https://bugs.swift.org/browse/SR-6509
public extension Optional {
func apply<Result>(_ transform: ((Wrapped) -> Result)?) -> Result? {
return self.flatMap { value in
transform.map { $0(value) }
}
}
func apply<Value, Result>(_ value: Value?) -> Result?
where Wrapped == (Value) -> Result {
return value.apply(self)
}
}
// https://bugs.swift.org/browse/SR-6837
// FIXME: Can't overlaod local functions so these must be top-level
func takePairOverload(_ pair: (Int, Int?)) {} // expected-note {{found this candidate}}
func takePairOverload(_: () -> ()) {} // expected-note {{found this candidate}}
do {
func takeFn(fn: (_ i: Int, _ j: Int?) -> ()) {}
func takePair(_ pair: (Int, Int?)) {}
takeFn(fn: takePair) // expected-error {{cannot convert value of type '((Int, Int?)) -> ()' to expected argument type '(Int, Int?) -> ()'}}
takeFn(fn: takePairOverload) // expected-error {{ambiguous reference to member 'takePairOverload'}}
takeFn(fn: { (pair: (Int, Int?)) in } ) // Disallow for -swift-version 4 and later
// expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}}
takeFn { (pair: (Int, Int?)) in } // Disallow for -swift-version 4 and later
// expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// https://bugs.swift.org/browse/SR-6796
do {
func f(a: (() -> Void)? = nil) {}
func log<T>() -> ((T) -> Void)? { return nil }
f(a: log() as ((()) -> Void)?) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}}
func logNoOptional<T>() -> (T) -> Void { }
f(a: logNoOptional() as ((()) -> Void)) // expected-error {{cannot convert value of type '(()) -> Void' to expected argument type '(() -> Void)?'}}
func g() {}
g(()) // expected-error {{argument passed to call that takes no arguments}}
func h(_: ()) {} // expected-note {{'h' declared here}}
h() // expected-error {{missing argument for parameter #1 in call}}
}
// https://bugs.swift.org/browse/SR-7191
class Mappable<T> {
init(_: T) { }
func map<U>(_ body: (T) -> U) -> U { fatalError() }
}
let x = Mappable(())
_ = x.map { (_: Void) in return () }
_ = x.map { (_: ()) in () }
// https://bugs.swift.org/browse/SR-9470
do {
func f(_: Int...) {}
let _ = [(1, 2, 3)].map(f) // expected-error {{cannot invoke 'map' with an argument list of type '(@escaping (Int...) -> ())'}}
}
// rdar://problem/48443263 - cannot convert value of type '() -> Void' to expected argument type '(_) -> Void'
protocol P_48443263 {
associatedtype V
}
func rdar48443263() {
func foo<T : P_48443263>(_: T, _: (T.V) -> Void) {}
struct S1 : P_48443263 {
typealias V = Void
}
struct S2: P_48443263 {
typealias V = Int
}
func bar(_ s1: S1, _ s2: S2, _ fn: () -> Void) {
foo(s1, fn) // Ok because s.V is Void
foo(s2, fn) // expected-error {{cannot convert value of type '() -> Void' to expected argument type '(S2.V) -> Void' (aka '(Int) -> ()')}}
}
}
func autoclosureSplat() {
func takeFn<T>(_: (T) -> ()) {}
takeFn { (fn: @autoclosure () -> Int) in }
// This type checks because we find a solution T:= @escaping () -> Int and
// wrap the closure in a function conversion.
takeFn { (fn: @autoclosure () -> Int, x: Int) in }
// expected-error@-1 {{contextual closure type '(@escaping () -> Int) -> ()' expects 1 argument, but 2 were used in closure body}}
takeFn { (fn: @autoclosure @escaping () -> Int) in }
// FIXME: It looks like matchFunctionTypes() does not check @autoclosure at all.
// Perhaps this is intentional, but we should document it eventually. In the
// interim, this test serves as "documentation"; if it fails, please investigate why
// instead of changing the test.
takeFn { (fn: @autoclosure @escaping () -> Int, x: Int) in }
// expected-error@-1 {{contextual closure type '(@escaping () -> Int) -> ()' expects 1 argument, but 2 were used in closure body}}
}
func noescapeSplat() {
func takesFn<T>(_ fn: (T) -> ()) -> T {}
func takesEscaping(_: @escaping () -> Int) {}
do {
let t = takesFn { (fn: () -> Int) in }
takesEscaping(t)
// This type checks because we find a solution T:= (@escaping () -> Int).
}
do {
let t = takesFn { (fn: () -> Int, x: Int) in }
// expected-error@-1 {{converting non-escaping value to 'T' may allow it to escape}}
takesEscaping(t.0)
}
}
| 36.679683 | 253 | 0.640689 |
5d776c9b31b5714321edef63c6e93ba589595bb3 | 128 | import Foundation
public enum SWAPIError: Error {
case missingData
case unknown
case statusCode(Int?)
case parsingError
} | 12.8 | 31 | 0.78125 |
5be7f1a62e7657b7b2acf5875f02a1c3449a7315 | 323 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
tln(Range<T where h
protocol a {
typealias e: b, U, y)
var b) -> {
d<T..advance(T> Any, g(")
class func b.j
| 24.846154 | 87 | 0.705882 |
0a87bc76f124982dbb86dea7bef9a3536ae67c7c | 150 | import XCTest
#if !os(macOS)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(ModelResponseTests.allTests),
]
}
#endif | 16.666667 | 46 | 0.66 |
ff36a20dff71cbed28e3979ef4b18b6a9c2e04f7 | 1,228 | //
// DemoUITests.swift
// DemoUITests
//
// Created by Atit Modi on 4/22/18.
// Copyright © 2018 Atit Modi. All rights reserved.
//
import XCTest
class DemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.189189 | 182 | 0.65798 |
0eb3b7b0e4afb9889dfb25e9ac64966aa84031a4 | 468 | //
// LogsCollector.swift
// CrowdinSDK
//
// Created by Serhii Londar on 11.08.2020.
//
import Foundation
class CrowdinLogsCollector {
static let shared = CrowdinLogsCollector()
fileprivate var _logs = Atomic<[CrowdinLog]>([])
var logs: [CrowdinLog] {
return _logs.value
}
func add(log: CrowdinLog) {
_logs.mutate { $0.append(log) }
}
func clear() {
_logs.mutate { $0.removeAll() }
}
}
| 17.333333 | 52 | 0.58547 |
c1c167ee02790c9f44c6895739692cf658fc8a76 | 3,211 | //
// DetailView.swift
// Scrumdinger
//
// Created by Muhammad Fawwaz Mayda on 28/08/21.
//
import SwiftUI
struct DetailView: View {
@Binding var scrum: DailyScrum
@State var data: DailyScrum.Data = DailyScrum.Data()
@State var isPresented = false
var body: some View {
List {
Section(header: Text("Meeting Info")) {
NavigationLink(
destination: MeetingView(scrum: $scrum)){
Label("Start meeting", systemImage: "timer")
.font(.headline)
.foregroundColor(.accentColor)
.accessibility(label: Text("Start Meeting"))
}
HStack {
Label("Length", systemImage: "clock")
.accessibility(label: Text("Meeting Length"))
Spacer()
Text("\(scrum.lengthInMinutes) minutes")
}
HStack {
Label("Color",systemImage: "paintpalette")
Spacer()
Image(systemName: "checkmark.circle.fill")
.foregroundColor(scrum.color)
}.accessibilityElement(children: .ignore)
}
Section(header: Text("Attendees")) {
ForEach(scrum.attendees, id: \.self) { attendee in
Label(attendee, systemImage: "person")
.accessibility(label: Text("Person"))
.accessibility(value: Text(attendee))
}
}
Section(header: Text("History")) {
if scrum.history.isEmpty {
Label("No meetings yet", systemImage: "calendar.badge.exclamationmark")
}
ForEach(scrum.history) { history in
NavigationLink(
destination: HistoryView(history: history),
label: {
HStack {
Image(systemName: "calendar")
Text(history.date,style: .date)
}
})
}
}
}.listStyle(InsetGroupedListStyle())
.navigationTitle(Text(scrum.title))
.navigationBarItems(trailing: Button("Edit", action: {
isPresented = true
data = scrum.data
}))
.fullScreenCover(isPresented: $isPresented, content: {
NavigationView {
EditView(scrumData: $data)
.navigationTitle(scrum.title)
.navigationBarItems(leading: Button("Cancel", action: {
isPresented = false
}), trailing: Button("Done", action: {
isPresented = false
scrum.update(from: data)
}))
}
})
}
}
struct DetailView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
DetailView(scrum: .constant(DailyScrum.data[0]))
}
}
}
| 35.285714 | 91 | 0.461538 |
20d4321ed921e04b4865ae1de5dda08922b3810c | 242 | //
// GeoAPIManagerError.swift
// PACECloudSDK
//
// Created by PACE Telematics GmbH.
//
import Foundation
enum GeoApiManagerError: Error {
case invalidSpeed
case requestCancelled
case invalidResponse
case unknownError
}
| 15.125 | 36 | 0.727273 |
64beb2ca94021947e865cb4904a30086b882a151 | 124 | import XCTest
import SwiftMatrixTests
var tests = [XCTestCaseEntry]()
tests += SwiftMatrixTests.allTests()
XCTMain(tests)
| 15.5 | 36 | 0.790323 |
03cee245b6809c4e7d9dd4277b3bbb226ab827f4 | 491 | //
// ThemeManagerProtocol.swift
// SwiftJsonThemeManager
//
// Created by Felipe Florencio Garcia on 26/12/18.
// Copyright © 2018 Felipe Florencio Garcia. All rights reserved.
//
import Foundation
@objc
public protocol ThemedView {
func applyUIAppearance(with theme: Theme?, avoid thisViews: [Any]?)
}
// Customize appearance using closure
public typealias ThemedViewCustomTheme = (Theme?) -> Void
public protocol CustomTheme {
var customTheme: ThemedViewCustomTheme { get }
}
| 23.380952 | 71 | 0.753564 |
2311c243220c5752cc05add890aa43ded4da2737 | 15,840 | // Upload.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension Manager {
fileprivate enum Uploadable {
case data(Foundation.URLRequest, Foundation.Data)
case file(Foundation.URLRequest, URL)
case stream(Foundation.URLRequest, InputStream)
}
fileprivate func upload(_ uploadable: Uploadable) -> Request {
var uploadTask: URLSessionUploadTask!
var HTTPBodyStream: InputStream?
switch uploadable {
case .data(let request, let data):
queue.sync {
uploadTask = self.session.uploadTask(with: request, from: data)
}
case .file(let request, let fileURL):
queue.sync {
uploadTask = self.session.uploadTask(with: request, fromFile: fileURL)
}
case .stream(let request, let stream):
queue.sync {
uploadTask = self.session.uploadTask(withStreamedRequest: request)
}
HTTPBodyStream = stream
}
let request = Request(session: session, task: uploadTask)
if HTTPBodyStream != nil {
request.delegate.taskNeedNewBodyStream = { _, _ in
return HTTPBodyStream
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: File
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- parameter file: The file to upload
- returns: The created upload request.
*/
public func upload(_ URLRequest: URLRequestConvertible, file: URL) -> Request {
return upload(.file(URLRequest.URLRequest as URLRequest, file))
}
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter file: The file to upload
- returns: The created upload request.
*/
public func upload(
_ method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
file: URL)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
return upload(mutableURLRequest, file: file)
}
// MARK: Data
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request.
- parameter data: The data to upload.
- returns: The created upload request.
*/
public func upload(_ URLRequest: URLRequestConvertible, data: Data) -> Request {
return upload(.data(URLRequest.URLRequest as URLRequest, data))
}
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter data: The data to upload
- returns: The created upload request.
*/
public func upload(
_ method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
data: Data)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
return upload(mutableURLRequest, data: data)
}
// MARK: Stream
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request.
- parameter stream: The stream to upload.
- returns: The created upload request.
*/
public func upload(_ URLRequest: URLRequestConvertible, stream: InputStream) -> Request {
return upload(.stream(URLRequest.URLRequest as URLRequest, stream))
}
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter stream: The stream to upload.
- returns: The created upload request.
*/
public func upload(
_ method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
stream: InputStream)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
return upload(mutableURLRequest, stream: stream)
}
// MARK: MultipartFormData
/// Default memory threshold used when encoding `MultipartFormData`.
public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024
/**
Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as
associated values.
- Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with
streaming information.
- Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding
error.
*/
public enum MultipartFormDataEncodingResult {
case success(request: Request, streamingFromDisk: Bool, streamFileURL: URL?)
case failure(Error)
}
/**
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
used for larger payloads such as video content.
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
technique was used.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter headers: The HTTP headers. `nil` by default.
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
`MultipartFormDataEncodingMemoryThreshold` by default.
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
*/
public func upload(
_ method: Method,
_ URLString: URLStringConvertible,
headers: [String: String]? = nil,
multipartFormData: (MultipartFormData) -> Void,
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
return upload(
mutableURLRequest,
multipartFormData: multipartFormData,
encodingMemoryThreshold: encodingMemoryThreshold,
encodingCompletion: encodingCompletion
)
}
/**
Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request.
It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
used for larger payloads such as video content.
The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
technique was used.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request.
- parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
- parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
`MultipartFormDataEncodingMemoryThreshold` by default.
- parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
*/
public func upload(
_ URLRequest: URLRequestConvertible,
multipartFormData: @escaping (MultipartFormData) -> Void,
encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?)
{
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async {
let formData = MultipartFormData()
multipartFormData(formData)
let URLRequestWithContentType = URLRequest.URLRequest
URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")
let isBackgroundSession = self.session.configuration.identifier != nil
if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession {
do {
let data = try formData.encode()
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(URLRequestWithContentType, data: data as Data),
streamingFromDisk: false,
streamFileURL: nil
)
DispatchQueue.main.async {
encodingCompletion?(encodingResult)
}
} catch {
DispatchQueue.main.async {
encodingCompletion?(.failure(error as NSError))
}
}
} else {
let fileManager = FileManager.default
let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let directoryURL = tempDirectoryURL.appendingPathComponent("com.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
do {
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
try formData.writeEncodedDataToDisk(fileURL)
DispatchQueue.main.async {
let encodingResult = MultipartFormDataEncodingResult.success(
request: self.upload(URLRequestWithContentType, file: fileURL),
streamingFromDisk: true,
streamFileURL: fileURL
)
encodingCompletion?(encodingResult)
}
} catch {
DispatchQueue.main.async {
encodingCompletion?(.failure(error as NSError))
}
}
}
}
}
}
// MARK: -
extension Request {
// MARK: - UploadTaskDelegate
class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: URLSessionUploadTask? { return task as? URLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
var taskDidSendBodyData: ((Foundation.URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
// MARK: Delegate Methods
func URLSession(
_ session: Foundation.URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
progress.totalUnitCount = totalBytesExpectedToSend
progress.completedUnitCount = totalBytesSent
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
}
}
| 42.466488 | 121 | 0.649432 |
20db983dd75753db3ce7a4fe9dc9a22d6e0151fc | 3,939 | #if os(macOS)
import Cocoa
public typealias Rect = NSRect
#else
import UIKit
public typealias Rect = CGRect
#endif
extension View {
/// Swizzle initializers for views if application is compiled in debug mode.
static func _swizzleViews() {
#if DEBUG
DispatchQueue.once(token: "com.zenangst.Vaccine.\(#function)") {
let originalSelector = #selector(View.init(frame:))
let swizzledSelector = #selector(View.init(vaccineFrame:))
Swizzling.swizzle(View.self,
originalSelector: originalSelector,
swizzledSelector: swizzledSelector)
}
#endif
}
/// Recursively gather all subviews into a single collection.
///
/// - Returns: A collection of views.
func subviewsRecursive() -> [View] {
return subviews + subviews.flatMap { $0.subviewsRecursive() }
}
/// Swizzled init method for view.
/// This method is used to add a responder for InjectionIII notifications.
///
/// - Parameter frame: The frame rectangle for the view, measured in points.
@objc public convenience init(vaccineFrame frame: Rect) {
self.init(vaccineFrame: frame)
let selector = #selector(View.vaccine_view_injected(_:))
if responds(to: selector) {
addInjection(with: selector, invoke: nil)
}
}
/// Respond to InjectionIII notifications.
/// The notification will be validate to verify that the current view
/// was injected. If the view responds to `loadView`, that method
/// will be invoked after the layout constraints have been deactivated.
/// See `invalidateIfNeededLayoutConstraints` for more information about
/// how layout constraints are handled via convention.
///
/// - Parameter notification: An InjectionIII notification.
@objc func vaccine_view_injected(_ notification: Notification) {
let selector = _Selector("loadView")
let closure = { [weak self] in
self?.invalidateIfNeededLayoutConstraints()
self?.perform(selector)
}
if responds(to: selector), Injection.objectWasInjected(self, in: notification) {
#if os(macOS)
closure()
#else
guard Injection.animations else { closure(); return }
let options: UIView.AnimationOptions = [.allowAnimatedContent,
.beginFromCurrentState,
.layoutSubviews]
UIView.animate(withDuration: 0.3, delay: 0.0, options: options, animations: {
closure()
}, completion: nil)
#endif
}
}
/// Create selector using string. This method is meant to silence the warning
/// that occure when trying to use `Selector` instead of `#selector`.
///
/// - Parameter string: The key that should be used as selector.
/// - Returns: A selector constructed from the given string parameter.
private func _Selector(_ string: String) -> Selector {
return Selector(string)
}
/// Invalidate layout constraints if `.layoutConstraints` can be resolved.
/// If `.layoutConstraints` cannot be resolved, then it will recursively deactivate
/// constraints on all subviews.
private func invalidateIfNeededLayoutConstraints() {
let key = "layoutConstraints"
if responds(to: _Selector(key)), let layoutConstraints = value(forKey: key) as? [NSLayoutConstraint] {
NSLayoutConstraint.deactivate(layoutConstraints)
} else {
let removeConstraints: (View, NSLayoutConstraint) -> Void = { parentView, constraint in
if let subview = constraint.firstItem, subview.superview == parentView {
NSLayoutConstraint.deactivate([constraint])
parentView.removeConstraint(constraint)
}
}
#if !os(macOS)
if let cell = self as? UITableViewCell {
cell.contentView.constraints.forEach { removeConstraints(cell.contentView, $0) }
}
#endif
constraints.forEach { removeConstraints(self, $0) }
}
}
}
| 37.160377 | 106 | 0.67149 |
289a0d1c59fdd430d4c0df00a31e0441659cd280 | 1,078 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// An optional type that allows implicit member access.
///
/// The `ImplicitlyUnwrappedOptional` type is deprecated. To create an optional
/// value that is implicitly unwrapped, place an exclamation mark (`!`) after
/// the type that you want to denote as optional.
///
/// // An implicitly unwrapped optional integer
/// let guaranteedNumber: Int! = 6
///
/// // An optional integer
/// let possibleNumber: Int? = 5
@available(*, unavailable, renamed: "Optional")
public typealias ImplicitlyUnwrappedOptional<Wrapped> = Optional<Wrapped>
| 41.461538 | 80 | 0.615028 |
ed1cf859070dc11366b0240ef8e63435444ac456 | 5,062 | /// Copyright (c) 2021 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// 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
struct AcronymRequest {
let resource: URL
init(acronymID: UUID) {
let resourceString = "http://localhost:8080/api/acronyms/\(acronymID)"
guard let resourceURL = URL(string: resourceString) else {
fatalError("Unable to createURL")
}
self.resource = resourceURL
}
func getUser(
completion: @escaping (
Result<User, ResourceRequestError>
) -> Void
) {
let url = resource.appendingPathComponent("user")
let dataTask = URLSession.shared.dataTask(with: url) { data, _, _ in
guard let jsonData = data else {
completion(.failure(.noData))
return
}
do {
let user = try JSONDecoder().decode(User.self, from: jsonData)
completion(.success(user))
} catch {
completion(.failure(.decodingError))
}
}
dataTask.resume()
}
func getCategories(completion: @escaping (Result<[Category], ResourceRequestError>) -> Void) {
let url = resource.appendingPathComponent("categories")
let dataTask = URLSession.shared.dataTask(with: url) { data, _, _ in
guard let jsonData = data else {
completion(.failure(.noData))
return
}
do {
let categories = try JSONDecoder().decode([Category].self, from: jsonData)
completion(.success(categories))
} catch {
completion(.failure(.decodingError))
}
}
dataTask.resume()
}
func update(
with updateData: CreateAcronymData,
completion: @escaping (Result<Acronym, ResourceRequestError>) -> Void
) {
do {
var urlRequest = URLRequest(url: resource)
urlRequest.httpMethod = "PUT"
urlRequest.httpBody = try JSONEncoder().encode(updateData)
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, response, _ in
guard
let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200,
let jsonData = data
else {
completion(.failure(.noData))
return
}
do {
let acronym = try JSONDecoder().decode(Acronym.self, from: jsonData)
completion(.success(acronym))
} catch {
completion(.failure(.decodingError))
}
}
dataTask.resume()
} catch {
completion(.failure(.encodingError))
}
}
func delete() {
var urlRequest = URLRequest(url: resource)
urlRequest.httpMethod = "DELETE"
let dataTask = URLSession.shared.dataTask(with: urlRequest)
dataTask.resume()
}
func add(
category: Category,
completion: @escaping (Result<Void, CategoryAddError>) -> Void
) {
guard let categoryID = category.id else {
completion(.failure(.noID))
return
}
let url = resource
.appendingPathComponent("categories")
.appendingPathComponent("\(categoryID)")
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let dataTask = URLSession.shared
.dataTask(with: urlRequest) { _, response, _ in
guard
let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 201
else {
completion(.failure(.invalidResponse))
return
}
completion(.success(()))
}
dataTask.resume()
}
}
| 34.671233 | 96 | 0.665152 |
ac80c172a8d55f04e1ff350b2674b217c0a1fbc4 | 8,238 | //
// AppDelegate.swift
// SidebarMenu
//
// Created by Simon Ng on 2/2/15.
// Copyright (c) 2015 Thibault. All rights reserved.
//
import UIKit
import MapKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate, AlertAgencyDelegate {
var backgroundSessionCompletionHandler : (() -> Void)?
private var mUserLocation:CLLocation!
private var mLocationManager: CLLocationManager!
private let mJson = JsonAgencyAlert()
let dispatchingUserPosition = DispatchingValue(CLLocation())
let dispatchingUserAddress = DispatchingValue("")
var mPositionSetted: Bool = false
var window: UIWindow?
func sharedInstance() -> AppDelegate{
return UIApplication.sharedApplication().delegate as! AppDelegate
}
func startLocationManager() {
if CLLocationManager.locationServicesEnabled() {
mLocationManager = CLLocationManager()
mLocationManager.delegate = self
mLocationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
mLocationManager.requestWhenInUseAuthorization()
mLocationManager.distanceFilter = 10.0
mLocationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error) in
if (error != nil) {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
print("Problem with the data received from geocoder")
}
})
let wNewPosition = manager.location!
let wDistance = Int(self.mUserLocation.coordinate.distanceInMetersFrom(CLLocationCoordinate2D(latitude: wNewPosition.coordinate.latitude, longitude: wNewPosition.coordinate.longitude)))
if wDistance > 10{
mPositionSetted = true
mUserLocation = manager.location!
dispatchingUserPosition.value = mUserLocation
}
}
func displayLocationInfo(placemark: CLPlacemark) {
dispatchingUserAddress.value = placemark.addressDictionary!["Street"] as? String ?? ""
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error while updating location " + error.localizedDescription)
mPositionSetted = true
dispatchingUserPosition.value = mUserLocation
}
func locationManagerDidPauseLocationUpdates(manager: CLLocationManager) {
}
func getUserLocation() -> CLLocation{
return mUserLocation
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//Check if databse created
// debug delete
//File.deleteContentsOfFolder(File.getDocumentFilePath())
parseXmlAgency()
if !File.documentFileExist(NSBundle.mainBundle().releaseVersionNumber!)
{
displayLoadingView()
}
else
{
// set zip path
for wAgency in AgencyManager.getAgencies(){
wAgency.setZipData()
}
SQLProvider.sqlProvider.openDatabase()
displayNearestView()
}
return true
}
private func parseXmlAgency()
{
var wString = File.open(File.getBundleFilePath("Agencies", iOfType: "xml")!)!
wString = wString.stringByReplacingOccurrencesOfString("\n", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "")
let parser=XMLParser(xml: wString, element:"agency")
parser.parse()
let agencies = parser.getAgencies()
AgencyManager.setAgencies(agencies)
if agencies.capacity > 0 {
AgencyManager.setCurrentAgency((agencies.first?.mAgencyId)!)
}
}
private func displayNearestView(){
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let swViewController: SwiftSWRevealViewController = mainStoryboard.instantiateViewControllerWithIdentifier("SWRevealViewController") as! SwiftSWRevealViewController
self.window?.rootViewController = swViewController
self.window?.makeKeyAndVisible()
}
private func displayLoadingView(){
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let swViewController: LoadingViewController = mainStoryboard.instantiateViewControllerWithIdentifier("LoadingViewController") as! LoadingViewController
self.window?.rootViewController = swViewController
self.window?.makeKeyAndVisible()
}
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.
// retrieve user position
mUserLocation = CLLocation(latitude: AgencyManager.getAgency().getLatitude(), longitude: AgencyManager.getAgency().getLongitude())
startLocationManager()
//retrieve alert
mJson.delegate = self
mJson.getJsonAlert(AgencyManager.getAgency().getJsonAlertPath())
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func getJson() -> JsonAgencyAlert{
return mJson
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
let events = event!.allTouches()
let touch = events!.first
let location = touch!.locationInView(self.window)
let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
if CGRectContainsPoint(statusBarFrame, location) {
NSNotificationCenter.defaultCenter().postNotificationName("statusBarSelected", object: nil)
}
}
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {
backgroundSessionCompletionHandler = completionHandler
}
}
| 40.185366 | 285 | 0.673343 |
2913761c3ae050cb5efea608e78ffaa2fe63d653 | 6,500 | //
// UsingListViewController.swift
// Emojilist
//
// Created by Thiago Ricieri on 12/01/2018.
// Copyright © 2018 Ghost Ship. All rights reserved.
//
import Foundation
import UIKit
import PopupDialog
class UsingListViewController: BaseCollectionViewController {
var viewModel: UsingListViewModel!
var passListViewModel: EmojiListViewModel!
@IBOutlet weak var listNameLabel: UILabel!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var settingsButton: SecondaryFloatingButton!
@IBOutlet weak var shareButton: SecondaryFloatingButton!
@IBOutlet weak var topFadeDecoration: UIImageView!
@IBOutlet weak var bottomFadeDecoration: UIImageView!
override func instantiateDependencies() {
baseViewModel = UsingListViewModel(list: passListViewModel)
viewModel = baseViewModel as! UsingListViewModel
}
override func applyTheme(_ theme: Theme) {
super.applyTheme(theme)
theme.actionButton(doneButton)
theme.background(self.view)
theme.secondaryButton(shareButton)
theme.secondaryButton(settingsButton)
theme.primaryText(listNameLabel)
topFadeDecoration.image = UIImage(named: theme.topDecoration())
bottomFadeDecoration.image = UIImage(named: theme.bottomDecoration())
}
override func setViewStyle() {
listNameLabel.text = viewModel.name
doneButton.setTitle("UsingList.Done".localized, for: .normal)
navigationController?.isNavigationBarHidden = true
}
override func reload() {
super.reload()
setViewStyle()
}
// MARK: - Collection
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let emoji = viewModel.item(at: indexPath)
if !emoji.hasImage {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: AsciiEmojiCell.identifier, for: indexPath) as! AsciiEmojiCell
cell.configure(with: emoji)
return cell
}
else {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ImageEmojiCell.identifier, for: indexPath) as! ImageEmojiCell
cell.configure(with: emoji)
return cell
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: false)
viewModel.toggleEmoji(at: indexPath)
if let cell = collectionView.cellForItem(at: indexPath) as? BaseEmojiCell {
cell.configure(with: viewModel.item(at: indexPath))
cell.springView.animation = "pop"
cell.springView.curve = "easeOut"
cell.springView.duration = 0.5
cell.springView.animate()
}
heavyImpact()
}
// MARK: - List Settings Options
func redoList() {
for cell in collection.visibleCells {
let indexPath = collection.indexPath(for: cell)
let emoji = viewModel.item(at: indexPath!)
if let ccell = cell as? BaseEmojiCell, emoji.isChecked {
ccell.springView.animation = "swing"
ccell.springView.curve = "easeInOut"
ccell.springView.duration = 0.7
ccell.springView.animate()
ccell.uncheckEmoji()
}
}
viewModel.reuseList()
}
func settingsOptions() {
let title = "UsingList.Settings.Title".localized
let message = "UsingList.Settings.Msg".localized
let popup = PopupDialog(title: title, message: message)
let dismissButton = CancelButton(title: "Dismiss".localized) {
print("You canceled the car dialog.")
}
let deleteButton = DestructiveButton(
title: "UsingList.Settings.DeleteList".localized,
dismissOnTap: true) {
self.confirmDeletion()
}
let reuseButton = DefaultButton(
title: "UsingList.Settings.Redo".localized,
dismissOnTap: true) {
self.redoList()
}
let editButton = DefaultButton(
title: "UsingList.Settings.Edit".localized,
dismissOnTap: true) {
self.performSegue(
withIdentifier: MainStoryboard.Segue.toEditList,
sender: nil)
}
popup.addButtons([reuseButton, editButton, deleteButton, dismissButton])
self.present(popup, animated: true, completion: nil)
}
func confirmDeletion() {
let title = "UsingList.Settings.DeleteList".localized
let message = "UsingList.Delete.Msg".localized
let popup = PopupDialog(title: title, message: message)
let dismissButton = CancelButton(title: "No".localized) { }
let deleteButton = DestructiveButton(
title: "UsingList.Settings.DeleteListConfirmation".localized,
dismissOnTap: true) {
self.viewModel.deleteList()
self.dismiss(animated: true)
}
popup.addButtons([dismissButton, deleteButton])
self.present(popup, animated: true, completion: nil)
}
func shareList() {
viewModel.trackSharing()
Marketing.share(list: passListViewModel) { activityController in
self.present(activityController, animated: true) { }
}
}
// MARK: - Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == MainStoryboard.Segue.toEditList {
let dest = segue.destination as! CreateListViewController
dest.passListViewModel = viewModel.source
}
}
// MARK: - Actions
@IBAction func actionDone(sender: Any) {
dismiss(animated: true, completion: nil)
viewModel.trackCompletedList()
mediumImpact()
}
@IBAction func actionSettings(sender: Any) {
settingsOptions()
lightImpact()
}
@IBAction func actionShare(sender: Any) {
shareList()
lightImpact()
}
}
| 32.828283 | 99 | 0.605385 |
1af9d51aab1a01e4273dce3102b9637bbc305cb1 | 19,177 | /* file: nearly_degenerate_geometry.swift generated: Mon Jan 3 16:32:52 2022 */
/* This file was generated by the EXPRESS to Swift translator "exp2swift",
derived from STEPcode (formerly NIST's SCL).
exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23
WARNING: You probably don't want to edit it since your modifications
will be lost if exp2swift is used to regenerate it.
*/
import SwiftSDAIcore
extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF {
//MARK: -ENTITY DEFINITION in EXPRESS
/*
ENTITY nearly_degenerate_geometry
ABSTRACT SUPERTYPE OF (
ONEOF (
small_area_surface,
short_length_curve,
entirely_narrow_surface ) )
SUBTYPE OF ( inapt_geometry );
END_ENTITY; -- nearly_degenerate_geometry (line:21948 file:ap242ed2_mim_lf_v1.101.TY.exp)
*/
//MARK: - ALL DEFINED ATTRIBUTES
/*
SUPER- ENTITY(1) representation_item
ATTR: name, TYPE: label -- EXPLICIT
SUPER- ENTITY(2) data_quality_criterion
(no local attributes)
SUPER- ENTITY(3) data_quality_measurement_requirement
(no local attributes)
SUPER- ENTITY(4) shape_data_quality_criterion
ATTR: assessment_specification, TYPE: shape_data_quality_assessment_specification_select -- EXPLICIT
-- possibly overriden by
ENTITY: multiply_defined_placements, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: steep_angle_between_adjacent_edges, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: multiply_defined_directions, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: short_length_edge, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: wrongly_placed_void, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: g1_discontinuous_surface, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: short_length_curve, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: non_manifold_at_edge, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: multiply_defined_cartesian_points, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: small_area_surface, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: g2_discontinuity_between_adjacent_faces, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: indistinct_surface_knots, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: excessively_high_degree_curve, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: solid_with_wrong_number_of_voids, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: wrongly_oriented_void, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: entirely_narrow_surface, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: excessively_high_degree_surface, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: wrongly_placed_loop, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: self_intersecting_surface, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: curve_with_small_curvature_radius, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: self_intersecting_shell, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: entirely_narrow_solid, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: gap_between_pcurves_related_to_an_edge, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: inconsistent_face_and_surface_normals, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: intersecting_connected_face_sets, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: inconsistent_face_and_closed_shell_normals, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: indistinct_curve_knots, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: surface_with_excessive_patches_in_one_direction, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: non_manifold_at_vertex, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: partly_overlapping_edges, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: gap_between_edge_and_base_surface, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: inconsistent_curve_transition_code, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: free_edge, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: multiply_defined_faces, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: multiply_defined_edges, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: open_closed_shell, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: steep_angle_between_adjacent_faces, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: intersecting_shells_in_solid, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: intersecting_loops_in_face, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: erroneous_b_spline_curve_definition, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: entirely_narrow_face, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: unused_patches, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: g2_discontinuous_curve, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: solid_with_excessive_number_of_voids, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: partly_overlapping_solids, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: small_area_surface_patch, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: nearly_degenerate_surface_boundary, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: g2_discontinuous_surface, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: partly_overlapping_surfaces, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: gap_between_vertex_and_edge, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: high_degree_linear_curve, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: multiply_defined_solids, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: high_degree_planar_surface, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: inconsistent_edge_and_curve_directions, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: edge_with_excessive_segments, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: g1_discontinuity_between_adjacent_faces, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: partly_overlapping_curves, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: self_intersecting_curve, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: gap_between_adjacent_edges_in_loop, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: g1_discontinuous_curve, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: small_volume_solid, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: surface_with_small_curvature_radius, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: short_length_curve_segment, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: over_used_vertex, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: zero_surface_normal, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: disconnected_face_set, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: multiply_defined_surfaces, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: partly_overlapping_faces, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: narrow_surface_patch, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: multiply_defined_curves, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: self_intersecting_loop, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: curve_with_excessive_segments, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: multiply_defined_vertices, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: gap_between_faces_related_to_an_edge, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: extreme_patch_width_variation, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: inconsistent_adjacent_face_normals, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: inconsistent_surface_transition_code, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: nearly_degenerate_surface_patch, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: erroneous_b_spline_surface_definition, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: face_surface_with_excessive_patches_in_one_direction, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: high_degree_axi_symmetric_surface, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: open_edge_loop, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: small_area_face, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: abrupt_change_of_surface_normal, TYPE: shape_data_quality_assessment_by_logical_test
ENTITY: high_degree_conic, TYPE: shape_data_quality_assessment_by_numerical_test
ENTITY: gap_between_vertex_and_base_surface, TYPE: shape_data_quality_assessment_by_numerical_test
SUPER- ENTITY(5) inapt_data
(no local attributes)
SUPER- ENTITY(6) inapt_geometry
(no local attributes)
ENTITY(SELF) nearly_degenerate_geometry
(no local attributes)
SUB- ENTITY(8) short_length_curve
REDCR: assessment_specification, TYPE: shape_data_quality_assessment_by_numerical_test -- EXPLICIT
-- OVERRIDING ENTITY: shape_data_quality_criterion
SUB- ENTITY(9) small_area_surface
REDCR: assessment_specification, TYPE: shape_data_quality_assessment_by_numerical_test -- EXPLICIT
-- OVERRIDING ENTITY: shape_data_quality_criterion
SUB- ENTITY(10) entirely_narrow_surface
REDCR: assessment_specification, TYPE: shape_data_quality_assessment_by_logical_test -- EXPLICIT
-- OVERRIDING ENTITY: shape_data_quality_criterion
ATTR: width_tolerance, TYPE: length_measure -- EXPLICIT
*/
//MARK: - Partial Entity
public final class _nearly_degenerate_geometry : SDAI.PartialEntity {
public override class var entityReferenceType: SDAI.EntityReference.Type {
eNEARLY_DEGENERATE_GEOMETRY.self
}
//ATTRIBUTES
// (no local attributes)
public override var typeMembers: Set<SDAI.STRING> {
var members = Set<SDAI.STRING>()
members.insert(SDAI.STRING(Self.typeName))
return members
}
//VALUE COMPARISON SUPPORT
public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) {
super.hashAsValue(into: &hasher, visited: &complexEntities)
}
public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool {
guard let rhs = rhs as? Self else { return false }
if !super.isValueEqual(to: rhs, visited: &comppairs) { return false }
return true
}
public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? {
guard let rhs = rhs as? Self else { return false }
var result: Bool? = true
if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) {
if !comp { return false }
}
else { result = nil }
return result
}
//EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR
public init() {
super.init(asAbstructSuperclass:())
}
//p21 PARTIAL ENTITY CONSTRUCTOR
public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) {
let numParams = 0
guard parameters.count == numParams
else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil }
self.init( )
}
}
//MARK: - Entity Reference
/** ENTITY reference
- EXPRESS:
```express
ENTITY nearly_degenerate_geometry
ABSTRACT SUPERTYPE OF (
ONEOF (
small_area_surface,
short_length_curve,
entirely_narrow_surface ) )
SUBTYPE OF ( inapt_geometry );
END_ENTITY; -- nearly_degenerate_geometry (line:21948 file:ap242ed2_mim_lf_v1.101.TY.exp)
```
*/
public final class eNEARLY_DEGENERATE_GEOMETRY : SDAI.EntityReference {
//MARK: PARTIAL ENTITY
public override class var partialEntityType: SDAI.PartialEntity.Type {
_nearly_degenerate_geometry.self
}
public let partialEntity: _nearly_degenerate_geometry
//MARK: SUPERTYPES
public let super_eREPRESENTATION_ITEM: eREPRESENTATION_ITEM // [1]
public let super_eDATA_QUALITY_CRITERION: eDATA_QUALITY_CRITERION // [2]
public let super_eDATA_QUALITY_MEASUREMENT_REQUIREMENT: eDATA_QUALITY_MEASUREMENT_REQUIREMENT // [3]
public let super_eSHAPE_DATA_QUALITY_CRITERION: eSHAPE_DATA_QUALITY_CRITERION // [4]
public let super_eINAPT_DATA: eINAPT_DATA // [5]
public let super_eINAPT_GEOMETRY: eINAPT_GEOMETRY // [6]
public var super_eNEARLY_DEGENERATE_GEOMETRY: eNEARLY_DEGENERATE_GEOMETRY { return self } // [7]
//MARK: SUBTYPES
public var sub_eSHORT_LENGTH_CURVE: eSHORT_LENGTH_CURVE? { // [8]
return self.complexEntity.entityReference(eSHORT_LENGTH_CURVE.self)
}
public var sub_eSMALL_AREA_SURFACE: eSMALL_AREA_SURFACE? { // [9]
return self.complexEntity.entityReference(eSMALL_AREA_SURFACE.self)
}
public var sub_eENTIRELY_NARROW_SURFACE: eENTIRELY_NARROW_SURFACE? { // [10]
return self.complexEntity.entityReference(eENTIRELY_NARROW_SURFACE.self)
}
//MARK: ATTRIBUTES
/// __EXPLICIT__ attribute
/// - origin: SUB( ``eENTIRELY_NARROW_SURFACE`` )
public var WIDTH_TOLERANCE: tLENGTH_MEASURE? {
get {
return sub_eENTIRELY_NARROW_SURFACE?.partialEntity._width_tolerance
}
set(newValue) {
guard let partial = sub_eENTIRELY_NARROW_SURFACE?.super_eENTIRELY_NARROW_SURFACE.partialEntity
else { return }
partial._width_tolerance = SDAI.UNWRAP(newValue)
}
}
/// __EXPLICIT__ attribute
/// - origin: SUPER( ``eSHAPE_DATA_QUALITY_CRITERION`` )
public var ASSESSMENT_SPECIFICATION: sSHAPE_DATA_QUALITY_ASSESSMENT_SPECIFICATION_SELECT {
get {
return SDAI.UNWRAP( super_eSHAPE_DATA_QUALITY_CRITERION.partialEntity._assessment_specification )
}
set(newValue) {
let partial = super_eSHAPE_DATA_QUALITY_CRITERION.partialEntity
partial._assessment_specification = SDAI.UNWRAP(newValue)
}
}
/// __EXPLICIT__ attribute
/// - origin: SUPER( ``eREPRESENTATION_ITEM`` )
public var NAME: tLABEL {
get {
return SDAI.UNWRAP( super_eREPRESENTATION_ITEM.partialEntity._name )
}
set(newValue) {
let partial = super_eREPRESENTATION_ITEM.partialEntity
partial._name = SDAI.UNWRAP(newValue)
}
}
//MARK: INITIALIZERS
public convenience init?(_ entityRef: SDAI.EntityReference?) {
let complex = entityRef?.complexEntity
self.init(complex: complex)
}
public required init?(complex complexEntity: SDAI.ComplexEntity?) {
guard let partial = complexEntity?.partialEntityInstance(_nearly_degenerate_geometry.self) else { return nil }
self.partialEntity = partial
guard let super1 = complexEntity?.entityReference(eREPRESENTATION_ITEM.self) else { return nil }
self.super_eREPRESENTATION_ITEM = super1
guard let super2 = complexEntity?.entityReference(eDATA_QUALITY_CRITERION.self) else { return nil }
self.super_eDATA_QUALITY_CRITERION = super2
guard let super3 = complexEntity?.entityReference(eDATA_QUALITY_MEASUREMENT_REQUIREMENT.self) else { return nil }
self.super_eDATA_QUALITY_MEASUREMENT_REQUIREMENT = super3
guard let super4 = complexEntity?.entityReference(eSHAPE_DATA_QUALITY_CRITERION.self) else { return nil }
self.super_eSHAPE_DATA_QUALITY_CRITERION = super4
guard let super5 = complexEntity?.entityReference(eINAPT_DATA.self) else { return nil }
self.super_eINAPT_DATA = super5
guard let super6 = complexEntity?.entityReference(eINAPT_GEOMETRY.self) else { return nil }
self.super_eINAPT_GEOMETRY = super6
super.init(complex: complexEntity)
}
public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) {
guard let entityRef = generic?.entityReference else { return nil }
self.init(complex: entityRef.complexEntity)
}
public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) }
public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) }
//MARK: DICTIONARY DEFINITION
public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition }
private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition()
private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition {
let entityDef = SDAIDictionarySchema.EntityDefinition(name: "NEARLY_DEGENERATE_GEOMETRY", type: self, explicitAttributeCount: 0)
//MARK: SUPERTYPE REGISTRATIONS
entityDef.add(supertype: eREPRESENTATION_ITEM.self)
entityDef.add(supertype: eDATA_QUALITY_CRITERION.self)
entityDef.add(supertype: eDATA_QUALITY_MEASUREMENT_REQUIREMENT.self)
entityDef.add(supertype: eSHAPE_DATA_QUALITY_CRITERION.self)
entityDef.add(supertype: eINAPT_DATA.self)
entityDef.add(supertype: eINAPT_GEOMETRY.self)
entityDef.add(supertype: eNEARLY_DEGENERATE_GEOMETRY.self)
//MARK: ATTRIBUTE REGISTRATIONS
entityDef.addAttribute(name: "WIDTH_TOLERANCE", keyPath: \eNEARLY_DEGENERATE_GEOMETRY.WIDTH_TOLERANCE,
kind: .explicit, source: .subEntity, mayYieldEntityReference: false)
entityDef.addAttribute(name: "ASSESSMENT_SPECIFICATION", keyPath: \eNEARLY_DEGENERATE_GEOMETRY.ASSESSMENT_SPECIFICATION,
kind: .explicit, source: .superEntity, mayYieldEntityReference: true)
entityDef.addAttribute(name: "NAME", keyPath: \eNEARLY_DEGENERATE_GEOMETRY.NAME,
kind: .explicit, source: .superEntity, mayYieldEntityReference: false)
return entityDef
}
}
}
| 51.690027 | 185 | 0.776555 |
28e9be75752b75329bb76ea9410b12beac2bf346 | 1,131 | //
// StopViewController.swift
// nairalance
//
// Created by Anthonio Ez on 05/08/2016.
// Copyright © 2016 Anthonio Ez. All rights reserved.
//
import UIKit
class StopViewController: UIViewController {
var message = "A new version of this app is available!"
var button = true;
@IBOutlet weak var textMessage: UITextView!
@IBOutlet weak var buttonUpdate: UIButton!
static func instance(_ msg: String, _ button: Bool) -> StopViewController
{
let vc = StopViewController(nibName: "StopViewController", bundle: nil)
vc.message = msg;
vc.button = button;
return vc;
}
override func viewDidLoad()
{
super.viewDidLoad()
textMessage.text = message
buttonUpdate.rounded()
buttonUpdate.isHidden = !button;
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
override var prefersStatusBarHidden : Bool
{
return false;
}
@IBAction func buttonUpdateTap(_ sender: AnyObject)
{
Rewards.openStoreUrl()
}
}
| 20.944444 | 79 | 0.622458 |
79a4b747f581c5d0d162354c9d8aee68917b7c0a | 593 | //
// PhotosBrowserCollectionLayout.swift
// CATransition
//
// Created by wenzhiji on 16/4/28.
// Copyright © 2016年 Manager. All rights reserved.
//
import UIKit
class PhotosBrowserCollectionLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
itemSize = (collectionView?.bounds.size)!
minimumInteritemSpacing = 0
minimumLineSpacing = 0
// 隐藏滚动条
collectionView?.showsHorizontalScrollIndicator = false
// 设置水平滚动
scrollDirection = .Horizontal
// 开启分页
collectionView?.pagingEnabled = true
}
}
| 24.708333 | 65 | 0.67285 |
e92b2a4897bb3985960d9e9e9cd92d175d760611 | 2,230 | //
// MockURLSession.swift
// ApolloTestSupport
//
// Copyright © 2019 Apollo GraphQL. All rights reserved.
//
import Foundation
import Apollo
import ApolloUtils
public final class MockURLSessionClient: URLSessionClient {
public private (set) var lastRequest: Atomic<URLRequest?> = Atomic(nil)
public var data: Data?
public var response: HTTPURLResponse?
public var error: Error?
private let callbackQueue: DispatchQueue
public init(callbackQueue: DispatchQueue? = nil) {
self.callbackQueue = callbackQueue ?? .main
}
public override func sendRequest(_ request: URLRequest,
rawTaskCompletionHandler: URLSessionClient.RawCompletion? = nil,
completion: @escaping URLSessionClient.Completion) -> URLSessionTask {
self.lastRequest.mutate { $0 = request }
// Capture data, response, and error instead of self to ensure we complete with the current state
// even if it is changed before the block runs.
callbackQueue.async { [data, response, error] in
rawTaskCompletionHandler?(data, response, error)
if let error = error {
completion(.failure(error))
} else {
guard let data = data else {
completion(.failure(URLSessionClientError.dataForRequestNotFound(request: request)))
return
}
guard let response = response else {
completion(.failure(URLSessionClientError.noHTTPResponse(request: request)))
return
}
completion(.success((data, response)))
}
}
let mockTaskType: URLSessionDataTaskMockProtocol.Type = URLSessionDataTaskMock.self
let mockTask = mockTaskType.init() as! URLSessionDataTaskMock
return mockTask
}
}
protocol URLSessionDataTaskMockProtocol {
init()
}
private final class URLSessionDataTaskMock: URLSessionDataTask, URLSessionDataTaskMockProtocol{
// This override is to supress the deprecation warning on macOS 10.15+.
// This deprecated method needs to be used for unit test mocking purposes only.
@available(macOS, deprecated: 10.15)
override init() {
super.init()
}
override func resume() {
// No-op
}
}
| 29.342105 | 105 | 0.679821 |
2f5453c9056468f21f9011768289a4788f50f836 | 528 | class Solution {
func groupThePeople(_ groupSizes: [Int]) -> [[Int]] {
var result : [[Int]] = []
var table : [Int: [Int]] = [:]
for idx in 0..<groupSizes.count {
let p = groupSizes[idx]
if table[p] != nil {
table[p]!.append(idx)
} else {
table[p] = [idx]
}
if table[p]!.count == p {
result.append(table[p]!)
table[p] = nil
}
}
return result
}
} | 27.789474 | 57 | 0.392045 |
62357538c28743b576c134a9788ee559fbc9eca2 | 61,017 | //
// BigUIntTests.swift
// BigInt
//
// Created by Károly Lőrentey on 2015-12-27.
// Copyright © 2016-2017 Károly Lőrentey.
//
import XCTest
import Foundation
@testable import BigInt
extension BigUInt.Kind: Equatable {
public static func ==(left: BigUInt.Kind, right: BigUInt.Kind) -> Bool {
switch (left, right) {
case let (.inline(l0, l1), .inline(r0, r1)): return l0 == r0 && l1 == r1
case let (.slice(from: ls, to: le), .slice(from: rs, to: re)): return ls == rs && le == re
case (.array, .array): return true
default: return false
}
}
}
class BigUIntTests: XCTestCase {
typealias Word = BigUInt.Word
func check(_ value: BigUInt, _ kind: BigUInt.Kind?, _ words: [Word], file: StaticString = #file, line: UInt = #line) {
if let kind = kind {
XCTAssertEqual(
value.kind, kind,
"Mismatching kind: \(value.kind) vs. \(kind)",
file: file, line: line)
}
XCTAssertEqual(
Array(value.words), words,
"Mismatching words: \(value.words) vs. \(words)",
file: file, line: line)
XCTAssertEqual(
value.isZero, words.isEmpty,
"Mismatching isZero: \(value.isZero) vs. \(words.isEmpty)",
file: file, line: line)
XCTAssertEqual(
value.count, words.count,
"Mismatching count: \(value.count) vs. \(words.count)",
file: file, line: line)
for i in 0 ..< words.count {
XCTAssertEqual(
value[i], words[i],
"Mismatching word at index \(i): \(value[i]) vs. \(words[i])",
file: file, line: line)
}
for i in words.count ..< words.count + 10 {
XCTAssertEqual(
value[i], 0,
"Expected 0 word at index \(i), got \(value[i])",
file: file, line: line)
}
}
func check(_ value: BigUInt?, _ kind: BigUInt.Kind?, _ words: [Word], file: StaticString = #file, line: UInt = #line) {
guard let value = value else {
XCTFail("Expected non-nil BigUInt", file: file, line: line)
return
}
check(value, kind, words, file: file, line: line)
}
func testInit_WordBased() {
check(BigUInt(), .inline(0, 0), [])
check(BigUInt(word: 0), .inline(0, 0), [])
check(BigUInt(word: 1), .inline(1, 0), [1])
check(BigUInt(word: Word.max), .inline(Word.max, 0), [Word.max])
check(BigUInt(low: 0, high: 0), .inline(0, 0), [])
check(BigUInt(low: 0, high: 1), .inline(0, 1), [0, 1])
check(BigUInt(low: 1, high: 0), .inline(1, 0), [1])
check(BigUInt(low: 1, high: 2), .inline(1, 2), [1, 2])
check(BigUInt(words: []), .array, [])
check(BigUInt(words: [0, 0, 0, 0]), .array, [])
check(BigUInt(words: [1]), .array, [1])
check(BigUInt(words: [1, 2, 3, 0, 0]), .array, [1, 2, 3])
check(BigUInt(words: [0, 1, 2, 3, 4]), .array, [0, 1, 2, 3, 4])
check(BigUInt(words: [], from: 0, to: 0), .inline(0, 0), [])
check(BigUInt(words: [1, 2, 3, 4], from: 0, to: 4), .array, [1, 2, 3, 4])
check(BigUInt(words: [1, 2, 3, 4], from: 0, to: 3), .slice(from: 0, to: 3), [1, 2, 3])
check(BigUInt(words: [1, 2, 3, 4], from: 1, to: 4), .slice(from: 1, to: 4), [2, 3, 4])
check(BigUInt(words: [1, 2, 3, 4], from: 0, to: 2), .inline(1, 2), [1, 2])
check(BigUInt(words: [1, 2, 3, 4], from: 0, to: 1), .inline(1, 0), [1])
check(BigUInt(words: [1, 2, 3, 4], from: 1, to: 1), .inline(0, 0), [])
check(BigUInt(words: [0, 0, 0, 1, 0, 0, 0, 2], from: 0, to: 4), .slice(from: 0, to: 4), [0, 0, 0, 1])
check(BigUInt(words: [0, 0, 0, 1, 0, 0, 0, 2], from: 0, to: 3), .inline(0, 0), [])
check(BigUInt(words: [0, 0, 0, 1, 0, 0, 0, 2], from: 2, to: 6), .inline(0, 1), [0, 1])
check(BigUInt(words: [].lazy), .inline(0, 0), [])
check(BigUInt(words: [1].lazy), .inline(1, 0), [1])
check(BigUInt(words: [1, 2].lazy), .inline(1, 2), [1, 2])
check(BigUInt(words: [1, 2, 3].lazy), .array, [1, 2, 3])
check(BigUInt(words: [1, 2, 3, 0, 0, 0, 0].lazy), .array, [1, 2, 3])
check(BigUInt(words: IteratorSequence([].makeIterator())), .inline(0, 0), [])
check(BigUInt(words: IteratorSequence([1].makeIterator())), .inline(1, 0), [1])
check(BigUInt(words: IteratorSequence([1, 2].makeIterator())), .inline(1, 2), [1, 2])
check(BigUInt(words: IteratorSequence([1, 2, 3].makeIterator())), .array, [1, 2, 3])
check(BigUInt(words: IteratorSequence([1, 2, 3, 0, 0, 0, 0].makeIterator())), .array, [1, 2, 3])
}
func testInit_BinaryInteger() {
XCTAssertNil(BigUInt(exactly: -42))
check(BigUInt(exactly: 0 as Int), .inline(0, 0), [])
check(BigUInt(exactly: 42 as Int), .inline(42, 0), [42])
check(BigUInt(exactly: 43 as UInt), .inline(43, 0), [43])
check(BigUInt(exactly: 44 as UInt8), .inline(44, 0), [44])
check(BigUInt(exactly: BigUInt(words: [])), .inline(0, 0), [])
check(BigUInt(exactly: BigUInt(words: [1])), .inline(1, 0), [1])
check(BigUInt(exactly: BigUInt(words: [1, 2])), .inline(1, 2), [1, 2])
check(BigUInt(exactly: BigUInt(words: [1, 2, 3, 4])), .array, [1, 2, 3, 4])
}
func testInit_FloatingPoint() {
check(BigUInt(exactly: -0.0 as Float), nil, [])
check(BigUInt(exactly: -0.0 as Double), nil, [])
XCTAssertNil(BigUInt(exactly: -42.0 as Float))
XCTAssertNil(BigUInt(exactly: -42.0 as Double))
XCTAssertNil(BigUInt(exactly: 42.5 as Float))
XCTAssertNil(BigUInt(exactly: 42.5 as Double))
check(BigUInt(exactly: 100 as Float), nil, [100])
check(BigUInt(exactly: 100 as Double), nil, [100])
check(BigUInt(exactly: Float.greatestFiniteMagnitude), nil,
convertWords([0, 0xFFFFFF0000000000]))
check(BigUInt(exactly: Double.greatestFiniteMagnitude), nil,
convertWords([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFFFFFFFFFFFFF800]))
XCTAssertNil(BigUInt(exactly: Float.leastNormalMagnitude))
XCTAssertNil(BigUInt(exactly: Double.leastNormalMagnitude))
XCTAssertNil(BigUInt(exactly: Float.infinity))
XCTAssertNil(BigUInt(exactly: Double.infinity))
XCTAssertNil(BigUInt(exactly: Float.nan))
XCTAssertNil(BigUInt(exactly: Double.nan))
check(BigUInt(0 as Float), nil, [])
check(BigUInt(Float.leastNonzeroMagnitude), nil, [])
check(BigUInt(Float.leastNormalMagnitude), nil, [])
check(BigUInt(0.5 as Float), nil, [])
check(BigUInt(1.5 as Float), nil, [1])
check(BigUInt(42 as Float), nil, [42])
check(BigUInt(Double(sign: .plus, exponent: 2 * Word.bitWidth, significand: 1.0)),
nil, [0, 0, 1])
}
func testConversionToFloatingPoint() {
func test<F: BinaryFloatingPoint>(_ a: BigUInt, _ b: F, file: StaticString = #file, line: UInt = #line)
where F.RawExponent: FixedWidthInteger, F.RawSignificand: FixedWidthInteger {
let f = F(a)
XCTAssertEqual(f, b, file: file, line: line)
}
for i in 0 ..< 100 {
test(BigUInt(i), Double(i))
}
test(BigUInt(0x5A5A5A), 0x5A5A5A as Double)
test(BigUInt(1) << 64, 0x1p64 as Double)
test(BigUInt(0x5A5A5A) << 64, 0x5A5A5Ap64 as Double)
test(BigUInt(1) << 1023, 0x1p1023 as Double)
test(BigUInt(10) << 1020, 0xAp1020 as Double)
test(BigUInt(1) << 1024, Double.infinity)
test(BigUInt(words: convertWords([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFFFFFFFFFFFFF800])),
Double.greatestFiniteMagnitude)
test(BigUInt(UInt64.max), 0x1p64 as Double)
for i in 0 ..< 100 {
test(BigUInt(i), Float(i))
}
test(BigUInt(0x5A5A5A), 0x5A5A5A as Float)
test(BigUInt(1) << 64, 0x1p64 as Float)
test(BigUInt(0x5A5A5A) << 64, 0x5A5A5Ap64 as Float)
test(BigUInt(1) << 1023, 0x1p1023 as Float)
test(BigUInt(10) << 1020, 0xAp1020 as Float)
test(BigUInt(1) << 1024, Float.infinity)
test(BigUInt(words: convertWords([0, 0xFFFFFF0000000000])),
Float.greatestFiniteMagnitude)
// Test rounding
test(BigUInt(0xFFFFFF0000000000 as UInt64), 0xFFFFFFp40 as Float)
test(BigUInt(0xFFFFFF7FFFFFFFFF as UInt64), 0xFFFFFFp40 as Float)
test(BigUInt(0xFFFFFF8000000000 as UInt64), 0x1p64 as Float)
test(BigUInt(0xFFFFFFFFFFFFFFFF as UInt64), 0x1p64 as Float)
test(BigUInt(0xFFFFFE0000000000 as UInt64), 0xFFFFFEp40 as Float)
test(BigUInt(0xFFFFFE7FFFFFFFFF as UInt64), 0xFFFFFEp40 as Float)
test(BigUInt(0xFFFFFE8000000000 as UInt64), 0xFFFFFEp40 as Float)
test(BigUInt(0xFFFFFEFFFFFFFFFF as UInt64), 0xFFFFFEp40 as Float)
test(BigUInt(0x8000010000000000 as UInt64), 0x800001p40 as Float)
test(BigUInt(0x8000017FFFFFFFFF as UInt64), 0x800001p40 as Float)
test(BigUInt(0x8000018000000000 as UInt64), 0x800002p40 as Float)
test(BigUInt(0x800001FFFFFFFFFF as UInt64), 0x800002p40 as Float)
test(BigUInt(0x8000020000000000 as UInt64), 0x800002p40 as Float)
test(BigUInt(0x8000027FFFFFFFFF as UInt64), 0x800002p40 as Float)
test(BigUInt(0x8000028000000000 as UInt64), 0x800002p40 as Float)
test(BigUInt(0x800002FFFFFFFFFF as UInt64), 0x800002p40 as Float)
}
func testInit_Misc() {
check(BigUInt(0), .inline(0, 0), [])
check(BigUInt(42), .inline(42, 0), [42])
check(BigUInt(BigUInt(words: [1, 2, 3])), .array, [1, 2, 3])
check(BigUInt(truncatingIfNeeded: 0 as Int8), .inline(0, 0), [])
check(BigUInt(truncatingIfNeeded: 1 as Int8), .inline(1, 0), [1])
check(BigUInt(truncatingIfNeeded: -1 as Int8), .inline(Word.max, 0), [Word.max])
check(BigUInt(truncatingIfNeeded: BigUInt(words: [1, 2, 3])), .array, [1, 2, 3])
check(BigUInt(clamping: 0), .inline(0, 0), [])
check(BigUInt(clamping: -100), .inline(0, 0), [])
check(BigUInt(clamping: Word.max), .inline(Word.max, 0), [Word.max])
}
func testEnsureArray() {
var a = BigUInt()
a.ensureArray()
check(a, .array, [])
a = BigUInt(word: 1)
a.ensureArray()
check(a, .array, [1])
a = BigUInt(low: 1, high: 2)
a.ensureArray()
check(a, .array, [1, 2])
a = BigUInt(words: [1, 2, 3, 4])
a.ensureArray()
check(a, .array, [1, 2, 3, 4])
a = BigUInt(words: [1, 2, 3, 4, 5, 6], from: 1, to: 5)
a.ensureArray()
check(a, .array, [2, 3, 4, 5])
}
func testCapacity() {
XCTAssertEqual(BigUInt(low: 1, high: 2).capacity, 0)
XCTAssertEqual(BigUInt(words: 1 ..< 10).extract(2 ..< 5).capacity, 0)
var words: [Word] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
words.reserveCapacity(100)
XCTAssertEqual(BigUInt(words: words).capacity, 100)
}
func testReserveCapacity() {
var a = BigUInt()
a.reserveCapacity(100)
check(a, .array, [])
XCTAssertEqual(a.capacity, 100)
a = BigUInt(word: 1)
a.reserveCapacity(100)
check(a, .array, [1])
XCTAssertEqual(a.capacity, 100)
a = BigUInt(low: 1, high: 2)
a.reserveCapacity(100)
check(a, .array, [1, 2])
XCTAssertEqual(a.capacity, 100)
a = BigUInt(words: [1, 2, 3, 4])
a.reserveCapacity(100)
check(a, .array, [1, 2, 3, 4])
XCTAssertEqual(a.capacity, 100)
a = BigUInt(words: [1, 2, 3, 4, 5, 6], from: 1, to: 5)
a.reserveCapacity(100)
check(a, .array, [2, 3, 4, 5])
XCTAssertEqual(a.capacity, 100)
}
func testLoad() {
var a: BigUInt = 0
a.reserveCapacity(100)
a.load(BigUInt(low: 1, high: 2))
check(a, .array, [1, 2])
XCTAssertEqual(a.capacity, 100)
a.load(BigUInt(words: [1, 2, 3, 4, 5, 6]))
check(a, .array, [1, 2, 3, 4, 5, 6])
XCTAssertEqual(a.capacity, 100)
a.clear()
check(a, .array, [])
XCTAssertEqual(a.capacity, 100)
}
func testInitFromLiterals() {
check(0, .inline(0, 0), [])
check(42, .inline(42, 0), [42])
check("42", .inline(42, 0), [42])
check("1512366075204170947332355369683137040",
.inline(0xFEDCBA9876543210, 0x0123456789ABCDEF),
[0xFEDCBA9876543210, 0x0123456789ABCDEF])
// I have no idea how to exercise these in the wild
check(BigUInt(unicodeScalarLiteral: UnicodeScalar(52)), .inline(4, 0), [4])
check(BigUInt(extendedGraphemeClusterLiteral: "4"), .inline(4, 0), [4])
}
func testSubscriptingGetter() {
let a = BigUInt(words: [1, 2])
XCTAssertEqual(a[0], 1)
XCTAssertEqual(a[1], 2)
XCTAssertEqual(a[2], 0)
XCTAssertEqual(a[3], 0)
XCTAssertEqual(a[10000], 0)
let b = BigUInt(low: 1, high: 2)
XCTAssertEqual(b[0], 1)
XCTAssertEqual(b[1], 2)
XCTAssertEqual(b[2], 0)
XCTAssertEqual(b[3], 0)
XCTAssertEqual(b[10000], 0)
}
func testSubscriptingSetter() {
var a = BigUInt()
check(a, .inline(0, 0), [])
a[10] = 0
check(a, .inline(0, 0), [])
a[0] = 42
check(a, .inline(42, 0), [42])
a[10] = 23
check(a, .array, [42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23])
a[0] = 0
check(a, .array, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23])
a[10] = 0
check(a, .array, [])
a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 5)
a[2] = 42
check(a, .array, [1, 2, 42, 4])
}
func testSlice() {
let a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
check(a.extract(3 ..< 6), .slice(from: 3, to: 6), [3, 4, 5])
check(a.extract(3 ..< 5), .inline(3, 4), [3, 4])
check(a.extract(3 ..< 4), .inline(3, 0), [3])
check(a.extract(3 ..< 3), .inline(0, 0), [])
check(a.extract(0 ..< 100), .array, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
check(a.extract(100 ..< 200), .inline(0, 0), [])
let b = BigUInt(low: 1, high: 2)
check(b.extract(0 ..< 2), .inline(1, 2), [1, 2])
check(b.extract(0 ..< 1), .inline(1, 0), [1])
check(b.extract(1 ..< 2), .inline(2, 0), [2])
check(b.extract(1 ..< 1), .inline(0, 0), [])
check(b.extract(0 ..< 100), .inline(1, 2), [1, 2])
check(b.extract(100 ..< 200), .inline(0, 0), [])
let c = BigUInt(words: [1, 0, 0, 0, 2, 0, 0, 0, 3, 4, 5, 0, 0, 6, 0, 0, 0, 7])
check(c.extract(0 ..< 4), .inline(1, 0), [1])
check(c.extract(1 ..< 5), .slice(from: 1, to: 5), [0, 0, 0, 2])
check(c.extract(1 ..< 8), .slice(from: 1, to: 5), [0, 0, 0, 2])
check(c.extract(6 ..< 12), .slice(from: 6, to: 11), [0, 0, 3, 4, 5])
check(c.extract(4 ..< 7), .inline(2, 0), [2])
let d = c.extract(3 ..< 14)
// 0 1 2 3 4 5 6 7 8 9 10
check(d, .slice(from: 3, to: 14), [0, 2, 0, 0, 0, 3, 4, 5, 0, 0, 6])
check(d.extract(1 ..< 5), .inline(2, 0), [2])
check(d.extract(0 ..< 3), .inline(0, 2), [0, 2])
check(d.extract(1 ..< 6), .slice(from: 4, to: 9), [2, 0, 0, 0, 3])
check(d.extract(7 ..< 1000), .slice(from: 10, to: 14), [5, 0, 0, 6])
check(d.extract(10 ..< 1000), .inline(6, 0), [6])
check(d.extract(11 ..< 1000), .inline(0, 0), [])
}
func testSigns() {
XCTAssertFalse(BigUInt.isSigned)
XCTAssertEqual(BigUInt().signum(), 0)
XCTAssertEqual(BigUInt(words: []).signum(), 0)
XCTAssertEqual(BigUInt(words: [0, 1, 2]).signum(), 1)
XCTAssertEqual(BigUInt(word: 42).signum(), 1)
}
func testBits() {
let indices: Set<Int> = [0, 13, 59, 64, 79, 130]
var value: BigUInt = 0
for i in indices {
value[bitAt: i] = true
}
for i in 0 ..< 300 {
XCTAssertEqual(value[bitAt: i], indices.contains(i))
}
check(value, nil, convertWords([0x0800000000002001, 0x8001, 0x04]))
for i in indices {
value[bitAt: i] = false
}
check(value, nil, [])
}
func testStrideableRequirements() {
XCTAssertEqual(BigUInt(10), BigUInt(4).advanced(by: BigInt(6)))
XCTAssertEqual(BigUInt(4), BigUInt(10).advanced(by: BigInt(-6)))
XCTAssertEqual(BigInt(6), BigUInt(4).distance(to: 10))
XCTAssertEqual(BigInt(-6), BigUInt(10).distance(to: 4))
}
func testRightShift_ByWord() {
var a = BigUInt()
a.shiftRight(byWords: 1)
check(a, .inline(0, 0), [])
a = BigUInt(low: 1, high: 2)
a.shiftRight(byWords: 0)
check(a, .inline(1, 2), [1, 2])
a = BigUInt(low: 1, high: 2)
a.shiftRight(byWords: 1)
check(a, .inline(2, 0), [2])
a = BigUInt(low: 1, high: 2)
a.shiftRight(byWords: 2)
check(a, .inline(0, 0), [])
a = BigUInt(low: 1, high: 2)
a.shiftRight(byWords: 10)
check(a, .inline(0, 0), [])
a = BigUInt(words: [0, 1, 2, 3, 4])
a.shiftRight(byWords: 1)
check(a, .array, [1, 2, 3, 4])
a = BigUInt(words: [0, 1, 2, 3, 4])
a.shiftRight(byWords: 2)
check(a, .array, [2, 3, 4])
a = BigUInt(words: [0, 1, 2, 3, 4])
a.shiftRight(byWords: 5)
check(a, .array, [])
a = BigUInt(words: [0, 1, 2, 3, 4])
a.shiftRight(byWords: 100)
check(a, .array, [])
a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6)
check(a, .slice(from: 1, to: 6), [1, 2, 3, 4, 5])
a.shiftRight(byWords: 1)
check(a, .slice(from: 2, to: 6), [2, 3, 4, 5])
a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6)
a.shiftRight(byWords: 2)
check(a, .slice(from: 3, to: 6), [3, 4, 5])
a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6)
a.shiftRight(byWords: 3)
check(a, .inline(4, 5), [4, 5])
a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6)
a.shiftRight(byWords: 4)
check(a, .inline(5, 0), [5])
a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6)
a.shiftRight(byWords: 5)
check(a, .inline(0, 0), [])
a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 1, to: 6)
a.shiftRight(byWords: 10)
check(a, .inline(0, 0), [])
}
func testLeftShift_ByWord() {
var a = BigUInt()
a.shiftLeft(byWords: 1)
check(a, .inline(0, 0), [])
a = BigUInt(word: 1)
a.shiftLeft(byWords: 0)
check(a, .inline(1, 0), [1])
a = BigUInt(word: 1)
a.shiftLeft(byWords: 1)
check(a, .inline(0, 1), [0, 1])
a = BigUInt(word: 1)
a.shiftLeft(byWords: 2)
check(a, .array, [0, 0, 1])
a = BigUInt(low: 1, high: 2)
a.shiftLeft(byWords: 1)
check(a, .array, [0, 1, 2])
a = BigUInt(low: 1, high: 2)
a.shiftLeft(byWords: 2)
check(a, .array, [0, 0, 1, 2])
a = BigUInt(words: [1, 2, 3, 4, 5, 6])
a.shiftLeft(byWords: 1)
check(a, .array, [0, 1, 2, 3, 4, 5, 6])
a = BigUInt(words: [1, 2, 3, 4, 5, 6])
a.shiftLeft(byWords: 10)
check(a, .array, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6])
a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 2, to: 6)
a.shiftLeft(byWords: 1)
check(a, .array, [0, 2, 3, 4, 5])
a = BigUInt(words: [0, 1, 2, 3, 4, 5, 6], from: 2, to: 6)
a.shiftLeft(byWords: 3)
check(a, .array, [0, 0, 0, 2, 3, 4, 5])
}
func testSplit() {
let a = BigUInt(words: [0, 1, 2, 3])
XCTAssertEqual(a.split.low, BigUInt(words: [0, 1]))
XCTAssertEqual(a.split.high, BigUInt(words: [2, 3]))
}
func testLowHigh() {
let a = BigUInt(words: [0, 1, 2, 3])
check(a.low, .inline(0, 1), [0, 1])
check(a.high, .inline(2, 3), [2, 3])
check(a.low.low, .inline(0, 0), [])
check(a.low.high, .inline(1, 0), [1])
check(a.high.low, .inline(2, 0), [2])
check(a.high.high, .inline(3, 0), [3])
let b = BigUInt(words: [0, 1, 2, 3, 4, 5])
let bl = b.low
check(bl, .slice(from: 0, to: 3), [0, 1, 2])
let bh = b.high
check(bh, .slice(from: 3, to: 6), [3, 4, 5])
let bll = bl.low
check(bll, .inline(0, 1), [0, 1])
let blh = bl.high
check(blh, .inline(2, 0), [2])
let bhl = bh.low
check(bhl, .inline(3, 4), [3, 4])
let bhh = bh.high
check(bhh, .inline(5, 0), [5])
let blhl = bll.low
check(blhl, .inline(0, 0), [])
let blhh = bll.high
check(blhh, .inline(1, 0), [1])
let bhhl = bhl.low
check(bhhl, .inline(3, 0), [3])
let bhhh = bhl.high
check(bhhh, .inline(4, 0), [4])
}
func testComparison() {
XCTAssertEqual(BigUInt(words: [1, 2, 3]), BigUInt(words: [1, 2, 3]))
XCTAssertNotEqual(BigUInt(words: [1, 2]), BigUInt(words: [1, 2, 3]))
XCTAssertNotEqual(BigUInt(words: [1, 2, 3]), BigUInt(words: [1, 3, 3]))
XCTAssertEqual(BigUInt(words: [1, 2, 3, 4, 5, 6]).low.high, BigUInt(words: [3]))
XCTAssertTrue(BigUInt(words: [1, 2]) < BigUInt(words: [1, 2, 3]))
XCTAssertTrue(BigUInt(words: [1, 2, 2]) < BigUInt(words: [1, 2, 3]))
XCTAssertFalse(BigUInt(words: [1, 2, 3]) < BigUInt(words: [1, 2, 3]))
XCTAssertTrue(BigUInt(words: [3, 3]) < BigUInt(words: [1, 2, 3, 4, 5, 6]).extract(2 ..< 4))
XCTAssertTrue(BigUInt(words: [1, 2, 3, 4, 5, 6]).low.high < BigUInt(words: [3, 5]))
}
func testHashing() {
var hashes: [Int] = []
hashes.append(BigUInt(words: []).hashValue)
hashes.append(BigUInt(words: [1]).hashValue)
hashes.append(BigUInt(words: [2]).hashValue)
hashes.append(BigUInt(words: [0, 1]).hashValue)
hashes.append(BigUInt(words: [1, 1]).hashValue)
hashes.append(BigUInt(words: [1, 2]).hashValue)
hashes.append(BigUInt(words: [2, 1]).hashValue)
hashes.append(BigUInt(words: [2, 2]).hashValue)
hashes.append(BigUInt(words: [1, 2, 3, 4, 5]).hashValue)
hashes.append(BigUInt(words: [5, 4, 3, 2, 1]).hashValue)
hashes.append(BigUInt(words: [Word.max]).hashValue)
hashes.append(BigUInt(words: [Word.max, Word.max]).hashValue)
hashes.append(BigUInt(words: [Word.max, Word.max, Word.max]).hashValue)
hashes.append(BigUInt(words: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).hashValue)
XCTAssertEqual(hashes.count, Set(hashes).count)
}
func checkData(_ bytes: [UInt8], _ value: BigUInt, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(BigUInt(Data(bytes: bytes)), value, file: file, line: line)
XCTAssertEqual(bytes.withUnsafeBytes { buffer in BigUInt(buffer) }, value, file: file, line: line)
}
func testConversionFromBytes() {
checkData([], 0)
checkData([0], 0)
checkData([0, 0, 0, 0, 0, 0, 0, 0], 0)
checkData([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 0)
checkData([1], 1)
checkData([2], 2)
checkData([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 1)
checkData([0x01, 0x02, 0x03, 0x04, 0x05], 0x0102030405)
checkData([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08], 0x0102030405060708)
checkData([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A],
BigUInt(0x0102) << 64 + BigUInt(0x030405060708090A))
checkData([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
BigUInt(1) << 80)
checkData([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10],
BigUInt(0x0102030405060708) << 64 + BigUInt(0x090A0B0C0D0E0F10))
checkData([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11],
((BigUInt(1) << 128) as BigUInt) + BigUInt(0x0203040506070809) << 64 + BigUInt(0x0A0B0C0D0E0F1011))
}
func testConversionToData() {
func test(_ b: BigUInt, _ d: Array<UInt8>, file: StaticString = #file, line: UInt = #line) {
let expected = Data(d)
let actual = b.serialize()
XCTAssertEqual(actual, expected, file: file, line: line)
XCTAssertEqual(BigUInt(actual), b, file: file, line: line)
}
test(BigUInt(), [])
test(BigUInt(1), [0x01])
test(BigUInt(2), [0x02])
test(BigUInt(0x0102030405060708), [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08])
test(BigUInt(0x01) << 64 + BigUInt(0x0203040506070809), [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 09])
}
func testCodable() {
func test(_ a: BigUInt, file: StaticString = #file, line: UInt = #line) {
do {
let json = try JSONEncoder().encode(a)
print(String(data: json, encoding: .utf8)!)
let b = try JSONDecoder().decode(BigUInt.self, from: json)
XCTAssertEqual(a, b, file: file, line: line)
}
catch let error {
XCTFail("Error thrown: \(error.localizedDescription)", file: file, line: line)
}
}
test(0)
test(1)
test(0x0102030405060708)
test(BigUInt(1) << 64)
test(BigUInt(words: [1, 2, 3, 4, 5, 6, 7]))
XCTAssertThrowsError(try JSONDecoder().decode(BigUInt.self, from: "[\"*\", 1]".data(using: .utf8)!)) { error in
guard let error = error as? DecodingError else { XCTFail("Expected a decoding error"); return }
guard case .dataCorrupted(let context) = error else { XCTFail("Expected a dataCorrupted error"); return }
XCTAssertEqual(context.debugDescription, "Invalid big integer sign")
}
XCTAssertThrowsError(try JSONDecoder().decode(BigUInt.self, from: "[\"-\", 1]".data(using: .utf8)!)) { error in
guard let error = error as? DecodingError else { XCTFail("Expected a decoding error"); return }
guard case .dataCorrupted(let context) = error else { XCTFail("Expected a dataCorrupted error"); return }
XCTAssertEqual(context.debugDescription, "BigUInt cannot hold a negative value")
}
}
func testAddition() {
XCTAssertEqual(BigUInt(0) + BigUInt(0), BigUInt(0))
XCTAssertEqual(BigUInt(0) + BigUInt(Word.max), BigUInt(Word.max))
XCTAssertEqual(BigUInt(Word.max) + BigUInt(1), BigUInt(words: [0, 1]))
check(BigUInt(3) + BigUInt(42), .inline(45, 0), [45])
check(BigUInt(3) + BigUInt(42), .inline(45, 0), [45])
check(0 + BigUInt(Word.max), .inline(Word.max, 0), [Word.max])
check(1 + BigUInt(Word.max), .inline(0, 1), [0, 1])
check(BigUInt(low: 0, high: 1) + BigUInt(low: 3, high: 4), .inline(3, 5), [3, 5])
check(BigUInt(low: 3, high: 5) + BigUInt(low: 0, high: Word.max), .array, [3, 4, 1])
check(BigUInt(words: [3, 4, 1]) + BigUInt(low: 0, high: Word.max), .array, [3, 3, 2])
check(BigUInt(words: [3, 3, 2]) + 2, .array, [5, 3, 2])
check(BigUInt(words: [Word.max - 5, Word.max, 4, Word.max]).addingWord(6), .array, [0, 0, 5, Word.max])
var b = BigUInt(words: [Word.max, 2, Word.max])
b.increment()
check(b, .array, [0, 3, Word.max])
}
func testShiftedAddition() {
var b = BigUInt()
b.add(1, shiftedBy: 1)
check(b, .inline(0, 1), [0, 1])
b.add(2, shiftedBy: 3)
check(b, .array, [0, 1, 0, 2])
b.add(BigUInt(Word.max), shiftedBy: 1)
check(b, .array, [0, 0, 1, 2])
}
func testSubtraction() {
var a1 = BigUInt(words: [1, 2, 3, 4])
XCTAssertEqual(false, a1.subtractWordReportingOverflow(3, shiftedBy: 1))
check(a1, .array, [1, Word.max, 2, 4])
let (diff, overflow) = BigUInt(words: [1, 2, 3, 4]).subtractingWordReportingOverflow(2)
XCTAssertEqual(false, overflow)
check(diff, .array, [Word.max, 1, 3, 4])
var a2 = BigUInt(words: [1, 2, 3, 4])
XCTAssertEqual(true, a2.subtractWordReportingOverflow(5, shiftedBy: 3))
check(a2, .array, [1, 2, 3, Word.max])
var a3 = BigUInt(words: [1, 2, 3, 4])
a3.subtractWord(4, shiftedBy: 3)
check(a3, .array, [1, 2, 3])
var a4 = BigUInt(words: [1, 2, 3, 4])
a4.decrement()
check(a4, .array, [0, 2, 3, 4])
a4.decrement()
check(a4, .array, [Word.max, 1, 3, 4])
check(BigUInt(words: [1, 2, 3, 4]).subtractingWord(5),
.array, [Word.max - 3, 1, 3, 4])
check(BigUInt(0) - BigUInt(0), .inline(0, 0), [])
var b = BigUInt(words: [1, 2, 3, 4])
XCTAssertEqual(false, b.subtractReportingOverflow(BigUInt(words: [0, 1, 1, 1])))
check(b, .array, [1, 1, 2, 3])
let b1 = BigUInt(words: [1, 1, 2, 3]).subtractingReportingOverflow(BigUInt(words: [1, 1, 3, 3]))
XCTAssertEqual(true, b1.overflow)
check(b1.partialValue, .array, [0, 0, Word.max, Word.max])
let b2 = BigUInt(words: [0, 0, 1]) - BigUInt(words: [1])
check(b2, .array, [Word.max, Word.max])
var b3 = BigUInt(words: [1, 0, 0, 1])
b3 -= 2
check(b3, .array, [Word.max, Word.max, Word.max])
check(BigUInt(42) - BigUInt(23), .inline(19, 0), [19])
}
func testMultiplyByWord() {
check(BigUInt(words: [1, 2, 3, 4]).multiplied(byWord: 0), .inline(0, 0), [])
check(BigUInt(words: [1, 2, 3, 4]).multiplied(byWord: 2), .array, [2, 4, 6, 8])
let full = Word.max
check(BigUInt(words: [full, 0, full, 0, full]).multiplied(byWord: 2),
.array, [full - 1, 1, full - 1, 1, full - 1, 1])
check(BigUInt(words: [full, full, full]).multiplied(byWord: 2),
.array, [full - 1, full, full, 1])
check(BigUInt(words: [full, full, full]).multiplied(byWord: full),
.array, [1, full, full, full - 1])
check(BigUInt("11111111111111111111111111111111", radix: 16)!.multiplied(byWord: 15),
.array, convertWords([UInt64.max, UInt64.max]))
check(BigUInt("11111111111111111111111111111112", radix: 16)!.multiplied(byWord: 15),
.array, convertWords([0xE, 0, 0x1]))
check(BigUInt(low: 1, high: 2).multiplied(byWord: 3), .inline(3, 6), [3, 6])
}
func testMultiplication() {
func test() {
check(BigUInt(low: 1, high: 1) * BigUInt(word: 3), .inline(3, 3), [3, 3])
check(BigUInt(word: 4) * BigUInt(low: 1, high: 2), .inline(4, 8), [4, 8])
XCTAssertEqual(
BigUInt(words: [1, 2, 3, 4]) * BigUInt(),
BigUInt())
XCTAssertEqual(
BigUInt() * BigUInt(words: [1, 2, 3, 4]),
BigUInt())
XCTAssertEqual(
BigUInt(words: [1, 2, 3, 4]) * BigUInt(words: [2]),
BigUInt(words: [2, 4, 6, 8]))
XCTAssertEqual(
BigUInt(words: [1, 2, 3, 4]).multiplied(by: BigUInt(words: [2])),
BigUInt(words: [2, 4, 6, 8]))
XCTAssertEqual(
BigUInt(words: [2]) * BigUInt(words: [1, 2, 3, 4]),
BigUInt(words: [2, 4, 6, 8]))
XCTAssertEqual(
BigUInt(words: [1, 2, 3, 4]) * BigUInt(words: [0, 1]),
BigUInt(words: [0, 1, 2, 3, 4]))
XCTAssertEqual(
BigUInt(words: [0, 1]) * BigUInt(words: [1, 2, 3, 4]),
BigUInt(words: [0, 1, 2, 3, 4]))
XCTAssertEqual(
BigUInt(words: [4, 3, 2, 1]) * BigUInt(words: [1, 2, 3, 4]),
BigUInt(words: [4, 11, 20, 30, 20, 11, 4]))
// 999 * 99 = 98901
XCTAssertEqual(
BigUInt(words: [Word.max, Word.max, Word.max]) * BigUInt(words: [Word.max, Word.max]),
BigUInt(words: [1, 0, Word.max, Word.max - 1, Word.max]))
XCTAssertEqual(
BigUInt(words: [1, 2]) * BigUInt(words: [2, 1]),
BigUInt(words: [2, 5, 2]))
var b = BigUInt("2637AB28", radix: 16)!
b *= BigUInt("164B", radix: 16)!
XCTAssertEqual(b, BigUInt("353FB0494B8", radix: 16))
XCTAssertEqual(BigUInt("16B60", radix: 16)! * BigUInt("33E28", radix: 16)!, BigUInt("49A5A0700", radix: 16)!)
}
test()
// Disable brute force multiplication.
let limit = BigUInt.directMultiplicationLimit
BigUInt.directMultiplicationLimit = 0
defer { BigUInt.directMultiplicationLimit = limit }
test()
}
func testDivision() {
func test(_ a: [Word], _ b: [Word], file: StaticString = #file, line: UInt = #line) {
let x = BigUInt(words: a)
let y = BigUInt(words: b)
let (div, mod) = x.quotientAndRemainder(dividingBy: y)
if mod >= y {
XCTFail("x:\(x) = div:\(div) * y:\(y) + mod:\(mod)", file: file, line: line)
}
if div * y + mod != x {
XCTFail("x:\(x) = div:\(div) * y:\(y) + mod:\(mod)", file: file, line: line)
}
let shift = y.leadingZeroBitCount
let norm = y << shift
var rem = x
rem.formRemainder(dividingBy: norm, normalizedBy: shift)
XCTAssertEqual(rem, mod, file: file, line: line)
}
// These cases exercise all code paths in the division when Word is UInt8 or UInt64.
test([], [1])
test([1], [1])
test([1], [2])
test([2], [1])
test([], [0, 1])
test([1], [0, 1])
test([0, 1], [0, 1])
test([0, 0, 1], [0, 1])
test([0, 0, 1], [1, 1])
test([0, 0, 1], [3, 1])
test([0, 0, 1], [75, 1])
test([0, 0, 0, 1], [0, 1])
test([2, 4, 6, 8], [1, 2])
test([2, 3, 4, 5], [4, 5])
test([Word.max, Word.max - 1, Word.max], [Word.max, Word.max])
test([0, Word.max, Word.max - 1], [Word.max, Word.max])
test([0, 0, 0, 0, 0, Word.max / 2 + 1, Word.max / 2], [1, 0, 0, Word.max / 2 + 1])
test([0, Word.max - 1, Word.max / 2 + 1], [Word.max, Word.max / 2 + 1])
test([0, 0, 0x41 << Word(Word.bitWidth - 8)], [Word.max, 1 << Word(Word.bitWidth - 1)])
XCTAssertEqual(BigUInt(328) / BigUInt(21), BigUInt(15))
XCTAssertEqual(BigUInt(328) % BigUInt(21), BigUInt(13))
var a = BigUInt(328)
a /= 21
XCTAssertEqual(a, 15)
a %= 7
XCTAssertEqual(a, 1)
#if false
for x0 in (0 ... Int(Word.max)) {
for x1 in (0 ... Int(Word.max)).reverse() {
for y0 in (0 ... Int(Word.max)).reverse() {
for y1 in (1 ... Int(Word.max)).reverse() {
for x2 in (1 ... y1).reverse() {
test(
[Word(x0), Word(x1), Word(x2)],
[Word(y0), Word(y1)])
}
}
}
}
}
#endif
}
func testFactorial() {
let power = 10
var forward = BigUInt(1)
for i in 1 ..< (1 << power) {
forward *= BigUInt(i)
}
print("\(1 << power - 1)! = \(forward) [\(forward.count)]")
var backward = BigUInt(1)
for i in (1 ..< (1 << power)).reversed() {
backward *= BigUInt(i)
}
func balancedFactorial(level: Int, offset: Int) -> BigUInt {
if level == 0 {
return BigUInt(offset == 0 ? 1 : offset)
}
let a = balancedFactorial(level: level - 1, offset: 2 * offset)
let b = balancedFactorial(level: level - 1, offset: 2 * offset + 1)
return a * b
}
let balanced = balancedFactorial(level: power, offset: 0)
XCTAssertEqual(backward, forward)
XCTAssertEqual(balanced, forward)
var remaining = balanced
for i in 1 ..< (1 << power) {
let (div, mod) = remaining.quotientAndRemainder(dividingBy: BigUInt(i))
XCTAssertEqual(mod, 0)
remaining = div
}
XCTAssertEqual(remaining, 1)
}
func testExponentiation() {
XCTAssertEqual(BigUInt(0).power(0), BigUInt(1))
XCTAssertEqual(BigUInt(0).power(1), BigUInt(0))
XCTAssertEqual(BigUInt(1).power(0), BigUInt(1))
XCTAssertEqual(BigUInt(1).power(1), BigUInt(1))
XCTAssertEqual(BigUInt(1).power(-1), BigUInt(1))
XCTAssertEqual(BigUInt(1).power(-2), BigUInt(1))
XCTAssertEqual(BigUInt(1).power(-3), BigUInt(1))
XCTAssertEqual(BigUInt(1).power(-4), BigUInt(1))
XCTAssertEqual(BigUInt(2).power(0), BigUInt(1))
XCTAssertEqual(BigUInt(2).power(1), BigUInt(2))
XCTAssertEqual(BigUInt(2).power(2), BigUInt(4))
XCTAssertEqual(BigUInt(2).power(3), BigUInt(8))
XCTAssertEqual(BigUInt(2).power(-1), BigUInt(0))
XCTAssertEqual(BigUInt(2).power(-2), BigUInt(0))
XCTAssertEqual(BigUInt(2).power(-3), BigUInt(0))
XCTAssertEqual(BigUInt(3).power(0), BigUInt(1))
XCTAssertEqual(BigUInt(3).power(1), BigUInt(3))
XCTAssertEqual(BigUInt(3).power(2), BigUInt(9))
XCTAssertEqual(BigUInt(3).power(3), BigUInt(27))
XCTAssertEqual(BigUInt(3).power(-1), BigUInt(0))
XCTAssertEqual(BigUInt(3).power(-2), BigUInt(0))
XCTAssertEqual((BigUInt(1) << 256).power(0), BigUInt(1))
XCTAssertEqual((BigUInt(1) << 256).power(1), BigUInt(1) << 256)
XCTAssertEqual((BigUInt(1) << 256).power(2), BigUInt(1) << 512)
XCTAssertEqual(BigUInt(0).power(577), BigUInt(0))
XCTAssertEqual(BigUInt(1).power(577), BigUInt(1))
XCTAssertEqual(BigUInt(2).power(577), BigUInt(1) << 577)
}
func testModularExponentiation() {
XCTAssertEqual(BigUInt(2).power(11, modulus: 1), 0)
XCTAssertEqual(BigUInt(2).power(11, modulus: 1000), 48)
func test(a: BigUInt, p: BigUInt, file: StaticString = #file, line: UInt = #line) {
// For all primes p and integers a, a % p == a^p % p. (Fermat's Little Theorem)
let x = a % p
let y = x.power(p, modulus: p)
XCTAssertEqual(x, y, file: file, line: line)
}
// Here are some primes
let m61 = (BigUInt(1) << 61) - BigUInt(1)
let m127 = (BigUInt(1) << 127) - BigUInt(1)
let m521 = (BigUInt(1) << 521) - BigUInt(1)
test(a: 2, p: m127)
test(a: BigUInt(1) << 42, p: m127)
test(a: BigUInt(1) << 42 + BigUInt(1), p: m127)
test(a: m61, p: m127)
test(a: m61 + 1, p: m127)
test(a: m61, p: m521)
test(a: m61 + 1, p: m521)
test(a: m127, p: m521)
}
func testBitWidth() {
XCTAssertEqual(BigUInt(0).bitWidth, 0)
XCTAssertEqual(BigUInt(1).bitWidth, 1)
XCTAssertEqual(BigUInt(Word.max).bitWidth, Word.bitWidth)
XCTAssertEqual(BigUInt(words: [Word.max, 1]).bitWidth, Word.bitWidth + 1)
XCTAssertEqual(BigUInt(words: [2, 12]).bitWidth, Word.bitWidth + 4)
XCTAssertEqual(BigUInt(words: [1, Word.max]).bitWidth, 2 * Word.bitWidth)
XCTAssertEqual(BigUInt(0).leadingZeroBitCount, 0)
XCTAssertEqual(BigUInt(1).leadingZeroBitCount, Word.bitWidth - 1)
XCTAssertEqual(BigUInt(Word.max).leadingZeroBitCount, 0)
XCTAssertEqual(BigUInt(words: [Word.max, 1]).leadingZeroBitCount, Word.bitWidth - 1)
XCTAssertEqual(BigUInt(words: [14, Word.max]).leadingZeroBitCount, 0)
XCTAssertEqual(BigUInt(0).trailingZeroBitCount, 0)
XCTAssertEqual(BigUInt((1 as Word) << (Word.bitWidth - 1)).trailingZeroBitCount, Word.bitWidth - 1)
XCTAssertEqual(BigUInt(Word.max).trailingZeroBitCount, 0)
XCTAssertEqual(BigUInt(words: [0, 1]).trailingZeroBitCount, Word.bitWidth)
XCTAssertEqual(BigUInt(words: [0, 1 << Word(Word.bitWidth - 1)]).trailingZeroBitCount, 2 * Word.bitWidth - 1)
}
func testBitwise() {
let a = BigUInt("1234567890ABCDEF13579BDF2468ACE", radix: 16)!
let b = BigUInt("ECA8642FDB97531FEDCBA0987654321", radix: 16)!
// a = 01234567890ABCDEF13579BDF2468ACE
// b = 0ECA8642FDB97531FEDCBA0987654321
XCTAssertEqual(String(~a, radix: 16), "fedcba9876f543210eca86420db97531")
XCTAssertEqual(String(a | b, radix: 16), "febc767fdbbfdfffffdfbbdf767cbef")
XCTAssertEqual(String(a & b, radix: 16), "2044289083410f014380982440200")
XCTAssertEqual(String(a ^ b, radix: 16), "fe9c32574b3c9ef0fe9c3b47523c9ef")
let ffff = BigUInt(words: Array(repeating: Word.max, count: 30))
let not = ~ffff
let zero = BigUInt()
XCTAssertEqual(not, zero)
XCTAssertEqual(Array((~ffff).words), [])
XCTAssertEqual(a | ffff, ffff)
XCTAssertEqual(a | 0, a)
XCTAssertEqual(a & a, a)
XCTAssertEqual(a & 0, 0)
XCTAssertEqual(a & ffff, a)
XCTAssertEqual(~(a | b), (~a & ~b))
XCTAssertEqual(~(a & b), (~a | ~b).extract(..<(a&b).count))
XCTAssertEqual(a ^ a, 0)
XCTAssertEqual((a ^ b) ^ b, a)
XCTAssertEqual((a ^ b) ^ a, b)
var z = a * b
z |= a
z &= b
z ^= ffff
XCTAssertEqual(z, (((a * b) | a) & b) ^ ffff)
}
func testLeftShifts() {
let sample = BigUInt("123456789ABCDEF01234567891631832727633", radix: 16)!
var a = sample
a <<= 0
XCTAssertEqual(a, sample)
a = sample
a <<= 1
XCTAssertEqual(a, 2 * sample)
a = sample
a <<= Word.bitWidth
XCTAssertEqual(a.count, sample.count + 1)
XCTAssertEqual(a[0], 0)
XCTAssertEqual(a.extract(1 ... sample.count + 1), sample)
a = sample
a <<= 100 * Word.bitWidth
XCTAssertEqual(a.count, sample.count + 100)
XCTAssertEqual(a.extract(0 ..< 100), 0)
XCTAssertEqual(a.extract(100 ... sample.count + 100), sample)
a = sample
a <<= 100 * Word.bitWidth + 2
XCTAssertEqual(a.count, sample.count + 100)
XCTAssertEqual(a.extract(0 ..< 100), 0)
XCTAssertEqual(a.extract(100 ... sample.count + 100), sample << 2)
a = sample
a <<= Word.bitWidth - 1
XCTAssertEqual(a.count, sample.count + 1)
XCTAssertEqual(a, BigUInt(words: [0] + sample.words) / 2)
a = sample
a <<= -4
XCTAssertEqual(a, sample / 16)
XCTAssertEqual(sample << 0, sample)
XCTAssertEqual(sample << 1, 2 * sample)
XCTAssertEqual(sample << 2, 4 * sample)
XCTAssertEqual(sample << 4, 16 * sample)
XCTAssertEqual(sample << Word.bitWidth, BigUInt(words: [0 as Word] + sample.words))
XCTAssertEqual(sample << (Word.bitWidth - 1), BigUInt(words: [0] + sample.words) / 2)
XCTAssertEqual(sample << (Word.bitWidth + 1), BigUInt(words: [0] + sample.words) * 2)
XCTAssertEqual(sample << (Word.bitWidth + 2), BigUInt(words: [0] + sample.words) * 4)
XCTAssertEqual(sample << (2 * Word.bitWidth), BigUInt(words: [0, 0] + sample.words))
XCTAssertEqual(sample << (2 * Word.bitWidth + 2), BigUInt(words: [0, 0] + (4 * sample).words))
XCTAssertEqual(sample << -1, sample / 2)
XCTAssertEqual(sample << -4, sample / 16)
}
func testRightShifts() {
let sample = BigUInt("123456789ABCDEF1234567891631832727633", radix: 16)!
var a = sample
a >>= BigUInt(0)
XCTAssertEqual(a, sample)
a >>= 0
XCTAssertEqual(a, sample)
a = sample
a >>= 1
XCTAssertEqual(a, sample / 2)
a = sample
a >>= Word.bitWidth
XCTAssertEqual(a, sample.extract(1...))
a = sample
a >>= Word.bitWidth + 2
XCTAssertEqual(a, sample.extract(1...) / 4)
a = sample
a >>= sample.count * Word.bitWidth
XCTAssertEqual(a, 0)
a = sample
a >>= 1000
XCTAssertEqual(a, 0)
a = sample
a >>= 100 * Word.bitWidth
XCTAssertEqual(a, 0)
a = sample
a >>= 100 * BigUInt(Word.max)
XCTAssertEqual(a, 0)
a = sample
a >>= -1
XCTAssertEqual(a, sample * 2)
a = sample
a >>= -4
XCTAssertEqual(a, sample * 16)
XCTAssertEqual(sample >> BigUInt(0), sample)
XCTAssertEqual(sample >> 0, sample)
XCTAssertEqual(sample >> 1, sample / 2)
XCTAssertEqual(sample >> 3, sample / 8)
XCTAssertEqual(sample >> Word.bitWidth, sample.extract(1 ..< sample.count))
XCTAssertEqual(sample >> (Word.bitWidth + 2), sample.extract(1...) / 4)
XCTAssertEqual(sample >> (Word.bitWidth + 3), sample.extract(1...) / 8)
XCTAssertEqual(sample >> (sample.count * Word.bitWidth), 0)
XCTAssertEqual(sample >> (100 * Word.bitWidth), 0)
XCTAssertEqual(sample >> (100 * BigUInt(Word.max)), 0)
XCTAssertEqual(sample >> -1, sample * 2)
XCTAssertEqual(sample >> -4, sample * 16)
}
func testSquareRoot() {
let sample = BigUInt("123456789ABCDEF1234567891631832727633", radix: 16)!
XCTAssertEqual(BigUInt(0).squareRoot(), 0)
XCTAssertEqual(BigUInt(256).squareRoot(), 16)
func checkSqrt(_ value: BigUInt, file: StaticString = #file, line: UInt = #line) {
let root = value.squareRoot()
XCTAssertLessThanOrEqual(root * root, value, "\(value)", file: file, line: line)
XCTAssertGreaterThan((root + 1) * (root + 1), value, "\(value)", file: file, line: line)
}
for i in 0 ... 100 {
checkSqrt(BigUInt(i))
checkSqrt(BigUInt(i) << 100)
}
checkSqrt(sample)
checkSqrt(sample * sample)
checkSqrt(sample * sample - 1)
checkSqrt(sample * sample + 1)
}
func testGCD() {
XCTAssertEqual(BigUInt(0).greatestCommonDivisor(with: 2982891), 2982891)
XCTAssertEqual(BigUInt(2982891).greatestCommonDivisor(with: 0), 2982891)
XCTAssertEqual(BigUInt(0).greatestCommonDivisor(with: 0), 0)
XCTAssertEqual(BigUInt(4).greatestCommonDivisor(with: 6), 2)
XCTAssertEqual(BigUInt(15).greatestCommonDivisor(with: 10), 5)
XCTAssertEqual(BigUInt(8 * 3 * 25 * 7).greatestCommonDivisor(with: 2 * 9 * 5 * 49), 2 * 3 * 5 * 7)
var fibo: [BigUInt] = [0, 1]
for i in 0...10000 {
fibo.append(fibo[i] + fibo[i + 1])
}
XCTAssertEqual(BigUInt(fibo[100]).greatestCommonDivisor(with: fibo[101]), 1)
XCTAssertEqual(BigUInt(fibo[1000]).greatestCommonDivisor(with: fibo[1001]), 1)
XCTAssertEqual(BigUInt(fibo[10000]).greatestCommonDivisor(with: fibo[10001]), 1)
XCTAssertEqual(BigUInt(3 * 5 * 7 * 9).greatestCommonDivisor(with: 5 * 7 * 7), 5 * 7)
XCTAssertEqual(BigUInt(fibo[4]).greatestCommonDivisor(with: fibo[2]), fibo[2])
XCTAssertEqual(BigUInt(fibo[3 * 5 * 7 * 9]).greatestCommonDivisor(with: fibo[5 * 7 * 7 * 9]), fibo[5 * 7 * 9])
XCTAssertEqual(BigUInt(fibo[7 * 17 * 83]).greatestCommonDivisor(with: fibo[6 * 17 * 83]), fibo[17 * 83])
}
func testInverse() {
XCTAssertNil(BigUInt(4).inverse(2))
XCTAssertNil(BigUInt(4).inverse(8))
XCTAssertNil(BigUInt(12).inverse(15))
XCTAssertEqual(BigUInt(13).inverse(15), 7)
XCTAssertEqual(BigUInt(251).inverse(1023), 269)
XCTAssertNil(BigUInt(252).inverse(1023))
XCTAssertEqual(BigUInt(2).inverse(1023), 512)
}
func testStrongProbablePrimeTest() {
let primes: [BigUInt.Word] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 79, 83, 89, 97]
let pseudoPrimes: [BigUInt] = [
/* 2 */ 2_047,
/* 3 */ 1_373_653,
/* 5 */ 25_326_001,
/* 7 */ 3_215_031_751,
/* 11 */ 2_152_302_898_747,
/* 13 */ 3_474_749_660_383,
/* 17 */ 341_550_071_728_321,
/* 19 */ 341_550_071_728_321,
/* 23 */ 3_825_123_056_546_413_051,
/* 29 */ 3_825_123_056_546_413_051,
/* 31 */ 3_825_123_056_546_413_051,
/* 37 */ "318665857834031151167461",
/* 41 */ "3317044064679887385961981",
]
for i in 0..<pseudoPrimes.count {
let candidate = pseudoPrimes[i]
print(candidate)
// SPPT should not rule out candidate's primality for primes less than prime[i + 1]
for j in 0...i {
XCTAssertTrue(candidate.isStrongProbablePrime(BigUInt(primes[j])))
}
// But the pseudoprimes aren't prime, so there is a base that disproves them.
let foo = (i + 1 ... i + 3).filter { !candidate.isStrongProbablePrime(BigUInt(primes[$0])) }
XCTAssertNotEqual(foo, [])
}
// Try the SPPT for some Mersenne numbers.
// Mersenne exponents from OEIS: https://oeis.org/A000043
XCTAssertFalse((BigUInt(1) << 606 - BigUInt(1)).isStrongProbablePrime(5))
XCTAssertTrue((BigUInt(1) << 607 - BigUInt(1)).isStrongProbablePrime(5)) // 2^607 - 1 is prime
XCTAssertFalse((BigUInt(1) << 608 - BigUInt(1)).isStrongProbablePrime(5))
XCTAssertFalse((BigUInt(1) << 520 - BigUInt(1)).isStrongProbablePrime(7))
XCTAssertTrue((BigUInt(1) << 521 - BigUInt(1)).isStrongProbablePrime(7)) // 2^521 -1 is prime
XCTAssertFalse((BigUInt(1) << 522 - BigUInt(1)).isStrongProbablePrime(7))
XCTAssertFalse((BigUInt(1) << 88 - BigUInt(1)).isStrongProbablePrime(128))
XCTAssertTrue((BigUInt(1) << 89 - BigUInt(1)).isStrongProbablePrime(128)) // 2^89 -1 is prime
XCTAssertFalse((BigUInt(1) << 90 - BigUInt(1)).isStrongProbablePrime(128))
// One extra test to exercise an a^2 % modulus == 1 case
XCTAssertFalse(BigUInt(217).isStrongProbablePrime(129))
}
func testIsPrime() {
XCTAssertFalse(BigUInt(0).isPrime())
XCTAssertFalse(BigUInt(1).isPrime())
XCTAssertTrue(BigUInt(2).isPrime())
XCTAssertTrue(BigUInt(3).isPrime())
XCTAssertFalse(BigUInt(4).isPrime())
XCTAssertTrue(BigUInt(5).isPrime())
// Try primality testing the first couple hundred Mersenne numbers comparing against the first few Mersenne exponents from OEIS: https://oeis.org/A000043
let mp: Set<Int> = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521]
for exponent in 2..<200 {
let m = BigUInt(1) << exponent - 1
XCTAssertEqual(m.isPrime(), mp.contains(exponent), "\(exponent)")
}
}
func testConversionToString() {
let sample = BigUInt("123456789ABCDEFEDCBA98765432123456789ABCDEF", radix: 16)!
// Radix = 10
XCTAssertEqual(String(BigUInt()), "0")
XCTAssertEqual(String(BigUInt(1)), "1")
XCTAssertEqual(String(BigUInt(100)), "100")
XCTAssertEqual(String(BigUInt(12345)), "12345")
XCTAssertEqual(String(BigUInt(123456789)), "123456789")
XCTAssertEqual(String(sample), "425693205796080237694414176550132631862392541400559")
// Radix = 16
XCTAssertEqual(String(BigUInt(0x1001), radix: 16), "1001")
XCTAssertEqual(String(BigUInt(0x0102030405060708), radix: 16), "102030405060708")
XCTAssertEqual(String(sample, radix: 16), "123456789abcdefedcba98765432123456789abcdef")
XCTAssertEqual(String(sample, radix: 16, uppercase: true), "123456789ABCDEFEDCBA98765432123456789ABCDEF")
// Radix = 2
XCTAssertEqual(String(BigUInt(12), radix: 2), "1100")
XCTAssertEqual(String(BigUInt(123), radix: 2), "1111011")
XCTAssertEqual(String(BigUInt(1234), radix: 2), "10011010010")
XCTAssertEqual(String(sample, radix: 2), "1001000110100010101100111100010011010101111001101111011111110110111001011101010011000011101100101010000110010000100100011010001010110011110001001101010111100110111101111")
// Radix = 31
XCTAssertEqual(String(BigUInt(30), radix: 31), "u")
XCTAssertEqual(String(BigUInt(31), radix: 31), "10")
XCTAssertEqual(String(BigUInt("10000000000000000", radix: 16)!, radix: 31), "nd075ib45k86g")
XCTAssertEqual(String(BigUInt("2908B5129F59DB6A41", radix: 16)!, radix: 31), "100000000000000")
XCTAssertEqual(String(sample, radix: 31), "ptf96helfaqi7ogc3jbonmccrhmnc2b61s")
let quickLook = BigUInt(513).playgroundDescription as? String
if quickLook == "513 (10 bits)" {
} else {
XCTFail("Unexpected playground QuickLook representation: \(quickLook ?? "nil")")
}
}
func testConversionFromString() {
let sample = "123456789ABCDEFEDCBA98765432123456789ABCDEF"
XCTAssertEqual(BigUInt("1"), 1)
XCTAssertEqual(BigUInt("123456789ABCDEF", radix: 16)!, 0x123456789ABCDEF)
XCTAssertEqual(BigUInt("1000000000000000000000"), BigUInt("3635C9ADC5DEA00000", radix: 16))
XCTAssertEqual(BigUInt("10000000000000000", radix: 16), BigUInt("18446744073709551616"))
XCTAssertEqual(BigUInt(sample, radix: 16)!, BigUInt("425693205796080237694414176550132631862392541400559"))
// We have to call BigUInt.init here because we don't want Literal initialization via coercion (SE-0213)
XCTAssertNil(BigUInt.init("Not a number"))
XCTAssertNil(BigUInt.init("X"))
XCTAssertNil(BigUInt.init("12349A"))
XCTAssertNil(BigUInt.init("000000000000000000000000A000"))
XCTAssertNil(BigUInt.init("00A0000000000000000000000000"))
XCTAssertNil(BigUInt.init("00 0000000000000000000000000"))
XCTAssertNil(BigUInt.init("\u{4e00}\u{4e03}")) // Chinese numerals "1", "7"
XCTAssertEqual(BigUInt("u", radix: 31)!, 30)
XCTAssertEqual(BigUInt("10", radix: 31)!, 31)
XCTAssertEqual(BigUInt("100000000000000", radix: 31)!, BigUInt("2908B5129F59DB6A41", radix: 16)!)
XCTAssertEqual(BigUInt("nd075ib45k86g", radix: 31)!, BigUInt("10000000000000000", radix: 16)!)
XCTAssertEqual(BigUInt("ptf96helfaqi7ogc3jbonmccrhmnc2b61s", radix: 31)!, BigUInt(sample, radix: 16)!)
XCTAssertNotNil(BigUInt(sample.repeated(100), radix: 16))
}
func testRandomIntegerWithMaximumWidth() {
XCTAssertEqual(BigUInt.randomInteger(withMaximumWidth: 0), 0)
let randomByte = BigUInt.randomInteger(withMaximumWidth: 8)
XCTAssertLessThan(randomByte, 256)
for _ in 0 ..< 100 {
XCTAssertLessThanOrEqual(BigUInt.randomInteger(withMaximumWidth: 1024).bitWidth, 1024)
}
// Verify that all widths <= maximum are produced (with a tiny maximum)
var widths: Set<Int> = [0, 1, 2, 3]
var i = 0
while !widths.isEmpty {
let random = BigUInt.randomInteger(withMaximumWidth: 3)
XCTAssertLessThanOrEqual(random.bitWidth, 3)
widths.remove(random.bitWidth)
i += 1
if i > 4096 {
XCTFail("randomIntegerWithMaximumWidth doesn't seem random")
break
}
}
// Verify that all bits are sometimes zero, sometimes one.
var oneBits = Set<Int>(0..<1024)
var zeroBits = Set<Int>(0..<1024)
while !oneBits.isEmpty || !zeroBits.isEmpty {
var random = BigUInt.randomInteger(withMaximumWidth: 1024)
for i in 0..<1024 {
if random[0] & 1 == 1 { oneBits.remove(i) }
else { zeroBits.remove(i) }
random >>= 1
}
}
}
func testRandomIntegerWithExactWidth() {
XCTAssertEqual(BigUInt.randomInteger(withExactWidth: 0), 0)
XCTAssertEqual(BigUInt.randomInteger(withExactWidth: 1), 1)
for _ in 0 ..< 1024 {
let randomByte = BigUInt.randomInteger(withExactWidth: 8)
XCTAssertEqual(randomByte.bitWidth, 8)
XCTAssertLessThan(randomByte, 256)
XCTAssertGreaterThanOrEqual(randomByte, 128)
}
for _ in 0 ..< 100 {
XCTAssertEqual(BigUInt.randomInteger(withExactWidth: 1024).bitWidth, 1024)
}
// Verify that all bits except the top are sometimes zero, sometimes one.
var oneBits = Set<Int>(0..<1023)
var zeroBits = Set<Int>(0..<1023)
while !oneBits.isEmpty || !zeroBits.isEmpty {
var random = BigUInt.randomInteger(withExactWidth: 1024)
for i in 0..<1023 {
if random[0] & 1 == 1 { oneBits.remove(i) }
else { zeroBits.remove(i) }
random >>= 1
}
}
}
func testRandomIntegerLessThan() {
// Verify that all bits in random integers generated by `randomIntegerLessThan` are sometimes zero, sometimes one.
//
// The limit starts with "11" so that generated random integers may easily begin with all combos.
// Also, 25% of the time the initial random int will be rejected as higher than the
// limit -- this helps stabilize code coverage.
let limit = BigUInt(3) << 1024
var oneBits = Set<Int>(0..<limit.bitWidth)
var zeroBits = Set<Int>(0..<limit.bitWidth)
for _ in 0..<100 {
var random = BigUInt.randomInteger(lessThan: limit)
XCTAssertLessThan(random, limit)
for i in 0..<limit.bitWidth {
if random[0] & 1 == 1 { oneBits.remove(i) }
else { zeroBits.remove(i) }
random >>= 1
}
}
XCTAssertEqual(oneBits, [])
XCTAssertEqual(zeroBits, [])
}
//
// you have to manually register linux tests here :-(
//
static var allTests = [
("testInit_WordBased", testInit_WordBased),
("testInit_BinaryInteger", testInit_BinaryInteger),
("testInit_FloatingPoint", testInit_FloatingPoint),
("testConversionToFloatingPoint", testConversionToFloatingPoint),
("testInit_Misc", testInit_Misc),
("testEnsureArray", testEnsureArray),
// ("testCapacity", testCapacity),
// ("testReserveCapacity", testReserveCapacity),
// ("testLoad", testLoad),
("testInitFromLiterals", testInitFromLiterals),
("testSubscriptingGetter", testSubscriptingGetter),
("testSubscriptingSetter", testSubscriptingSetter),
("testSlice", testSlice),
("testSigns", testSigns),
("testBits", testBits),
("testStrideableRequirements", testStrideableRequirements),
("testRightShift_ByWord", testRightShift_ByWord),
("testLeftShift_ByWord", testLeftShift_ByWord),
("testSplit", testSplit),
("testLowHigh", testLowHigh),
("testComparison", testComparison),
("testHashing", testHashing),
("testConversionFromBytes", testConversionFromBytes),
("testConversionToData", testConversionToData),
("testCodable", testCodable),
("testAddition", testAddition),
("testShiftedAddition", testShiftedAddition),
("testSubtraction", testSubtraction),
("testMultiplyByWord", testMultiplyByWord),
("testMultiplication", testMultiplication),
("testDivision", testDivision),
("testFactorial", testFactorial),
("testExponentiation", testExponentiation),
("testModularExponentiation", testModularExponentiation),
("testBitWidth", testBitWidth),
("testBitwise", testBitwise),
("testLeftShifts", testLeftShifts),
("testRightShifts", testRightShifts),
("testSquareRoot", testSquareRoot),
("testGCD", testGCD),
("testInverse", testInverse),
("testStrongProbablePrimeTest", testStrongProbablePrimeTest),
("testIsPrime", testIsPrime),
("testConversionToString", testConversionToString),
("testConversionFromString", testConversionFromString),
("testRandomIntegerWithMaximumWidth", testRandomIntegerWithMaximumWidth),
("testRandomIntegerWithExactWidth", testRandomIntegerWithExactWidth),
("testRandomIntegerLessThan", testRandomIntegerLessThan),
]
}
| 41.088889 | 221 | 0.559746 |
568ffc17d46341d13f88eea0844a9139f74f0bce | 29,686 | //
// ArgumentsTests.swift
// SwiftFormat
//
// Created by Nick Lockwood on 07/08/2018.
// Copyright © 2018 Nick Lockwood.
//
// Distributed under the permissive MIT license
// Get the latest version from here:
//
// https://github.com/nicklockwood/SwiftFormat
//
// 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 XCTest
@testable import SwiftFormat
class ArgumentsTests: XCTestCase {
// MARK: arg parser
func testParseSimpleArguments() {
let input = "hello world"
let output = ["", "hello", "world"]
XCTAssertEqual(parseArguments(input), output)
}
func testParseEscapedSpace() {
let input = "hello\\ world"
let output = ["", "hello world"]
XCTAssertEqual(parseArguments(input), output)
}
func testParseEscapedN() {
let input = "hello\\nworld"
let output = ["", "hellonworld"]
XCTAssertEqual(parseArguments(input), output)
}
func testParseQuoteArguments() {
let input = "\"hello world\""
let output = ["", "hello world"]
XCTAssertEqual(parseArguments(input), output)
}
func testParseEscapedQuote() {
let input = "hello \\\"world\\\""
let output = ["", "hello", "\"world\""]
XCTAssertEqual(parseArguments(input), output)
}
func testParseEscapedQuoteInString() {
let input = "\"hello \\\"world\\\"\""
let output = ["", "hello \"world\""]
XCTAssertEqual(parseArguments(input), output)
}
func testParseQuotedEscapedN() {
let input = "\"hello\\nworld\""
let output = ["", "hello\\nworld"]
XCTAssertEqual(parseArguments(input), output)
}
func testCommentedLine() {
let input = "#hello"
let output = [""]
XCTAssertEqual(parseArguments(input, ignoreComments: false), output)
}
func testCommentInLine() {
let input = "hello#world"
let output = ["", "hello"]
XCTAssertEqual(parseArguments(input, ignoreComments: false), output)
}
func testCommentAfterSpace() {
let input = "hello #world"
let output = ["", "hello"]
XCTAssertEqual(parseArguments(input, ignoreComments: false), output)
}
func testCommentBeforeSpace() {
let input = "hello# world"
let output = ["", "hello"]
XCTAssertEqual(parseArguments(input, ignoreComments: false), output)
}
func testCommentContainingSpace() {
let input = "hello #wide world"
let output = ["", "hello"]
XCTAssertEqual(parseArguments(input, ignoreComments: false), output)
}
func testEscapedComment() {
let input = "hello \\#world"
let output = ["", "hello", "#world"]
XCTAssertEqual(parseArguments(input, ignoreComments: false), output)
}
func testQuotedComment() {
let input = "hello \"#world\""
let output = ["", "hello", "#world"]
XCTAssertEqual(parseArguments(input, ignoreComments: false), output)
}
// MARK: arg preprocessor
func testPreprocessArguments() {
let input = ["", "foo", "bar", "-o", "baz", "-i", "4", "-l", "cr", "-s", "inline"]
let output = ["0": "", "1": "foo", "2": "bar", "output": "baz", "indent": "4", "linebreaks": "cr", "semicolons": "inline"]
XCTAssertEqual(try preprocessArguments(input, [
"output",
"indent",
"linebreaks",
"semicolons",
]), output)
}
func testEmptyArgsAreRecognized() {
let input = ["", "--help", "--version"]
let output = ["0": "", "help": "", "version": ""]
XCTAssertEqual(try preprocessArguments(input, [
"help",
"version",
]), output)
}
func testInvalidArgumentThrows() {
XCTAssertThrowsError(try preprocessArguments(["", "--vers"], [
"verbose",
"version",
])) { error in
XCTAssertEqual("\(error)", "Unknown option --vers. Did you mean --version?")
}
}
// merging
func testDuplicateDisableArgumentsAreMerged() {
let input = ["", "--disable", "foo", "--disable", "bar"]
let output = ["0": "", "disable": "foo,bar"]
XCTAssertEqual(try preprocessArguments(input, [
"disable",
]), output)
}
func testDuplicateExcludeArgumentsAreMerged() {
let input = ["", "--exclude", "foo", "--exclude", "bar"]
let output = ["0": "", "exclude": "foo,bar"]
XCTAssertEqual(try preprocessArguments(input, [
"exclude",
]), output)
}
func testDuplicateUnexcludeArgumentsAreMerged() {
let input = ["", "--unexclude", "foo", "--unexclude", "bar"]
let output = ["0": "", "unexclude": "foo,bar"]
XCTAssertEqual(try preprocessArguments(input, [
"unexclude",
]), output)
}
func testDuplicateSelfrequiredArgumentsAreMerged() {
let input = ["", "--selfrequired", "foo", "--selfrequired", "bar"]
let output = ["0": "", "selfrequired": "foo,bar"]
XCTAssertEqual(try preprocessArguments(input, [
"selfrequired",
]), output)
}
func testDuplicateNoSpaceOperatorsArgumentsAreMerged() {
let input = ["", "--nospaceoperators", "+", "--nospaceoperators", "*"]
let output = ["0": "", "nospaceoperators": "+,*"]
XCTAssertEqual(try preprocessArguments(input, [
"nospaceoperators",
]), output)
}
func testDuplicateNoWrapOperatorsArgumentsAreMerged() {
let input = ["", "--nowrapoperators", "+", "--nowrapoperators", "."]
let output = ["0": "", "nowrapoperators": "+,."]
XCTAssertEqual(try preprocessArguments(input, [
"nowrapoperators",
]), output)
}
func testDuplicateRangesArgumentsAreNotMerged() {
let input = ["", "--ranges", "spaced", "--ranges", "no-space"]
let output = ["0": "", "ranges": "no-space"]
XCTAssertEqual(try preprocessArguments(input, [
"ranges",
]), output)
}
// comma-delimited values
func testSpacesIgnoredInCommaDelimitedArguments() {
let input = ["", "--rules", "foo,", "bar"]
let output = ["0": "", "rules": "foo,bar"]
XCTAssertEqual(try preprocessArguments(input, [
"rules",
]), output)
}
func testNextArgumentNotIgnoredAfterCommaInArguments() {
let input = ["", "--enable", "foo,", "--disable", "bar"]
let output = ["0": "", "enable": "foo", "disable": "bar"]
XCTAssertEqual(try preprocessArguments(input, [
"enable",
"disable",
]), output)
}
// flags
func testVMatchesVerbose() {
let input = ["", "-v"]
let output = ["0": "", "verbose": ""]
XCTAssertEqual(try preprocessArguments(input, commandLineArguments), output)
}
func testHMatchesHelp() {
let input = ["", "-h"]
let output = ["0": "", "help": ""]
XCTAssertEqual(try preprocessArguments(input, commandLineArguments), output)
}
func testOMatchesOutput() {
let input = ["", "-o"]
let output = ["0": "", "output": ""]
XCTAssertEqual(try preprocessArguments(input, commandLineArguments), output)
}
func testNoMatchFlagThrows() {
let input = ["", "-v"]
XCTAssertThrowsError(try preprocessArguments(input, [
"help", "file",
]))
}
// MARK: format options to arguments
func testCommandLineArgumentsHaveValidNames() {
for key in argumentsFor(.default).keys {
XCTAssertTrue(optionsArguments.contains(key), "\(key) is not a valid argument name")
}
}
func testFormattingArgumentsAreAllImplemented() throws {
CLI.print = { _, _ in }
for key in formattingArguments {
guard let value = argumentsFor(.default)[key] else {
XCTAssert(deprecatedArguments.contains(key))
continue
}
XCTAssert(!deprecatedArguments.contains(key), key)
_ = try formatOptionsFor([key: value])
}
}
func testEmptyFormatOptions() throws {
XCTAssertNil(try formatOptionsFor([:]))
XCTAssertNil(try formatOptionsFor(["--disable": "void"]))
}
func testFileHeaderOptionToArguments() throws {
let options = FormatOptions(fileHeader: "// Hello World\n// Goodbye World")
let args = argumentsFor(Options(formatOptions: options), excludingDefaults: true)
XCTAssertEqual(args["header"], "// Hello World\\n// Goodbye World")
}
// TODO: should this go in OptionDescriptorTests instead?
func testRenamedArgument() throws {
XCTAssert(Descriptors.specifierOrder.isRenamed)
}
// MARK: config file parsing
func testParseArgumentsContainingBlankLines() {
let config = """
--allman true
--rules braces,fileHeader
"""
let data = Data(config.utf8)
do {
let args = try parseConfigFile(data)
XCTAssertEqual(args.count, 2)
} catch {
XCTFail("\(error)")
}
}
func testParseArgumentsContainingAnonymousValues() throws {
let config = """
hello
--allman true
"""
let data = Data(config.utf8)
XCTAssertThrowsError(try parseConfigFile(data)) { error in
guard case let FormatError.options(message) = error else {
XCTFail("\(error)")
return
}
XCTAssert(message.contains("hello"))
}
}
func testParseArgumentsContainingSpaces() throws {
let config = "--rules braces, fileHeader, consecutiveSpaces"
let data = Data(config.utf8)
let args = try parseConfigFile(data)
XCTAssertEqual(args.count, 1)
XCTAssertEqual(args["rules"], "braces, fileHeader, consecutiveSpaces")
}
func testParseArgumentsOnMultipleLines() throws {
let config = """
--rules braces, \\
fileHeader, \\
andOperator, typeSugar
--allman true
--hexgrouping \\
4, \\
8
"""
let data = Data(config.utf8)
let args = try parseConfigFile(data)
XCTAssertEqual(args["rules"], "braces, fileHeader, andOperator, typeSugar")
XCTAssertEqual(args["allman"], "true")
XCTAssertEqual(args["hexgrouping"], "4, 8")
}
func testCommentsInConsecutiveLines() throws {
let config = """
--rules braces, \\
# some comment
fileHeader, \\
# another comment invalidating this line separator \\
# yet another comment
andOperator
--hexgrouping \\
4, \\ # comment after line separator
8 # comment invalidating this line separator \\
"""
let data = Data(config.utf8)
let args = try parseConfigFile(data)
XCTAssertEqual(args["rules"], "braces, fileHeader, andOperator")
XCTAssertEqual(args["hexgrouping"], "4, 8")
}
func testLineContinuationCharacterOnLastLine() throws {
let config = """
--rules braces,\\
fileHeader\\
"""
let data = Data(config.utf8)
XCTAssertThrowsError(try parseConfigFile(data)) {
XCTAssert($0.localizedDescription.contains("line continuation character"))
}
}
func testParseArgumentsContainingEscapedCharacters() throws {
let config = "--header hello\\ world\\ngoodbye\\ world"
let data = Data(config.utf8)
let args = try parseConfigFile(data)
XCTAssertEqual(args.count, 1)
XCTAssertEqual(args["header"], "hello world\\ngoodbye world")
}
func testParseArgumentsContainingQuotedCharacters() throws {
let config = """
--header "hello world\\ngoodbye world"
"""
let data = Data(config.utf8)
let args = try parseConfigFile(data)
XCTAssertEqual(args.count, 1)
XCTAssertEqual(args["header"], "hello world\\ngoodbye world")
}
func testParseIgnoreFileHeader() throws {
let config = "--header ignore"
let data = Data(config.utf8)
let args = try parseConfigFile(data)
let options = try Options(args, in: "/")
XCTAssertEqual(options.formatOptions?.fileHeader, .ignore)
}
func testParseUppercaseIgnoreFileHeader() throws {
let config = "--header IGNORE"
let data = Data(config.utf8)
let args = try parseConfigFile(data)
let options = try Options(args, in: "/")
XCTAssertEqual(options.formatOptions?.fileHeader, .ignore)
}
func testParseArgumentsContainingSwiftVersion() throws {
let config = "--swiftversion 5.1"
let data = Data(config.utf8)
let args = try parseConfigFile(data)
XCTAssertEqual(args.count, 1)
XCTAssertEqual(args["swiftversion"], "5.1")
}
// MARK: config file serialization
// file header comment encoding
func testSerializeFileHeaderContainingSpace() throws {
let options = Options(formatOptions: FormatOptions(fileHeader: "// hello world"))
let config = serialize(options: options, excludingDefaults: true)
XCTAssertEqual(config, "--header \"// hello world\"")
}
func testSerializeFileHeaderContainingEscapedSpace() throws {
let options = Options(formatOptions: FormatOptions(fileHeader: "// hello\\ world"))
let config = serialize(options: options, excludingDefaults: true)
XCTAssertEqual(config, "--header \"// hello\\ world\"")
}
func testSerializeFileHeaderContainingLinebreak() throws {
let options = Options(formatOptions: FormatOptions(fileHeader: "//hello\nworld"))
let config = serialize(options: options, excludingDefaults: true)
XCTAssertEqual(config, "--header //hello\\nworld")
}
func testSerializeFileHeaderContainingLinebreakAndSpaces() throws {
let options = Options(formatOptions: FormatOptions(fileHeader: "// hello\n// world"))
let config = serialize(options: options, excludingDefaults: true)
XCTAssertEqual(config, "--header \"// hello\\n// world\"")
}
// trailing separator
func testSerializeOptionsDisabledDefaultRulesEnabledIsEmpty() throws {
let rules = allRules.subtracting(FormatRules.disabledByDefault)
let config: String = serialize(options: Options(formatOptions: nil, rules: rules))
XCTAssertEqual(config, "")
}
func testSerializeOptionsDisabledAllRulesEnabledNoTerminatingSeparator() throws {
let rules = allRules
let config: String = serialize(options: Options(formatOptions: nil, rules: rules))
XCTAssertFalse(config.contains("--disable"))
XCTAssertNotEqual(config.last, "\n")
}
func testSerializeOptionsDisabledSomeRulesDisabledNoTerminatingSeparator() throws {
let rules = Set(allRules.prefix(3)).subtracting(FormatRules.disabledByDefault)
let config: String = serialize(options: Options(formatOptions: nil, rules: rules))
XCTAssertTrue(config.contains("--disable"))
XCTAssertFalse(config.contains("--enable"))
XCTAssertNotEqual(config.last, "\n")
}
func testSerializeOptionsEnabledDefaultRulesEnabledNoTerminatingSeparator() throws {
let rules = allRules.subtracting(FormatRules.disabledByDefault)
let config: String = serialize(options: Options(formatOptions: .default, rules: rules))
XCTAssertNotEqual(config, "")
XCTAssertFalse(config.contains("--disable"))
XCTAssertFalse(config.contains("--enable"))
XCTAssertNotEqual(config.last, "\n")
}
func testSerializeOptionsEnabledAllRulesEnabledNoTerminatingSeparator() throws {
let rules = allRules
let config: String = serialize(options: Options(formatOptions: .default, rules: rules))
XCTAssertFalse(config.contains("--disable"))
XCTAssertNotEqual(config.last, "\n")
}
func testSerializeOptionsEnabledSomeRulesDisabledNoTerminatingSeparator() throws {
let rules = Set(allRules.prefix(3)).subtracting(FormatRules.disabledByDefault)
let config: String = serialize(options: Options(formatOptions: .default, rules: rules))
XCTAssertTrue(config.contains("--disable"))
XCTAssertFalse(config.contains("--enable"))
XCTAssertNotEqual(config.last, "\n")
}
// swift version
func testSerializeSwiftVersion() throws {
let version = Version(rawValue: "5.2") ?? "0"
let options = Options(formatOptions: FormatOptions(swiftVersion: version))
let config = serialize(options: options, excludingDefaults: true)
XCTAssertEqual(config, "--swiftversion 5.2")
}
// MARK: config file merging
func testMergeFormatOptionArguments() throws {
let args = ["allman": "false", "commas": "always"]
let config = ["allman": "true", "binarygrouping": "4,8"]
let result = try mergeArguments(args, into: config)
for (key, value) in result {
// args take precedence over config
XCTAssertEqual(value, args[key] ?? config[key])
}
for key in Set(args.keys).union(config.keys) {
// all keys should be present in result
XCTAssertNotNil(result[key])
}
}
func testMergeExcludedURLs() throws {
let args = ["exclude": "foo,bar"]
let config = ["exclude": "bar,baz"]
let result = try mergeArguments(args, into: config)
XCTAssertEqual(result["exclude"], "bar,baz,foo")
}
func testMergeUnexcludedURLs() throws {
let args = ["unexclude": "foo,bar"]
let config = ["unexclude": "bar,baz"]
let result = try mergeArguments(args, into: config)
XCTAssertEqual(result["unexclude"], "bar,baz,foo")
}
func testMergeRules() throws {
let args = ["rules": "braces,fileHeader"]
let config = ["rules": "consecutiveSpaces,braces"]
let result = try mergeArguments(args, into: config)
let rules = try parseRules(result["rules"]!)
XCTAssertEqual(rules, ["braces", "fileHeader"])
}
func testMergeEmptyRules() throws {
let args = ["rules": ""]
let config = ["rules": "consecutiveSpaces,braces"]
let result = try mergeArguments(args, into: config)
let rules = try parseRules(result["rules"]!)
XCTAssertEqual(Set(rules), Set(["braces", "consecutiveSpaces"]))
}
func testMergeEnableRules() throws {
let args = ["enable": "braces,fileHeader"]
let config = ["enable": "consecutiveSpaces,braces"]
let result = try mergeArguments(args, into: config)
let enabled = try parseRules(result["enable"]!)
XCTAssertEqual(enabled, ["braces", "consecutiveSpaces", "fileHeader"])
}
func testMergeDisableRules() throws {
let args = ["disable": "braces,fileHeader"]
let config = ["disable": "consecutiveSpaces,braces"]
let result = try mergeArguments(args, into: config)
let disabled = try parseRules(result["disable"]!)
XCTAssertEqual(disabled, ["braces", "consecutiveSpaces", "fileHeader"])
}
func testRulesArgumentOverridesAllConfigRules() throws {
let args = ["rules": "braces,fileHeader"]
let config = ["rules": "consecutiveSpaces", "disable": "braces", "enable": "redundantSelf"]
let result = try mergeArguments(args, into: config)
let disabled = try parseRules(result["rules"]!)
XCTAssertEqual(disabled, ["braces", "fileHeader"])
XCTAssertNil(result["enabled"])
XCTAssertNil(result["disabled"])
}
func testEnabledArgumentOverridesConfigRules() throws {
let args = ["enable": "braces"]
let config = ["rules": "fileHeader", "disable": "consecutiveSpaces,braces"]
let result = try mergeArguments(args, into: config)
let rules = try parseRules(result["rules"]!)
XCTAssertEqual(rules, ["fileHeader"])
let enabled = try parseRules(result["enable"]!)
XCTAssertEqual(enabled, ["braces"])
let disabled = try parseRules(result["disable"]!)
XCTAssertEqual(disabled, ["consecutiveSpaces"])
}
func testDisableArgumentOverridesConfigRules() throws {
let args = ["disable": "braces"]
let config = ["rules": "braces,fileHeader", "enable": "consecutiveSpaces,braces"]
let result = try mergeArguments(args, into: config)
let rules = try parseRules(result["rules"]!)
XCTAssertEqual(rules, ["fileHeader"])
let enabled = try parseRules(result["enable"]!)
XCTAssertEqual(enabled, ["consecutiveSpaces"])
let disabled = try parseRules(result["disable"]!)
XCTAssertEqual(disabled, ["braces"])
}
func testMergeSelfRequiredOptions() throws {
let args = ["selfrequired": "log,assert"]
let config = ["selfrequired": "expect"]
let result = try mergeArguments(args, into: config)
let selfRequired = parseCommaDelimitedList(result["selfrequired"]!)
XCTAssertEqual(selfRequired, ["assert", "expect", "log"])
}
// MARK: add arguments
func testAddFormatArguments() throws {
var options = Options(
formatOptions: FormatOptions(indent: " ", allowInlineSemicolons: true)
)
try options.addArguments(["indent": "2", "linebreaks": "crlf"], in: "")
guard let formatOptions = options.formatOptions else {
XCTFail()
return
}
XCTAssertEqual(formatOptions.indent, " ")
XCTAssertEqual(formatOptions.linebreak, "\r\n")
XCTAssertTrue(formatOptions.allowInlineSemicolons)
}
func testAddArgumentsDoesntBreakSwiftVersion() throws {
var options = Options(formatOptions: FormatOptions(swiftVersion: "4.2"))
try options.addArguments(["indent": "2"], in: "")
guard let formatOptions = options.formatOptions else {
XCTFail()
return
}
XCTAssertEqual(formatOptions.swiftVersion, "4.2")
}
func testAddArgumentsDoesntBreakFragment() throws {
var options = Options(formatOptions: FormatOptions(fragment: true))
try options.addArguments(["indent": "2"], in: "")
guard let formatOptions = options.formatOptions else {
XCTFail()
return
}
XCTAssertTrue(formatOptions.fragment)
}
func testAddArgumentsDoesntBreakFileInfo() throws {
let fileInfo = FileInfo(filePath: "~/Foo.swift", creationDate: Date())
var options = Options(formatOptions: FormatOptions(fileInfo: fileInfo))
try options.addArguments(["indent": "2"], in: "")
guard let formatOptions = options.formatOptions else {
XCTFail()
return
}
XCTAssertEqual(formatOptions.fileInfo, fileInfo)
}
// MARK: options parsing
func testParseEmptyOptions() throws {
let options = try Options([:], in: "")
XCTAssertNil(options.formatOptions)
XCTAssertNil(options.fileOptions)
XCTAssertEqual(options.rules, allRules.subtracting(FormatRules.disabledByDefault))
}
func testParseExcludedURLsFileOption() throws {
let options = try Options(["exclude": "foo bar, baz"], in: "/dir")
let paths = options.fileOptions?.excludedGlobs.map { $0.description } ?? []
XCTAssertEqual(paths, ["/dir/foo bar", "/dir/baz"])
}
func testParseUnexcludedURLsFileOption() throws {
let options = try Options(["unexclude": "foo bar, baz"], in: "/dir")
let paths = options.fileOptions?.unexcludedGlobs.map { $0.description } ?? []
XCTAssertEqual(paths, ["/dir/foo bar", "/dir/baz"])
}
func testParseDeprecatedOption() throws {
let options = try Options(["ranges": "nospace"], in: "")
XCTAssertEqual(options.formatOptions?.spaceAroundRangeOperators, false)
}
func testParseNoSpaceOperatorsOption() throws {
let options = try Options(["nospaceoperators": "...,..<"], in: "")
XCTAssertEqual(options.formatOptions?.noSpaceOperators, ["...", "..<"])
}
func testParseNoWrapOperatorsOption() throws {
let options = try Options(["nowrapoperators": ".,:,*"], in: "")
XCTAssertEqual(options.formatOptions?.noWrapOperators, [".", ":", "*"])
}
func testParseModifierOrderOption() throws {
let options = try Options(["modifierorder": "private(set),public,unowned"], in: "")
XCTAssertEqual(options.formatOptions?.modifierOrder, ["private(set)", "public", "unowned"])
}
func testParseParameterizedModifierOrderOption() throws {
let options = try Options(["modifierorder": "unowned(unsafe),unowned(safe)"], in: "")
XCTAssertEqual(options.formatOptions?.modifierOrder, ["unowned(unsafe)", "unowned(safe)"])
}
func testParseInvalidModifierOrderOption() throws {
XCTAssertThrowsError(try Options(["modifierorder": "unknowned"], in: "")) { error in
XCTAssertEqual("\(error)", "'unknowned' is not a valid modifier (did you mean 'unowned'?) in --modifierorder")
}
}
func testParseSpecifierOrderOption() throws {
let options = try Options(["specifierorder": "private(set),public"], in: "")
XCTAssertEqual(options.formatOptions?.modifierOrder, ["private(set)", "public"])
}
func testParseSwiftVersionOption() throws {
let options = try Options(["swiftversion": "4.2"], in: "")
XCTAssertEqual(options.formatOptions?.swiftVersion, "4.2")
}
// MARK: parse rules
func testParseRulesCaseInsensitive() throws {
let rules = try parseRules("strongoutlets")
XCTAssertEqual(rules, ["strongOutlets"])
}
func testParseAllRule() throws {
let rules = try parseRules("all")
XCTAssertEqual(rules, FormatRules.all.compactMap {
$0.isDeprecated ? nil : $0.name
})
}
func testParseInvalidRuleThrows() {
XCTAssertThrowsError(try parseRules("strongOutlet")) { error in
XCTAssertEqual("\(error)", "Unknown rule 'strongOutlet'. Did you mean 'strongOutlets'?")
}
}
func testParseOptionAsRuleThrows() {
XCTAssertThrowsError(try parseRules("importgrouping")) { error in
XCTAssert("\(error)".contains("'sortedImports'"))
}
}
// MARK: lintonly
func testLintonlyRulesContain() throws {
let options = try Options(["lint": "", "lintonly": "wrapEnumCases"], in: "")
XCTAssert(options.rules?.contains("wrapEnumCases") == true)
let arguments = argumentsFor(options)
XCTAssertEqual(arguments, ["lint": "", "enable": "wrapEnumCases"])
}
func testLintonlyRulesDontContain() throws {
let options = try Options(["lintonly": "unusedArguments"], in: "")
XCTAssert(options.rules?.contains("unusedArguments") == false)
let arguments = argumentsFor(options)
XCTAssertEqual(arguments, ["disable": "unusedArguments"])
}
func testLintonlyMergeOptionsAdd() throws {
var options = try Options(["lint": "", "disable": "unusedArguments"], in: "")
try options.addArguments(["lintonly": "unusedArguments"], in: "")
XCTAssert(options.rules?.contains("unusedArguments") == true)
}
func testLintonlyMergeOptionsRemove() throws {
var options = try Options(["enable": "wrapEnumCases"], in: "")
try options.addArguments(["lintonly": "wrapEnumCases"], in: "")
XCTAssert(options.rules?.contains("wrapEnumCases") == false)
}
// MARK: Edit distance
func testEditDistance() {
XCTAssertEqual("foo".editDistance(from: "fob"), 1)
XCTAssertEqual("foo".editDistance(from: "boo"), 1)
XCTAssertEqual("foo".editDistance(from: "bar"), 3)
XCTAssertEqual("aba".editDistance(from: "bbb"), 2)
XCTAssertEqual("foob".editDistance(from: "foo"), 1)
XCTAssertEqual("foo".editDistance(from: "foob"), 1)
XCTAssertEqual("foo".editDistance(from: "Foo"), 1)
XCTAssertEqual("FOO".editDistance(from: "foo"), 3)
}
func testEditDistanceWithEmptyStrings() {
XCTAssertEqual("foo".editDistance(from: ""), 3)
XCTAssertEqual("".editDistance(from: "foo"), 3)
XCTAssertEqual("".editDistance(from: ""), 0)
}
}
| 37.529709 | 130 | 0.618675 |
11910f43db2e6175fd4095231c51501ab6e53535 | 1,103 | //
// UITableView.swift
// My University
//
// Created by Yura Voevodin on 15.09.2021.
// Copyright © 2021 Yura Voevodin. All rights reserved.
//
import UIKit
public extension UITableView {
/// Get IndexPath of row with cell, that contains a view
///
/// - Parameter view: UIView in UITableViewCell
/// - Returns: IndexPath or nil if not found
func indexPath(for view: UIView) -> IndexPath? {
let viewLocation = convert(view.bounds.origin, from: view)
return indexPathForRow(at: viewLocation)
}
func register<T: UITableViewCell>(_: T.Type) where T: ReusableView, T: NibLoadableView {
let nib = UINib(nibName: T.nibName, bundle: nil)
register(nib, forCellReuseIdentifier: T.reuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)")
}
return cell
}
}
| 32.441176 | 108 | 0.673617 |
dbe5ad22341e339e40b9c17c1f3aa72401bfe023 | 22,224 | //
// TransformOperators.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2016-09-26.
// Copyright © 2016 hearst. All rights reserved.
//
import Foundation
// MARK:- Transforms
/// Object of Basic type with Transform
public func <- <Transform: TransformType>(left: inout Transform.Object, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let value = transform.transformFromJSON(map.currentValue)
FromJSON.basicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: Transform.Object, right: (Map, Transform)) {
let (map, transform) = right
if map.mappingType == .toJSON {
let value: Transform.JSON? = transform.transformToJSON(left)
ToJSON.optionalBasicType(value, map: map)
}
}
/// Optional object of basic type with Transform
public func <- <Transform: TransformType>(left: inout Transform.Object?, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let value = transform.transformFromJSON(map.currentValue)
FromJSON.optionalBasicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: Transform.Object?, right: (Map, Transform)) {
let (map, transform) = right
if map.mappingType == .toJSON {
let value: Transform.JSON? = transform.transformToJSON(left)
ToJSON.optionalBasicType(value, map: map)
}
}
/// Implicitly unwrapped optional object of basic type with Transform
public func <- <Transform: TransformType>(left: inout Transform.Object!, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let value = transform.transformFromJSON(map.currentValue)
FromJSON.optionalBasicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
/// Array of Basic type with Transform
public func <- <Transform: TransformType>(left: inout [Transform.Object], right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let values = fromJSONArrayWithTransform(map.currentValue, transform: transform)
FromJSON.basicType(&left, object: values)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: [Transform.Object], right: (Map, Transform)) {
let (map, transform) = right
if map.mappingType == .toJSON{
let values = toJSONArrayWithTransform(left, transform: transform)
ToJSON.optionalBasicType(values, map: map)
}
}
/// Optional array of Basic type with Transform
public func <- <Transform: TransformType>(left: inout [Transform.Object]?, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let values = fromJSONArrayWithTransform(map.currentValue, transform: transform)
FromJSON.optionalBasicType(&left, object: values)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: [Transform.Object]?, right: (Map, Transform)) {
let (map, transform) = right
if map.mappingType == .toJSON {
let values = toJSONArrayWithTransform(left, transform: transform)
ToJSON.optionalBasicType(values, map: map)
}
}
/// Implicitly unwrapped optional array of Basic type with Transform
public func <- <Transform: TransformType>(left: inout [Transform.Object]!, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let values = fromJSONArrayWithTransform(map.currentValue, transform: transform)
FromJSON.optionalBasicType(&left, object: values)
case .toJSON:
left >>> right
default: ()
}
}
/// Dictionary of Basic type with Transform
public func <- <Transform: TransformType>(left: inout [String: Transform.Object], right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform)
FromJSON.basicType(&left, object: values)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: [String: Transform.Object], right: (Map, Transform)) {
let (map, transform) = right
if map.mappingType == . toJSON {
let values = toJSONDictionaryWithTransform(left, transform: transform)
ToJSON.optionalBasicType(values, map: map)
}
}
/// Optional dictionary of Basic type with Transform
public func <- <Transform: TransformType>(left: inout [String: Transform.Object]?, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform)
FromJSON.optionalBasicType(&left, object: values)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: [String: Transform.Object]?, right: (Map, Transform)) {
let (map, transform) = right
if map.mappingType == .toJSON {
let values = toJSONDictionaryWithTransform(left, transform: transform)
ToJSON.optionalBasicType(values, map: map)
}
}
/// Implicitly unwrapped optional dictionary of Basic type with Transform
public func <- <Transform: TransformType>(left: inout [String: Transform.Object]!, right: (Map, Transform)) {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform)
FromJSON.optionalBasicType(&left, object: values)
case .toJSON:
left >>> right
default: ()
}
}
// MARK:- Transforms of Mappable Objects - <T: BaseMappable>
/// Object conforming to Mappable that have transforms
public func <- <Transform: TransformType>(left: inout Transform.Object, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let value: Transform.Object? = transform.transformFromJSON(map.currentValue)
FromJSON.basicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: Transform.Object, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let value: Transform.JSON? = transform.transformToJSON(left)
ToJSON.optionalBasicType(value, map: map)
}
}
/// Optional Mappable objects that have transforms
public func <- <Transform: TransformType>(left: inout Transform.Object?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let value: Transform.Object? = transform.transformFromJSON(map.currentValue)
FromJSON.optionalBasicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: Transform.Object?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON{
let value: Transform.JSON? = transform.transformToJSON(left)
ToJSON.optionalBasicType(value, map: map)
}
}
/// Implicitly unwrapped optional Mappable objects that have transforms
public func <- <Transform: TransformType>(left: inout Transform.Object!, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let value: Transform.Object? = transform.transformFromJSON(map.currentValue)
FromJSON.optionalBasicType(&left, object: value)
case .toJSON:
left >>> right
default: ()
}
}
// MARK:- Dictionary of Mappable objects with a transform - Dictionary<String, T: BaseMappable>
/// Dictionary of Mappable objects <String, T: Mappable> with a transform
public func <- <Transform: TransformType>(left: inout Dictionary<String, Transform.Object>, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .fromJSON && map.isKeyPresent,
let object = map.currentValue as? [String: AnyObject] {
let value = fromJSONDictionaryWithTransform(object as AnyObject?, transform: transform) ?? left
FromJSON.basicType(&left, object: value)
} else if map.mappingType == .toJSON {
left >>> right
}
}
public func >>> <Transform: TransformType>(left: Dictionary<String, Transform.Object>, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let value = toJSONDictionaryWithTransform(left, transform: transform)
ToJSON.basicType(value, map: map)
}
}
/// Optional Dictionary of Mappable object <String, T: Mappable> with a transform
public func <- <Transform: TransformType>(left: inout Dictionary<String, Transform.Object>?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .fromJSON && map.isKeyPresent, let object = map.currentValue as? [String : AnyObject]{
let value = fromJSONDictionaryWithTransform(object as AnyObject?, transform: transform) ?? left
FromJSON.optionalBasicType(&left, object: value)
} else if map.mappingType == .toJSON {
left >>> right
}
}
public func >>> <Transform: TransformType>(left: Dictionary<String, Transform.Object>?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let value = toJSONDictionaryWithTransform(left, transform: transform)
ToJSON.optionalBasicType(value, map: map)
}
}
/// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> with a transform
public func <- <Transform: TransformType>(left: inout Dictionary<String, Transform.Object>!, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .fromJSON && map.isKeyPresent, let dictionary = map.currentValue as? [String : AnyObject]{
let transformedDictionary = fromJSONDictionaryWithTransform(dictionary as AnyObject?, transform: transform) ?? left
FromJSON.optionalBasicType(&left, object: transformedDictionary)
} else if map.mappingType == .toJSON {
left >>> right
}
}
/// Dictionary of Mappable objects <String, T: Mappable> with a transform
public func <- <Transform: TransformType>(left: inout Dictionary<String, [Transform.Object]>, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if let dictionary = map.currentValue as? [String : [AnyObject]], map.mappingType == .fromJSON && map.isKeyPresent {
let transformedDictionary = dictionary.map { (key: String, values: [AnyObject]) -> (String, [Transform.Object]) in
if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) {
return (key, jsonArray)
}
if let leftValue = left[key] {
return (key, leftValue)
}
return (key, [])
}
FromJSON.basicType(&left, object: transformedDictionary)
} else if map.mappingType == .toJSON {
left >>> right
}
}
public func >>> <Transform: TransformType>(left: Dictionary<String, [Transform.Object]>, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let transformedDictionary = left.map { (key, values) in
return (key, toJSONArrayWithTransform(values, transform: transform) ?? [])
}
ToJSON.basicType(transformedDictionary, map: map)
}
}
/// Optional Dictionary of Mappable object <String, T: Mappable> with a transform
public func <- <Transform: TransformType>(left: inout Dictionary<String, [Transform.Object]>?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if let dictionary = map.currentValue as? [String : [AnyObject]], map.mappingType == .fromJSON && map.isKeyPresent {
let transformedDictionary = dictionary.map { (key: String, values: [AnyObject]) -> (String, [Transform.Object]) in
if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) {
return (key, jsonArray)
}
if let leftValue = left?[key] {
return (key, leftValue)
}
return (key, [])
}
FromJSON.optionalBasicType(&left, object: transformedDictionary)
} else if map.mappingType == .toJSON {
left >>> right
}
}
public func >>> <Transform: TransformType>(left: Dictionary<String, [Transform.Object]>?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let transformedDictionary = left?.map { (key, values) in
return (key, toJSONArrayWithTransform(values, transform: transform) ?? [])
}
ToJSON.optionalBasicType(transformedDictionary, map: map)
}
}
/// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> with a transform
public func <- <Transform: TransformType>(left: inout Dictionary<String, [Transform.Object]>!, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if let dictionary = map.currentValue as? [String : [AnyObject]], map.mappingType == .fromJSON && map.isKeyPresent {
let transformedDictionary = dictionary.map { (key: String, values: [AnyObject]) -> (String, [Transform.Object]) in
if let jsonArray = fromJSONArrayWithTransform(values, transform: transform) {
return (key, jsonArray)
}
if let leftValue = left?[key] {
return (key, leftValue)
}
return (key, [])
}
FromJSON.optionalBasicType(&left, object: transformedDictionary)
} else if map.mappingType == .toJSON {
left >>> right
}
}
// MARK:- Array of Mappable objects with transforms - Array<T: BaseMappable>
/// Array of Mappable objects
public func <- <Transform: TransformType>(left: inout Array<Transform.Object>, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) {
FromJSON.basicType(&left, object: transformedValues)
}
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: Array<Transform.Object>, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let transformedValues = toJSONArrayWithTransform(left, transform: transform)
ToJSON.optionalBasicType(transformedValues, map: map)
}
}
/// Optional array of Mappable objects
public func <- <Transform: TransformType>(left: inout Array<Transform.Object>?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform)
FromJSON.optionalBasicType(&left, object: transformedValues)
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: Array<Transform.Object>?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let transformedValues = toJSONArrayWithTransform(left, transform: transform)
ToJSON.optionalBasicType(transformedValues, map: map)
}
}
/// Implicitly unwrapped Optional array of Mappable objects
public func <- <Transform: TransformType>(left: inout Array<Transform.Object>!, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform)
FromJSON.optionalBasicType(&left, object: transformedValues)
case .toJSON:
left >>> right
default: ()
}
}
// MARK:- Array of Array of Mappable objects - Array<Array<T: BaseMappable>>> with transforms
/// Array of Array Mappable objects with transform
public func <- <Transform: TransformType>(left: inout Array<Array<Transform.Object>>, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .fromJSON && map.isKeyPresent, let original2DArray = map.currentValue as? [[AnyObject]]{
let transformed2DArray = original2DArray.flatMap { values in
fromJSONArrayWithTransform(values as AnyObject?, transform: transform)
}
FromJSON.basicType(&left, object: transformed2DArray)
} else if map.mappingType == .toJSON {
left >>> right
}
}
public func >>> <Transform: TransformType>(left: Array<Array<Transform.Object>>, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let transformed2DArray = left.flatMap { values in
toJSONArrayWithTransform(values, transform: transform)
}
ToJSON.basicType(transformed2DArray, map: map)
}
}
/// Optional array of Mappable objects with transform
public func <- <Transform: TransformType>(left:inout Array<Array<Transform.Object>>?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .fromJSON && map.isKeyPresent, let original2DArray = map.currentValue as? [[AnyObject]]{
let transformed2DArray = original2DArray.flatMap { values in
fromJSONArrayWithTransform(values as AnyObject?, transform: transform)
}
FromJSON.optionalBasicType(&left, object: transformed2DArray)
} else if map.mappingType == .toJSON {
left >>> right
}
}
public func >>> <Transform: TransformType>(left: Array<Array<Transform.Object>>?, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let transformed2DArray = left?.flatMap { values in
toJSONArrayWithTransform(values, transform: transform)
}
ToJSON.optionalBasicType(transformed2DArray, map: map)
}
}
/// Implicitly unwrapped Optional array of Mappable objects with transform
public func <- <Transform: TransformType>(left: inout Array<Array<Transform.Object>>!, right: (Map, Transform)) where Transform.Object: BaseMappable {
let (map, transform) = right
if map.mappingType == .fromJSON && map.isKeyPresent, let original2DArray = map.currentValue as? [[AnyObject]] {
let transformed2DArray = original2DArray.flatMap { values in
fromJSONArrayWithTransform(values as AnyObject?, transform: transform)
}
FromJSON.optionalBasicType(&left, object: transformed2DArray)
} else if map.mappingType == .toJSON {
left >>> right
}
}
// MARK:- Set of Mappable objects with a transform - Set<T: BaseMappable where T: Hashable>
/// Set of Mappable objects with transform
public func <- <Transform: TransformType>(left: inout Set<Transform.Object>, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) {
FromJSON.basicType(&left, object: Set(transformedValues))
}
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: Set<Transform.Object>, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
let transformedValues = toJSONArrayWithTransform(Array(left), transform: transform)
ToJSON.optionalBasicType(transformedValues, map: map)
}
}
/// Optional Set of Mappable objects with transform
public func <- <Transform: TransformType>(left: inout Set<Transform.Object>?, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) {
FromJSON.basicType(&left, object: Set(transformedValues))
}
case .toJSON:
left >>> right
default: ()
}
}
public func >>> <Transform: TransformType>(left: Set<Transform.Object>?, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable {
let (map, transform) = right
if map.mappingType == .toJSON {
if let values = left {
let transformedValues = toJSONArrayWithTransform(Array(values), transform: transform)
ToJSON.optionalBasicType(transformedValues, map: map)
}
}
}
/// Implicitly unwrapped Optional set of Mappable objects with transform
public func <- <Transform: TransformType>(left: inout Set<Transform.Object>!, right: (Map, Transform)) where Transform.Object: Hashable & BaseMappable {
let (map, transform) = right
switch map.mappingType {
case .fromJSON where map.isKeyPresent:
if let transformedValues = fromJSONArrayWithTransform(map.currentValue, transform: transform) {
FromJSON.basicType(&left, object: Set(transformedValues))
}
case .toJSON:
left >>> right
default: ()
}
}
private func fromJSONArrayWithTransform<Transform: TransformType>(_ input: Any?, transform: Transform) -> [Transform.Object]? {
if let values = input as? [AnyObject] {
return values.flatMap { value in
return transform.transformFromJSON(value)
}
} else {
return nil
}
}
private func fromJSONDictionaryWithTransform<Transform: TransformType>(_ input: Any?, transform: Transform) -> [String: Transform.Object]? {
if let values = input as? [String: AnyObject] {
return values.filterMap { value in
return transform.transformFromJSON(value)
}
} else {
return nil
}
}
private func toJSONArrayWithTransform<Transform: TransformType>(_ input: [Transform.Object]?, transform: Transform) -> [Transform.JSON]? {
return input?.flatMap { value in
return transform.transformToJSON(value)
}
}
private func toJSONDictionaryWithTransform<Transform: TransformType>(_ input: [String: Transform.Object]?, transform: Transform) -> [String: Transform.JSON]? {
return input?.filterMap { value in
return transform.transformToJSON(value)
}
}
| 36.61285 | 159 | 0.735466 |
46b8d71a2d6421ea9c8c909a0c95c737e277e5b2 | 1,725 | //
// AssetLoaderAssetLoaderRouter.swift
// AsciiArtPlayer
//
// Created by Sergey Teryokhin on 27/12/2016.
// Copyright © 2016 iMacDev. All rights reserved.
//
import ViperMcFlurry
class AssetLoaderRouter: NSObject, AssetLoaderRouterInput {
//fileprivate let mainStoryBoard = R.storyboard.main()
//fileprivate let segueIdentifier = "YourSegueID"
//fileprivate let moduleID = "YOURVIEWCONTROLLERID"
var transitionHandler: RamblerViperModuleTransitionHandlerProtocol!
//var moduleFactory: RamblerViperModuleFactory {
// let factory = RamblerViperModuleFactory(storyboard: mainStoryBoard, andRestorationId: moduleID)
//
// return factory!
//}
//Open module use Segue
// func showModule() {
// transitionHandler.openModule!(usingSegue: segueIdentifier).thenChain { moduleInput in
// guard let myModuleInput = moduleInput as? YOURModuleInput else {
// fatalError("invalid module type")
// }
//
// myModuleInput.configure()
//
// return nil
// }
// }
//func showPlayer() {
// self.transitionHandler.openModule!(usingFactory: moduleFactory) { sourceModuleTransitionHandler, destinationModuleTransitionHandler in
// let sourceVC = sourceModuleTransitionHandler as! UIViewController
// let destinationVC = destinationModuleTransitionHandler as! UIViewController
// sourceVC.navigationController?.pushViewController(destinationVC, animated: true)
// }.thenChain { moduleInput in
// guard let moduleInput = moduleInput as? YOURModuleInput else {
// fatalError("invalid module type")
// }
// moduleInput.configure()
//
// return nil
// }
//}
}
| 33.173077 | 140 | 0.691014 |
08efae841b6de2cbfa74c9f24516d6ab4f637573 | 14,992 | //
// QMUIStaticTableViewCellDataSource.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/4/23.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
/**
* 这个控件是为了方便地实现那种类似设置界面的列表(每个 cell 的样式、内容、操作控件均不太一样,每个 cell 之间不复用),使用方式:
* 1. 创建一个带 UITableView 的 viewController。
* 2. 通过 init 或 initWithCellDataSections: 创建一个 dataSource。若通过 init 方法初始化,则请在 tableView 渲染前(viewDidLoad 或更早)手动设置一个 cellDataSections 数组。
* 3. 将第 2 步里的 dataSource 赋值给 tableView.qmui_staticCellDataSource 即可完成一般情况下的界面展示。
* 4. 若需要重写某些 UITableViewDataSource、UITableViewDelegate 方法,则在 viewController 里直接实现该方法,并在方法里调用 QMUIStaticTableViewCellDataSource (Manual) 提供的同名方法即可,具体可参考 QMUI Demo。
*/
class QMUIStaticTableViewCellDataSource: NSObject {
/// 列表的数据源,是一个二维数组,其中一维表示 section,二维表示某个 section 里的 rows,每次调用这个属性的 setter 方法都会自动刷新 tableView 内容。
var cellDataSections: [[QMUIStaticTableViewCellData]] {
didSet {
tableView?.reloadData()
}
}
// 在 UITableView (QMUI_StaticCell) 那边会把 tableView 的 property 改为 readwrite,所以这里补上 setter
fileprivate(set) var tableView: UITableView? {
didSet {
let delegate = tableView?.delegate
tableView?.delegate = nil
tableView?.delegate = delegate
let dataSource = tableView?.dataSource
tableView?.dataSource = nil
tableView?.dataSource = dataSource
}
}
override init() {
self.cellDataSections = [[QMUIStaticTableViewCellData]]()
super.init()
}
convenience init(cellDataSections: [[QMUIStaticTableViewCellData]]) {
self.init()
self.cellDataSections = cellDataSections
}
// MARK: 当需要重写某些 UITableViewDataSource、UITableViewDelegate 方法时,这个分类里提供的同名方法需要在该方法中被调用,否则可能导致 QMUIStaticTableViewCellData 里设置的一些值无效。
/**
* 从 dataSource 里获取处于 indexPath 位置的 QMUIStaticTableViewCellData 对象
* @param indexPath cell 所处的位置
*/
func cellData(at indexPath: IndexPath) -> QMUIStaticTableViewCellData? {
if indexPath.section >= cellDataSections.count {
print("cellDataWithIndexPath:\(indexPath), data not exist in section!")
return nil
}
let rowDatas = cellDataSections[indexPath.section]
if indexPath.row >= rowDatas.count {
print("cellDataWithIndexPath:\(indexPath), data not exist in row!")
return nil
}
let cellData = rowDatas[indexPath.row]
cellData.indexPath = indexPath // 在这里才为 cellData.indexPath 赋值
return cellData
}
/**
* 根据 dataSource 计算出指定的 indexPath 的 cell 所对应的 reuseIdentifier(static tableView 里一般每个 cell 的 reuseIdentifier 都是不一样的,避免复用)
* @param indexPath cell 所处的位置
*/
func reuseIdentifierForCell(at indexPath: IndexPath) -> String {
guard let data = cellData(at: indexPath) else {
return ""
}
return "cell_\(data.identifier)"
}
/**
* 用于结合 indexPath 和 dataSource 生成 cell 的方法,其中 cell 使用的是 QMUITableViewCell
* @prama indexPath 当前 cell 的 indexPath
*/
func cellForRow(at indexPath: IndexPath) -> QMUITableViewCell? {
guard let data = cellData(at: indexPath) else {
return nil
}
let identifier = reuseIdentifierForCell(at: indexPath)
var cell = tableView?.dequeueReusableCell(withIdentifier: identifier) as? QMUITableViewCell
if cell == nil, let cls = data.cellClass as? QMUITableViewCell.Type, let tableView = tableView {
cell = cls.init(tableView: tableView, style: data.style, reuseIdentifier: identifier)
}
cell?.imageView?.image = data.image
cell?.textLabel?.text = data.text
cell?.detailTextLabel?.text = data.detailText
cell?.accessoryType = QMUIStaticTableViewCellData.tableViewCellAccessoryType(withStaticAccessoryType: data.accessoryType)
// 为某些控件类型的accessory添加控件及相应的事件绑定
if data.accessoryType == .switch, let cell = cell {
var switcher: UISwitch?
var switcherOn = false
if cell.accessoryView is UISwitch {
switcher = cell.accessoryView as? UISwitch
} else {
switcher = UISwitch()
}
if let accessoryValueObject = data.accessoryValueObject as? Int {
switcherOn = accessoryValueObject == 0 ? false : true
}
switcher?.isOn = switcherOn
switcher?.removeTarget(nil, action: nil, for: .allEvents)
if data.accessoryAction != nil {
switcher?.addTarget(data.accessoryTarget, action: data.accessoryAction!, for: .valueChanged)
}
cell.accessoryView = switcher
}
// 统一设置selectionStyle
if data.accessoryType == .switch || data.didSelectTarget == nil || data.didSelectAction == nil {
cell?.selectionStyle = .none
} else {
cell?.selectionStyle = .blue
}
cell?.updateCellAppearance(indexPath)
return cell
}
/**
* 从 dataSource 里获取指定位置的 cell 的高度
* @prama indexPath 当前 cell 的 indexPath
* @return 该位置的 cell 的高度
*/
func heightForRow(at indexPath: IndexPath) -> CGFloat {
guard let data = cellData(at: indexPath) else {
return 0
}
return data.height
}
/**
* 在 tableView:didSelectRowAtIndexPath: 里调用,可从 dataSource 里读取对应 indexPath 的 cellData,然后触发其中的 target 和 action
* @param indexPath 当前 cell 的 indexPath
*/
func didSelectRow(at indexPath: IndexPath) {
guard let data = cellData(at: indexPath), let didSelectTarget = data.didSelectTarget as? UIResponder, let didSelectAction = data.didSelectAction else {
if let cell = tableView?.cellForRow(at: indexPath), cell.selectionStyle != .none {
tableView?.deselectRow(at: indexPath, animated: true)
}
return
}
// 1、分发选中事件(UISwitch 类型不支持 didSelect)
if didSelectTarget.responds(to: didSelectAction) && data.accessoryType != .switch {
Thread.detachNewThreadSelector(didSelectAction, toTarget: didSelectTarget, with: data)
}
// 2、处理点击状态(对checkmark类型的cell,选中后自动反选)
if data.accessoryType == .checkmark {
tableView?.deselectRow(at: indexPath, animated: true)
}
}
/**
* 在 tableView:accessoryButtonTappedForRowWithIndexPath: 里调用,可从 dataSource 里读取对应 indexPath 的 cellData,然后触发其中的 target 和 action
* @param indexPath 当前 cell 的 indexPath
*/
func accessoryButtonTappedForRow(with indexPath: IndexPath) {
if let data = cellData(at: indexPath), let didSelectTarget = data.didSelectTarget as? UIResponder, let didSelectAction = data.didSelectAction {
if didSelectTarget.responds(to: didSelectAction) && data.accessoryType != .switch {
Thread.detachNewThreadSelector(didSelectAction, toTarget: didSelectTarget, with: data)
}
}
}
}
enum QMUIStaticTableViewCellAccessoryType {
case none
case disclosureIndicator
case detailDisclosureButton
case checkmark
case detailButton
case `switch`
}
/**
* 一个 cellData 对象用于存储 static tableView(例如设置界面那种列表) 列表里的一行 cell 的基本信息,包括这个 cell 的 class、text、detailText、accessoryView 等。
* @see QMUIStaticTableViewCellDataSource
*/
class QMUIStaticTableViewCellData: NSObject {
/// 当前 cellData 的标志,一般同个 tableView 里的每个 cellData 都会拥有不相同的 identifier
var identifier: Int
/// 当前 cellData 所对应的 indexPath
fileprivate(set) var indexPath: IndexPath?
/// cell 要使用的 class,默认为 QMUITableViewCell,若要改为自定义 class,必须是 QMUITableViewCell 的子类
var cellClass: AnyClass {
willSet {
assert(cellClass is QMUITableViewCell.Type, "\(type(of: self)).cellClass 必须为 QMUITableViewCell 的子类")
}
}
/// init cell 时要使用的 style
var style: UITableViewCell.CellStyle
/// cell 的高度,默认为 TableViewCellNormalHeight
var height: CGFloat
/// cell 左边要显示的图片,将会被设置到 cell.imageView.image
var image: UIImage?
/// cell 的文字,将会被设置到 cell.textLabel.text
var text: String
/// cell 的详细文字,将会被设置到 cell.detailTextLabel.text,所以要求 cellData.style 的值必须是带 detailTextLabel 类型的 style
var detailText: String?
/// 当 cell 的点击事件被触发时,要由哪个对象来接收
var didSelectTarget: Any?
/// 当 cell 的点击事件被触发时,要向 didSelectTarget 指针发送什么消息以响应事件
/// @warning 这个 selector 接收一个参数,这个参数也即当前的 QMUIStaticTableViewCellData 对象
var didSelectAction: Selector?
/// cell 右边的 accessoryView 的类型
var accessoryType: QMUIStaticTableViewCellAccessoryType
/// 配合 accessoryType 使用,不同的 accessoryType 需要配合不同 class 的 accessoryValueObject 使用。例如 QMUIStaticTableViewCellAccessoryTypeSwitch 要求传 @YES 或 @NO 用于控制 UISwitch.on 属性。
/// @warning 目前也仅支持与 QMUIStaticTableViewCellAccessoryTypeSwitch 搭配使用。
var accessoryValueObject: AnyObject?
/// 当 accessoryType 是某些带 UIControl 的控件时,可通过这两个属性来为 accessoryView 添加操作事件。
/// 目前支持的类型包括:QMUIStaticTableViewCellAccessoryTypeDetailDisclosureButton、QMUIStaticTableViewCellAccessoryTypeDetailButton、QMUIStaticTableViewCellAccessoryTypeSwitch
/// @warning 这个 selector 接收一个参数,与 didSelectAction 一样,这个参数一般情况下也是当前的 QMUIStaticTableViewCellData 对象,仅在 Switch 时会传 UISwitch 控件的实例
var accessoryTarget: Any?
var accessoryAction: Selector?
init(identifier: Int,
cellClass: AnyClass = QMUITableViewCell.self,
style: UITableViewCell.CellStyle = .default,
height: CGFloat = TableViewCellNormalHeight,
image: UIImage? = nil,
text: String,
detailText: String? = nil,
didSelectTarget: Any?,
didSelectAction: Selector?,
accessoryType: QMUIStaticTableViewCellAccessoryType = .none,
accessoryValueObject: AnyObject? = nil,
accessoryTarget: Any? = nil,
accessoryAction: Selector? = nil) {
self.identifier = identifier
self.cellClass = cellClass
self.style = style
self.height = height
self.image = image
self.text = text
self.detailText = detailText
self.didSelectTarget = didSelectTarget
self.didSelectAction = didSelectAction
self.accessoryType = accessoryType
self.accessoryValueObject = accessoryValueObject
self.accessoryTarget = accessoryTarget
self.accessoryAction = accessoryAction
}
static func tableViewCellAccessoryType(withStaticAccessoryType type: QMUIStaticTableViewCellAccessoryType) -> UITableViewCell.AccessoryType {
switch type {
case .disclosureIndicator:
return .disclosureIndicator
case .detailDisclosureButton:
return .detailDisclosureButton
case .checkmark:
return .checkmark
case .detailButton:
return .detailButton
default:
return .none
}
}
}
extension UITableView {
fileprivate struct Keys {
static var staticCellDataSource = "staticCellDataSource"
}
var qmui_staticCellDataSource: QMUIStaticTableViewCellDataSource? {
get {
return objc_getAssociatedObject(self, &Keys.staticCellDataSource) as? QMUIStaticTableViewCellDataSource
}
set {
objc_setAssociatedObject(self, &Keys.staticCellDataSource, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
newValue?.tableView = self
reloadData()
}
}
@objc func staticCell_setDataSource(_ dataSource: UITableViewDataSource?) {
if let dataSource = dataSource as? NSObject, let _ = qmui_staticCellDataSource {
// 这些 addMethod 的操作必须要在系统的 setDataSource 执行前就执行,否则 tableView 可能会认为不存在这些 method
// 并且 addMethod 操作执行一次之后,直到 App 进程被杀死前都会生效,所以多次进入这段代码可能就会提示添加方法失败,请不用在意
// MARK: TODO
addSelector(#selector(UITableViewDataSource.numberOfSections(in:)), implementation: imp_implementationWithBlock(unsafeBitCast(staticCell_numberOfSections, to: AnyObject.self)), types: "l@:@", for: dataSource)
addSelector(#selector(UITableViewDataSource.tableView(_:numberOfRowsInSection:)), implementation: imp_implementationWithBlock(staticCell_numberOfRows), types: "l@:@l", for: dataSource)
addSelector(#selector(UITableViewDataSource.tableView(_:cellForRowAt:)), implementation: imp_implementationWithBlock(staticCell_cellForRow), types: "@@:@@", for: dataSource)
}
staticCell_setDataSource(dataSource)
}
@objc func staticCell_setDelegate(_ delegate: UITableViewDelegate?) {
if let delegate = delegate, let _ = qmui_staticCellDataSource {
}
staticCell_setDelegate(delegate)
}
private typealias StaticCell_numberOfSectionsBlockType = @convention(block) (Any, Selector, UITableView) -> Int
private var staticCell_numberOfSections: StaticCell_numberOfSectionsBlockType {
get {
let block: StaticCell_numberOfSectionsBlockType = { (current_self, current_cmd, tableView) in
return tableView.qmui_staticCellDataSource?.cellDataSections.count ?? 0
}
return block
}
}
private typealias StaticCell_numberOfRowsBlockType = @convention(block) (Any, Selector, UITableView, Int) -> Int
private var staticCell_numberOfRows: StaticCell_numberOfRowsBlockType {
get {
let block: StaticCell_numberOfRowsBlockType = { (current_self, current_cmd, tableView, section) in
print(tableView)
return tableView.qmui_staticCellDataSource?.cellDataSections[section].count ?? 0
}
return block
}
}
private typealias StaticCell_cellForRowBlockType = @convention(block) (Any, Selector, UITableView, IndexPath) -> Any?
private var staticCell_cellForRow: StaticCell_cellForRowBlockType {
get {
let block: StaticCell_cellForRowBlockType = { (current_self, current_cmd, tableView, indexPath) in
return tableView.qmui_staticCellDataSource?.accessoryButtonTappedForRow(with: indexPath) ?? nil
}
return block
}
}
}
fileprivate var QMUI_staticTableViewAddedClass = Set<String>()
fileprivate func addSelector(_ selector: Selector, implementation: IMP, types: UnsafePointer<Int8>?, for object: NSObject) {
let cls = type(of: object)
if !class_addMethod(cls.self, selector, implementation, types) {
let identifier = "\(type(of: object))\(NSStringFromSelector(selector))"
if !QMUI_staticTableViewAddedClass.contains(identifier) {
print("\(cls), 尝试为 \(cls) 添加方法 \(NSStringFromSelector(selector)) 失败,可能该类里已经实现了这个方法")
QMUI_staticTableViewAddedClass.insert(identifier)
}
}
}
| 40.409704 | 220 | 0.66909 |
23827ab841a690ba96641329aa7ca6ff290964d3 | 43,689 | // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import Foundation
import AWSSDKSwiftCore
extension CloudHSMV2 {
public struct Backup: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "BackupId", required: true, type: .string),
AWSShapeMember(label: "BackupState", required: false, type: .enum),
AWSShapeMember(label: "ClusterId", required: false, type: .string),
AWSShapeMember(label: "CopyTimestamp", required: false, type: .timestamp),
AWSShapeMember(label: "CreateTimestamp", required: false, type: .timestamp),
AWSShapeMember(label: "DeleteTimestamp", required: false, type: .timestamp),
AWSShapeMember(label: "SourceBackup", required: false, type: .string),
AWSShapeMember(label: "SourceCluster", required: false, type: .string),
AWSShapeMember(label: "SourceRegion", required: false, type: .string)
]
/// The identifier (ID) of the backup.
public let backupId: String
/// The state of the backup.
public let backupState: BackupState?
/// The identifier (ID) of the cluster that was backed up.
public let clusterId: String?
public let copyTimestamp: TimeStamp?
/// The date and time when the backup was created.
public let createTimestamp: TimeStamp?
/// The date and time when the backup will be permanently deleted.
public let deleteTimestamp: TimeStamp?
public let sourceBackup: String?
public let sourceCluster: String?
public let sourceRegion: String?
public init(backupId: String, backupState: BackupState? = nil, clusterId: String? = nil, copyTimestamp: TimeStamp? = nil, createTimestamp: TimeStamp? = nil, deleteTimestamp: TimeStamp? = nil, sourceBackup: String? = nil, sourceCluster: String? = nil, sourceRegion: String? = nil) {
self.backupId = backupId
self.backupState = backupState
self.clusterId = clusterId
self.copyTimestamp = copyTimestamp
self.createTimestamp = createTimestamp
self.deleteTimestamp = deleteTimestamp
self.sourceBackup = sourceBackup
self.sourceCluster = sourceCluster
self.sourceRegion = sourceRegion
}
private enum CodingKeys: String, CodingKey {
case backupId = "BackupId"
case backupState = "BackupState"
case clusterId = "ClusterId"
case copyTimestamp = "CopyTimestamp"
case createTimestamp = "CreateTimestamp"
case deleteTimestamp = "DeleteTimestamp"
case sourceBackup = "SourceBackup"
case sourceCluster = "SourceCluster"
case sourceRegion = "SourceRegion"
}
}
public enum BackupPolicy: String, CustomStringConvertible, Codable {
case `default` = "DEFAULT"
public var description: String { return self.rawValue }
}
public enum BackupState: String, CustomStringConvertible, Codable {
case createInProgress = "CREATE_IN_PROGRESS"
case ready = "READY"
case deleted = "DELETED"
case pendingDeletion = "PENDING_DELETION"
public var description: String { return self.rawValue }
}
public struct Certificates: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "AwsHardwareCertificate", required: false, type: .string),
AWSShapeMember(label: "ClusterCertificate", required: false, type: .string),
AWSShapeMember(label: "ClusterCsr", required: false, type: .string),
AWSShapeMember(label: "HsmCertificate", required: false, type: .string),
AWSShapeMember(label: "ManufacturerHardwareCertificate", required: false, type: .string)
]
/// The HSM hardware certificate issued (signed) by AWS CloudHSM.
public let awsHardwareCertificate: String?
/// The cluster certificate issued (signed) by the issuing certificate authority (CA) of the cluster's owner.
public let clusterCertificate: String?
/// The cluster's certificate signing request (CSR). The CSR exists only when the cluster's state is UNINITIALIZED.
public let clusterCsr: String?
/// The HSM certificate issued (signed) by the HSM hardware.
public let hsmCertificate: String?
/// The HSM hardware certificate issued (signed) by the hardware manufacturer.
public let manufacturerHardwareCertificate: String?
public init(awsHardwareCertificate: String? = nil, clusterCertificate: String? = nil, clusterCsr: String? = nil, hsmCertificate: String? = nil, manufacturerHardwareCertificate: String? = nil) {
self.awsHardwareCertificate = awsHardwareCertificate
self.clusterCertificate = clusterCertificate
self.clusterCsr = clusterCsr
self.hsmCertificate = hsmCertificate
self.manufacturerHardwareCertificate = manufacturerHardwareCertificate
}
private enum CodingKeys: String, CodingKey {
case awsHardwareCertificate = "AwsHardwareCertificate"
case clusterCertificate = "ClusterCertificate"
case clusterCsr = "ClusterCsr"
case hsmCertificate = "HsmCertificate"
case manufacturerHardwareCertificate = "ManufacturerHardwareCertificate"
}
}
public struct Cluster: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "BackupPolicy", required: false, type: .enum),
AWSShapeMember(label: "Certificates", required: false, type: .structure),
AWSShapeMember(label: "ClusterId", required: false, type: .string),
AWSShapeMember(label: "CreateTimestamp", required: false, type: .timestamp),
AWSShapeMember(label: "Hsms", required: false, type: .list),
AWSShapeMember(label: "HsmType", required: false, type: .string),
AWSShapeMember(label: "PreCoPassword", required: false, type: .string),
AWSShapeMember(label: "SecurityGroup", required: false, type: .string),
AWSShapeMember(label: "SourceBackupId", required: false, type: .string),
AWSShapeMember(label: "State", required: false, type: .enum),
AWSShapeMember(label: "StateMessage", required: false, type: .string),
AWSShapeMember(label: "SubnetMapping", required: false, type: .map),
AWSShapeMember(label: "VpcId", required: false, type: .string)
]
/// The cluster's backup policy.
public let backupPolicy: BackupPolicy?
/// Contains one or more certificates or a certificate signing request (CSR).
public let certificates: Certificates?
/// The cluster's identifier (ID).
public let clusterId: String?
/// The date and time when the cluster was created.
public let createTimestamp: TimeStamp?
/// Contains information about the HSMs in the cluster.
public let hsms: [Hsm]?
/// The type of HSM that the cluster contains.
public let hsmType: String?
/// The default password for the cluster's Pre-Crypto Officer (PRECO) user.
public let preCoPassword: String?
/// The identifier (ID) of the cluster's security group.
public let securityGroup: String?
/// The identifier (ID) of the backup used to create the cluster. This value exists only when the cluster was created from a backup.
public let sourceBackupId: String?
/// The cluster's state.
public let state: ClusterState?
/// A description of the cluster's state.
public let stateMessage: String?
/// A map of the cluster's subnets and their corresponding Availability Zones.
public let subnetMapping: [String: String]?
/// The identifier (ID) of the virtual private cloud (VPC) that contains the cluster.
public let vpcId: String?
public init(backupPolicy: BackupPolicy? = nil, certificates: Certificates? = nil, clusterId: String? = nil, createTimestamp: TimeStamp? = nil, hsms: [Hsm]? = nil, hsmType: String? = nil, preCoPassword: String? = nil, securityGroup: String? = nil, sourceBackupId: String? = nil, state: ClusterState? = nil, stateMessage: String? = nil, subnetMapping: [String: String]? = nil, vpcId: String? = nil) {
self.backupPolicy = backupPolicy
self.certificates = certificates
self.clusterId = clusterId
self.createTimestamp = createTimestamp
self.hsms = hsms
self.hsmType = hsmType
self.preCoPassword = preCoPassword
self.securityGroup = securityGroup
self.sourceBackupId = sourceBackupId
self.state = state
self.stateMessage = stateMessage
self.subnetMapping = subnetMapping
self.vpcId = vpcId
}
private enum CodingKeys: String, CodingKey {
case backupPolicy = "BackupPolicy"
case certificates = "Certificates"
case clusterId = "ClusterId"
case createTimestamp = "CreateTimestamp"
case hsms = "Hsms"
case hsmType = "HsmType"
case preCoPassword = "PreCoPassword"
case securityGroup = "SecurityGroup"
case sourceBackupId = "SourceBackupId"
case state = "State"
case stateMessage = "StateMessage"
case subnetMapping = "SubnetMapping"
case vpcId = "VpcId"
}
}
public enum ClusterState: String, CustomStringConvertible, Codable {
case createInProgress = "CREATE_IN_PROGRESS"
case uninitialized = "UNINITIALIZED"
case initializeInProgress = "INITIALIZE_IN_PROGRESS"
case initialized = "INITIALIZED"
case active = "ACTIVE"
case updateInProgress = "UPDATE_IN_PROGRESS"
case deleteInProgress = "DELETE_IN_PROGRESS"
case deleted = "DELETED"
case degraded = "DEGRADED"
public var description: String { return self.rawValue }
}
public struct CopyBackupToRegionRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "BackupId", required: true, type: .string),
AWSShapeMember(label: "DestinationRegion", required: true, type: .string)
]
/// The ID of the backup that will be copied to the destination region.
public let backupId: String
/// The AWS region that will contain your copied CloudHSM cluster backup.
public let destinationRegion: String
public init(backupId: String, destinationRegion: String) {
self.backupId = backupId
self.destinationRegion = destinationRegion
}
public func validate(name: String) throws {
try validate(self.backupId, name:"backupId", parent: name, pattern: "backup-[2-7a-zA-Z]{11,16}")
try validate(self.destinationRegion, name:"destinationRegion", parent: name, pattern: "[a-z]{2}(-(gov))?-(east|west|north|south|central){1,2}-\\d")
}
private enum CodingKeys: String, CodingKey {
case backupId = "BackupId"
case destinationRegion = "DestinationRegion"
}
}
public struct CopyBackupToRegionResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "DestinationBackup", required: false, type: .structure)
]
/// Information on the backup that will be copied to the destination region, including CreateTimestamp, SourceBackup, SourceCluster, and Source Region. CreateTimestamp of the destination backup will be the same as that of the source backup. You will need to use the sourceBackupID returned in this operation to use the DescribeBackups operation on the backup that will be copied to the destination region.
public let destinationBackup: DestinationBackup?
public init(destinationBackup: DestinationBackup? = nil) {
self.destinationBackup = destinationBackup
}
private enum CodingKeys: String, CodingKey {
case destinationBackup = "DestinationBackup"
}
}
public struct CreateClusterRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "HsmType", required: true, type: .string),
AWSShapeMember(label: "SourceBackupId", required: false, type: .string),
AWSShapeMember(label: "SubnetIds", required: true, type: .list)
]
/// The type of HSM to use in the cluster. Currently the only allowed value is hsm1.medium.
public let hsmType: String
/// The identifier (ID) of the cluster backup to restore. Use this value to restore the cluster from a backup instead of creating a new cluster. To find the backup ID, use DescribeBackups.
public let sourceBackupId: String?
/// The identifiers (IDs) of the subnets where you are creating the cluster. You must specify at least one subnet. If you specify multiple subnets, they must meet the following criteria: All subnets must be in the same virtual private cloud (VPC). You can specify only one subnet per Availability Zone.
public let subnetIds: [String]
public init(hsmType: String, sourceBackupId: String? = nil, subnetIds: [String]) {
self.hsmType = hsmType
self.sourceBackupId = sourceBackupId
self.subnetIds = subnetIds
}
public func validate(name: String) throws {
try validate(self.hsmType, name:"hsmType", parent: name, pattern: "(hsm1\\.medium)")
try validate(self.sourceBackupId, name:"sourceBackupId", parent: name, pattern: "backup-[2-7a-zA-Z]{11,16}")
try self.subnetIds.forEach {
try validate($0, name: "subnetIds[]", parent: name, pattern: "subnet-[0-9a-fA-F]{8,17}")
}
try validate(self.subnetIds, name:"subnetIds", parent: name, max: 10)
try validate(self.subnetIds, name:"subnetIds", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case hsmType = "HsmType"
case sourceBackupId = "SourceBackupId"
case subnetIds = "SubnetIds"
}
}
public struct CreateClusterResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Cluster", required: false, type: .structure)
]
/// Information about the cluster that was created.
public let cluster: Cluster?
public init(cluster: Cluster? = nil) {
self.cluster = cluster
}
private enum CodingKeys: String, CodingKey {
case cluster = "Cluster"
}
}
public struct CreateHsmRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "AvailabilityZone", required: true, type: .string),
AWSShapeMember(label: "ClusterId", required: true, type: .string),
AWSShapeMember(label: "IpAddress", required: false, type: .string)
]
/// The Availability Zone where you are creating the HSM. To find the cluster's Availability Zones, use DescribeClusters.
public let availabilityZone: String
/// The identifier (ID) of the HSM's cluster. To find the cluster ID, use DescribeClusters.
public let clusterId: String
/// The HSM's IP address. If you specify an IP address, use an available address from the subnet that maps to the Availability Zone where you are creating the HSM. If you don't specify an IP address, one is chosen for you from that subnet.
public let ipAddress: String?
public init(availabilityZone: String, clusterId: String, ipAddress: String? = nil) {
self.availabilityZone = availabilityZone
self.clusterId = clusterId
self.ipAddress = ipAddress
}
public func validate(name: String) throws {
try validate(self.availabilityZone, name:"availabilityZone", parent: name, pattern: "[a-z]{2}(-(gov))?-(east|west|north|south|central){1,2}-\\d[a-z]")
try validate(self.clusterId, name:"clusterId", parent: name, pattern: "cluster-[2-7a-zA-Z]{11,16}")
try validate(self.ipAddress, name:"ipAddress", parent: name, pattern: "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")
}
private enum CodingKeys: String, CodingKey {
case availabilityZone = "AvailabilityZone"
case clusterId = "ClusterId"
case ipAddress = "IpAddress"
}
}
public struct CreateHsmResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Hsm", required: false, type: .structure)
]
/// Information about the HSM that was created.
public let hsm: Hsm?
public init(hsm: Hsm? = nil) {
self.hsm = hsm
}
private enum CodingKeys: String, CodingKey {
case hsm = "Hsm"
}
}
public struct DeleteBackupRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "BackupId", required: true, type: .string)
]
/// The ID of the backup to be deleted. To find the ID of a backup, use the DescribeBackups operation.
public let backupId: String
public init(backupId: String) {
self.backupId = backupId
}
public func validate(name: String) throws {
try validate(self.backupId, name:"backupId", parent: name, pattern: "backup-[2-7a-zA-Z]{11,16}")
}
private enum CodingKeys: String, CodingKey {
case backupId = "BackupId"
}
}
public struct DeleteBackupResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Backup", required: false, type: .structure)
]
/// Information on the Backup object deleted.
public let backup: Backup?
public init(backup: Backup? = nil) {
self.backup = backup
}
private enum CodingKeys: String, CodingKey {
case backup = "Backup"
}
}
public struct DeleteClusterRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "ClusterId", required: true, type: .string)
]
/// The identifier (ID) of the cluster that you are deleting. To find the cluster ID, use DescribeClusters.
public let clusterId: String
public init(clusterId: String) {
self.clusterId = clusterId
}
public func validate(name: String) throws {
try validate(self.clusterId, name:"clusterId", parent: name, pattern: "cluster-[2-7a-zA-Z]{11,16}")
}
private enum CodingKeys: String, CodingKey {
case clusterId = "ClusterId"
}
}
public struct DeleteClusterResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Cluster", required: false, type: .structure)
]
/// Information about the cluster that was deleted.
public let cluster: Cluster?
public init(cluster: Cluster? = nil) {
self.cluster = cluster
}
private enum CodingKeys: String, CodingKey {
case cluster = "Cluster"
}
}
public struct DeleteHsmRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "ClusterId", required: true, type: .string),
AWSShapeMember(label: "EniId", required: false, type: .string),
AWSShapeMember(label: "EniIp", required: false, type: .string),
AWSShapeMember(label: "HsmId", required: false, type: .string)
]
/// The identifier (ID) of the cluster that contains the HSM that you are deleting.
public let clusterId: String
/// The identifier (ID) of the elastic network interface (ENI) of the HSM that you are deleting.
public let eniId: String?
/// The IP address of the elastic network interface (ENI) of the HSM that you are deleting.
public let eniIp: String?
/// The identifier (ID) of the HSM that you are deleting.
public let hsmId: String?
public init(clusterId: String, eniId: String? = nil, eniIp: String? = nil, hsmId: String? = nil) {
self.clusterId = clusterId
self.eniId = eniId
self.eniIp = eniIp
self.hsmId = hsmId
}
public func validate(name: String) throws {
try validate(self.clusterId, name:"clusterId", parent: name, pattern: "cluster-[2-7a-zA-Z]{11,16}")
try validate(self.eniId, name:"eniId", parent: name, pattern: "eni-[0-9a-fA-F]{8,17}")
try validate(self.eniIp, name:"eniIp", parent: name, pattern: "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")
try validate(self.hsmId, name:"hsmId", parent: name, pattern: "hsm-[2-7a-zA-Z]{11,16}")
}
private enum CodingKeys: String, CodingKey {
case clusterId = "ClusterId"
case eniId = "EniId"
case eniIp = "EniIp"
case hsmId = "HsmId"
}
}
public struct DeleteHsmResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "HsmId", required: false, type: .string)
]
/// The identifier (ID) of the HSM that was deleted.
public let hsmId: String?
public init(hsmId: String? = nil) {
self.hsmId = hsmId
}
private enum CodingKeys: String, CodingKey {
case hsmId = "HsmId"
}
}
public struct DescribeBackupsRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Filters", required: false, type: .map),
AWSShapeMember(label: "MaxResults", required: false, type: .integer),
AWSShapeMember(label: "NextToken", required: false, type: .string),
AWSShapeMember(label: "SortAscending", required: false, type: .boolean)
]
/// One or more filters to limit the items returned in the response. Use the backupIds filter to return only the specified backups. Specify backups by their backup identifier (ID). Use the sourceBackupIds filter to return only the backups created from a source backup. The sourceBackupID of a source backup is returned by the CopyBackupToRegion operation. Use the clusterIds filter to return only the backups for the specified clusters. Specify clusters by their cluster identifier (ID). Use the states filter to return only backups that match the specified state.
public let filters: [String: [String]]?
/// The maximum number of backups to return in the response. When there are more backups than the number you specify, the response contains a NextToken value.
public let maxResults: Int?
/// The NextToken value that you received in the previous response. Use this value to get more backups.
public let nextToken: String?
public let sortAscending: Bool?
public init(filters: [String: [String]]? = nil, maxResults: Int? = nil, nextToken: String? = nil, sortAscending: Bool? = nil) {
self.filters = filters
self.maxResults = maxResults
self.nextToken = nextToken
self.sortAscending = sortAscending
}
public func validate(name: String) throws {
try self.filters?.forEach {
try validate($0.key, name:"filters.key", parent: name, pattern: "[a-zA-Z0-9_-]+")
}
try validate(self.maxResults, name:"maxResults", parent: name, max: 100)
try validate(self.maxResults, name:"maxResults", parent: name, min: 1)
try validate(self.nextToken, name:"nextToken", parent: name, max: 256)
try validate(self.nextToken, name:"nextToken", parent: name, pattern: ".*")
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case maxResults = "MaxResults"
case nextToken = "NextToken"
case sortAscending = "SortAscending"
}
}
public struct DescribeBackupsResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Backups", required: false, type: .list),
AWSShapeMember(label: "NextToken", required: false, type: .string)
]
/// A list of backups.
public let backups: [Backup]?
/// An opaque string that indicates that the response contains only a subset of backups. Use this value in a subsequent DescribeBackups request to get more backups.
public let nextToken: String?
public init(backups: [Backup]? = nil, nextToken: String? = nil) {
self.backups = backups
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case backups = "Backups"
case nextToken = "NextToken"
}
}
public struct DescribeClustersRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Filters", required: false, type: .map),
AWSShapeMember(label: "MaxResults", required: false, type: .integer),
AWSShapeMember(label: "NextToken", required: false, type: .string)
]
/// One or more filters to limit the items returned in the response. Use the clusterIds filter to return only the specified clusters. Specify clusters by their cluster identifier (ID). Use the vpcIds filter to return only the clusters in the specified virtual private clouds (VPCs). Specify VPCs by their VPC identifier (ID). Use the states filter to return only clusters that match the specified state.
public let filters: [String: [String]]?
/// The maximum number of clusters to return in the response. When there are more clusters than the number you specify, the response contains a NextToken value.
public let maxResults: Int?
/// The NextToken value that you received in the previous response. Use this value to get more clusters.
public let nextToken: String?
public init(filters: [String: [String]]? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.filters = filters
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.filters?.forEach {
try validate($0.key, name:"filters.key", parent: name, pattern: "[a-zA-Z0-9_-]+")
}
try validate(self.maxResults, name:"maxResults", parent: name, max: 100)
try validate(self.maxResults, name:"maxResults", parent: name, min: 1)
try validate(self.nextToken, name:"nextToken", parent: name, max: 256)
try validate(self.nextToken, name:"nextToken", parent: name, pattern: ".*")
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct DescribeClustersResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Clusters", required: false, type: .list),
AWSShapeMember(label: "NextToken", required: false, type: .string)
]
/// A list of clusters.
public let clusters: [Cluster]?
/// An opaque string that indicates that the response contains only a subset of clusters. Use this value in a subsequent DescribeClusters request to get more clusters.
public let nextToken: String?
public init(clusters: [Cluster]? = nil, nextToken: String? = nil) {
self.clusters = clusters
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case clusters = "Clusters"
case nextToken = "NextToken"
}
}
public struct DestinationBackup: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "CreateTimestamp", required: false, type: .timestamp),
AWSShapeMember(label: "SourceBackup", required: false, type: .string),
AWSShapeMember(label: "SourceCluster", required: false, type: .string),
AWSShapeMember(label: "SourceRegion", required: false, type: .string)
]
public let createTimestamp: TimeStamp?
public let sourceBackup: String?
public let sourceCluster: String?
public let sourceRegion: String?
public init(createTimestamp: TimeStamp? = nil, sourceBackup: String? = nil, sourceCluster: String? = nil, sourceRegion: String? = nil) {
self.createTimestamp = createTimestamp
self.sourceBackup = sourceBackup
self.sourceCluster = sourceCluster
self.sourceRegion = sourceRegion
}
private enum CodingKeys: String, CodingKey {
case createTimestamp = "CreateTimestamp"
case sourceBackup = "SourceBackup"
case sourceCluster = "SourceCluster"
case sourceRegion = "SourceRegion"
}
}
public struct Hsm: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "AvailabilityZone", required: false, type: .string),
AWSShapeMember(label: "ClusterId", required: false, type: .string),
AWSShapeMember(label: "EniId", required: false, type: .string),
AWSShapeMember(label: "EniIp", required: false, type: .string),
AWSShapeMember(label: "HsmId", required: true, type: .string),
AWSShapeMember(label: "State", required: false, type: .enum),
AWSShapeMember(label: "StateMessage", required: false, type: .string),
AWSShapeMember(label: "SubnetId", required: false, type: .string)
]
/// The Availability Zone that contains the HSM.
public let availabilityZone: String?
/// The identifier (ID) of the cluster that contains the HSM.
public let clusterId: String?
/// The identifier (ID) of the HSM's elastic network interface (ENI).
public let eniId: String?
/// The IP address of the HSM's elastic network interface (ENI).
public let eniIp: String?
/// The HSM's identifier (ID).
public let hsmId: String
/// The HSM's state.
public let state: HsmState?
/// A description of the HSM's state.
public let stateMessage: String?
/// The subnet that contains the HSM's elastic network interface (ENI).
public let subnetId: String?
public init(availabilityZone: String? = nil, clusterId: String? = nil, eniId: String? = nil, eniIp: String? = nil, hsmId: String, state: HsmState? = nil, stateMessage: String? = nil, subnetId: String? = nil) {
self.availabilityZone = availabilityZone
self.clusterId = clusterId
self.eniId = eniId
self.eniIp = eniIp
self.hsmId = hsmId
self.state = state
self.stateMessage = stateMessage
self.subnetId = subnetId
}
private enum CodingKeys: String, CodingKey {
case availabilityZone = "AvailabilityZone"
case clusterId = "ClusterId"
case eniId = "EniId"
case eniIp = "EniIp"
case hsmId = "HsmId"
case state = "State"
case stateMessage = "StateMessage"
case subnetId = "SubnetId"
}
}
public enum HsmState: String, CustomStringConvertible, Codable {
case createInProgress = "CREATE_IN_PROGRESS"
case active = "ACTIVE"
case degraded = "DEGRADED"
case deleteInProgress = "DELETE_IN_PROGRESS"
case deleted = "DELETED"
public var description: String { return self.rawValue }
}
public struct InitializeClusterRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "ClusterId", required: true, type: .string),
AWSShapeMember(label: "SignedCert", required: true, type: .string),
AWSShapeMember(label: "TrustAnchor", required: true, type: .string)
]
/// The identifier (ID) of the cluster that you are claiming. To find the cluster ID, use DescribeClusters.
public let clusterId: String
/// The cluster certificate issued (signed) by your issuing certificate authority (CA). The certificate must be in PEM format and can contain a maximum of 5000 characters.
public let signedCert: String
/// The issuing certificate of the issuing certificate authority (CA) that issued (signed) the cluster certificate. This can be a root (self-signed) certificate or a certificate chain that begins with the certificate that issued the cluster certificate and ends with a root certificate. The certificate or certificate chain must be in PEM format and can contain a maximum of 5000 characters.
public let trustAnchor: String
public init(clusterId: String, signedCert: String, trustAnchor: String) {
self.clusterId = clusterId
self.signedCert = signedCert
self.trustAnchor = trustAnchor
}
public func validate(name: String) throws {
try validate(self.clusterId, name:"clusterId", parent: name, pattern: "cluster-[2-7a-zA-Z]{11,16}")
try validate(self.signedCert, name:"signedCert", parent: name, max: 5000)
try validate(self.signedCert, name:"signedCert", parent: name, pattern: "[a-zA-Z0-9+-/=\\s]*")
try validate(self.trustAnchor, name:"trustAnchor", parent: name, max: 5000)
try validate(self.trustAnchor, name:"trustAnchor", parent: name, pattern: "[a-zA-Z0-9+-/=\\s]*")
}
private enum CodingKeys: String, CodingKey {
case clusterId = "ClusterId"
case signedCert = "SignedCert"
case trustAnchor = "TrustAnchor"
}
}
public struct InitializeClusterResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "State", required: false, type: .enum),
AWSShapeMember(label: "StateMessage", required: false, type: .string)
]
/// The cluster's state.
public let state: ClusterState?
/// A description of the cluster's state.
public let stateMessage: String?
public init(state: ClusterState? = nil, stateMessage: String? = nil) {
self.state = state
self.stateMessage = stateMessage
}
private enum CodingKeys: String, CodingKey {
case state = "State"
case stateMessage = "StateMessage"
}
}
public struct ListTagsRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "MaxResults", required: false, type: .integer),
AWSShapeMember(label: "NextToken", required: false, type: .string),
AWSShapeMember(label: "ResourceId", required: true, type: .string)
]
/// The maximum number of tags to return in the response. When there are more tags than the number you specify, the response contains a NextToken value.
public let maxResults: Int?
/// The NextToken value that you received in the previous response. Use this value to get more tags.
public let nextToken: String?
/// The cluster identifier (ID) for the cluster whose tags you are getting. To find the cluster ID, use DescribeClusters.
public let resourceId: String
public init(maxResults: Int? = nil, nextToken: String? = nil, resourceId: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.resourceId = resourceId
}
public func validate(name: String) throws {
try validate(self.maxResults, name:"maxResults", parent: name, max: 100)
try validate(self.maxResults, name:"maxResults", parent: name, min: 1)
try validate(self.nextToken, name:"nextToken", parent: name, max: 256)
try validate(self.nextToken, name:"nextToken", parent: name, pattern: ".*")
try validate(self.resourceId, name:"resourceId", parent: name, pattern: "cluster-[2-7a-zA-Z]{11,16}")
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
case resourceId = "ResourceId"
}
}
public struct ListTagsResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "NextToken", required: false, type: .string),
AWSShapeMember(label: "TagList", required: true, type: .list)
]
/// An opaque string that indicates that the response contains only a subset of tags. Use this value in a subsequent ListTags request to get more tags.
public let nextToken: String?
/// A list of tags.
public let tagList: [Tag]
public init(nextToken: String? = nil, tagList: [Tag]) {
self.nextToken = nextToken
self.tagList = tagList
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case tagList = "TagList"
}
}
public struct RestoreBackupRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "BackupId", required: true, type: .string)
]
/// The ID of the backup to be restored. To find the ID of a backup, use the DescribeBackups operation.
public let backupId: String
public init(backupId: String) {
self.backupId = backupId
}
public func validate(name: String) throws {
try validate(self.backupId, name:"backupId", parent: name, pattern: "backup-[2-7a-zA-Z]{11,16}")
}
private enum CodingKeys: String, CodingKey {
case backupId = "BackupId"
}
}
public struct RestoreBackupResponse: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Backup", required: false, type: .structure)
]
/// Information on the Backup object created.
public let backup: Backup?
public init(backup: Backup? = nil) {
self.backup = backup
}
private enum CodingKeys: String, CodingKey {
case backup = "Backup"
}
}
public struct Tag: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "Key", required: true, type: .string),
AWSShapeMember(label: "Value", required: true, type: .string)
]
/// The key of the tag.
public let key: String
/// The value of the tag.
public let value: String
public init(key: String, value: String) {
self.key = key
self.value = value
}
public func validate(name: String) throws {
try validate(self.key, name:"key", parent: name, max: 128)
try validate(self.key, name:"key", parent: name, min: 1)
try validate(self.key, name:"key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
try validate(self.value, name:"value", parent: name, max: 256)
try validate(self.value, name:"value", parent: name, min: 0)
try validate(self.value, name:"value", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
private enum CodingKeys: String, CodingKey {
case key = "Key"
case value = "Value"
}
}
public struct TagResourceRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "ResourceId", required: true, type: .string),
AWSShapeMember(label: "TagList", required: true, type: .list)
]
/// The cluster identifier (ID) for the cluster that you are tagging. To find the cluster ID, use DescribeClusters.
public let resourceId: String
/// A list of one or more tags.
public let tagList: [Tag]
public init(resourceId: String, tagList: [Tag]) {
self.resourceId = resourceId
self.tagList = tagList
}
public func validate(name: String) throws {
try validate(self.resourceId, name:"resourceId", parent: name, pattern: "cluster-[2-7a-zA-Z]{11,16}")
try self.tagList.forEach {
try $0.validate(name: "\(name).tagList[]")
}
try validate(self.tagList, name:"tagList", parent: name, max: 50)
try validate(self.tagList, name:"tagList", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case resourceId = "ResourceId"
case tagList = "TagList"
}
}
public struct TagResourceResponse: AWSShape {
public init() {
}
}
public struct UntagResourceRequest: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "ResourceId", required: true, type: .string),
AWSShapeMember(label: "TagKeyList", required: true, type: .list)
]
/// The cluster identifier (ID) for the cluster whose tags you are removing. To find the cluster ID, use DescribeClusters.
public let resourceId: String
/// A list of one or more tag keys for the tags that you are removing. Specify only the tag keys, not the tag values.
public let tagKeyList: [String]
public init(resourceId: String, tagKeyList: [String]) {
self.resourceId = resourceId
self.tagKeyList = tagKeyList
}
public func validate(name: String) throws {
try validate(self.resourceId, name:"resourceId", parent: name, pattern: "cluster-[2-7a-zA-Z]{11,16}")
try self.tagKeyList.forEach {
try validate($0, name: "tagKeyList[]", parent: name, max: 128)
try validate($0, name: "tagKeyList[]", parent: name, min: 1)
try validate($0, name: "tagKeyList[]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
try validate(self.tagKeyList, name:"tagKeyList", parent: name, max: 50)
try validate(self.tagKeyList, name:"tagKeyList", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case resourceId = "ResourceId"
case tagKeyList = "TagKeyList"
}
}
public struct UntagResourceResponse: AWSShape {
public init() {
}
}
}
| 45.747644 | 572 | 0.626176 |
674bcd4dfb7c1d63d62ac83d2b7325765e085c31 | 1,149 | //
// PHStatusBarUpdater.swift
// ProductHunt
//
// Created by Vlado on 3/30/16.
// Copyright © 2016 ProductHunt. All rights reserved.
//
import Cocoa
import ReSwift
class PHStatusBarUpdater: StoreSubscriber {
fileprivate var button: NSStatusBarButton?
fileprivate var store: Store<PHAppState>
init(button: NSStatusBarButton?, store: Store<PHAppState>) {
self.button = button
self.store = store
store.subscribe(self)
}
deinit {
store.unsubscribe(self)
}
func newState(state: PHAppState) {
updateTitle()
}
fileprivate func updateTitle() {
guard let button = button, let posts = store.state.posts.todayPosts else {
return
}
let sortedPosts = PHPostSorter.filter(store, posts: posts, by: [.seen(false), .votes(store.state.settings.filterCount)])
button.title = title(fromCount: sortedPosts.count)
}
fileprivate func title(fromCount count: Int) -> String {
if !store.state.settings.showsCount {
return ""
}
return count > 9 ? "9+" : (count == 0 ? "" : "\(count)")
}
}
| 22.98 | 128 | 0.62054 |
f7fb7f0688c9ccf871fcc5a82c53b1aa41baf348 | 5,008 | import Foundation
import ArgumentParser
import URLExpressibleByArgument
import MetalPetalSourceLocator
public struct SwiftPackageGenerator: ParsableCommand {
@Argument(help: "The root directory of the MetalPetal repo.")
var projectRoot: URL
enum CodingKeys: CodingKey {
case projectRoot
}
private let fileManager = FileManager()
private let objectiveCModuleMapContents = """
module MetalPetalObjectiveC {
explicit module Core {
header "MetalPetal.h"
export *
}
explicit module Extension {
header "MTIContext+Internal.h"
header "MTIImage+Promise.h"
export *
}
}
"""
public init() { }
public func run() throws {
let sourcesDirectory = MetalPetalSourcesRootURL(in: projectRoot)
let packageSourcesDirectory = projectRoot.appendingPathComponent("Sources/")
try? fileManager.removeItem(at: packageSourcesDirectory)
try fileManager.createDirectory(at: packageSourcesDirectory, withIntermediateDirectories: true, attributes: nil)
let swiftTargetDirectory = packageSourcesDirectory.appendingPathComponent("MetalPetal/")
let objectiveCTargetDirectory = packageSourcesDirectory.appendingPathComponent("MetalPetalObjectiveC/")
let objectiveCHeaderDirectory = packageSourcesDirectory.appendingPathComponent("MetalPetalObjectiveC/include/")
try fileManager.createDirectory(at: swiftTargetDirectory, withIntermediateDirectories: true, attributes: nil)
try fileManager.createDirectory(at: objectiveCTargetDirectory, withIntermediateDirectories: true, attributes: nil)
try fileManager.createDirectory(at: objectiveCHeaderDirectory, withIntermediateDirectories: true, attributes: nil)
let fileHandlers = [
SourceFileHandler(fileTypes: ["h"], projectRoot: projectRoot, targetURL: objectiveCHeaderDirectory, fileManager: fileManager),
SourceFileHandler(fileTypes: ["m", "mm", "metal"], projectRoot: projectRoot, targetURL: objectiveCTargetDirectory, fileManager: fileManager),
SourceFileHandler(fileTypes: ["swift"], projectRoot: projectRoot, targetURL: swiftTargetDirectory, fileManager: fileManager)
]
try processSources(in: sourcesDirectory, fileHandlers: fileHandlers)
try objectiveCModuleMapContents.write(to: objectiveCHeaderDirectory.appendingPathComponent("module.modulemap"), atomically: true, encoding: .utf8)
}
private func processSources(in directory: URL, fileHandlers: [SourceFileHandler]) throws {
let sourceFiles = try fileManager.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles])
for sourceFile in sourceFiles {
if try sourceFile.resourceValues(forKeys: Set<URLResourceKey>([URLResourceKey.isDirectoryKey])).isDirectory == true {
try processSources(in: sourceFile, fileHandlers: fileHandlers)
} else {
for fileHandler in fileHandlers {
if try fileHandler.handle(sourceFile) {
break
}
}
}
}
}
struct SourceFileHandler {
let fileTypes: [String]
let projectRoot: URL
let targetURL: URL
let fileManager: FileManager
enum Error: String, Swift.Error, LocalizedError {
case cannotCreateRelativePath
var errorDescription: String? {
return self.rawValue
}
}
func handle(_ file: URL) throws -> Bool {
if fileTypes.contains(file.pathExtension) {
let fileRelativeToProjectRoot = try relativePathComponents(for: file, baseURL: projectRoot)
let targetRelativeToProjectRoot = try relativePathComponents(for: targetURL, baseURL: projectRoot)
let destinationURL = URL(string: (Array<String>(repeating: "..", count: targetRelativeToProjectRoot.count) + fileRelativeToProjectRoot).joined(separator: "/"))!
try fileManager.createSymbolicLink(at: targetURL.appendingPathComponent(file.lastPathComponent), withDestinationURL: destinationURL)
return true
} else {
return false
}
}
private func relativePathComponents(for url: URL, baseURL: URL) throws -> [String] {
let filePathComponents = url.standardized.pathComponents
let basePathComponents = baseURL.standardized.pathComponents
let r: [String] = filePathComponents.dropLast(filePathComponents.count - basePathComponents.count)
if r == basePathComponents {
return [String](filePathComponents.dropFirst(basePathComponents.count))
} else {
throw Error.cannotCreateRelativePath
}
}
}
}
| 45.944954 | 176 | 0.667133 |
8f6c66fcc6d08a1339888f01e77285b9ef4dc486 | 528 | //
// LineBreakMode.swift
// TokamakUIKit
//
// Created by Max Desiatov on 14/02/2019.
//
import Tokamak
import UIKit
extension NSLineBreakMode {
public init(_ mode: LineBreakMode) {
switch mode {
case .wordWrap:
self = .byWordWrapping
case .charWrap:
self = .byCharWrapping
case .clip:
self = .byClipping
case .truncateHead:
self = .byTruncatingHead
case .truncateTail:
self = .byTruncatingTail
case .truncateMiddle:
self = .byTruncatingMiddle
}
}
}
| 18.206897 | 42 | 0.643939 |
0931bd1f5547976741934da14ee77e74806c6f3b | 5,063 | //
// ViewController.swift
// DuffSnake
//
// Created by Eivind Morris Bakke on 6/28/15.
// Copyright (c) 2015 Duff Development. All rights reserved.
//
import UIKit
class ViewController: UIViewController{
enum Direction: Int {
case N, S, E, W
}
let screenWidth:CGFloat = UIScreen.mainScreen().bounds.width;
let screenHeight:CGFloat = UIScreen.mainScreen().bounds.height;
let HEAD = 0
let TAIL = 1
let snakeSegmentWidth:CGFloat = 5
var snakeSegmentSize:CGSize
var startRect:CGRect
var snake:[CGRect]
var snakeSegmentViews:[UIView] = []
var snakeDirection:Direction = Direction.E
var apple:CGRect
var appleView:UIView
var appleWidth:Int = 5
@IBOutlet var upDownSwipeRecognizer:UISwipeGestureRecognizer!
@IBOutlet var leftRightSwipeRecognizer:UISwipeGestureRecognizer!
required init(coder aDecoder: NSCoder) {
var x = arc4random_uniform(UInt32(Int(screenWidth) - appleWidth))
var y = arc4random_uniform(UInt32(Int(screenHeight) - appleWidth))
apple = CGRectMake(CGFloat(x), CGFloat(y), CGFloat(appleWidth), CGFloat(appleWidth))
appleView = UIView(frame: CGRectZero)
snakeSegmentSize = CGSizeMake(snakeSegmentWidth, snakeSegmentWidth)
startRect = CGRectMake(screenWidth / 2, screenHeight / 2, snakeSegmentWidth, snakeSegmentWidth)
snake = [startRect, CGRectMake(startRect.origin.x - (1 * snakeSegmentWidth), startRect.origin.y, snakeSegmentWidth, snakeSegmentWidth), CGRectMake(startRect.origin.x - (2 * snakeSegmentWidth), startRect.origin.y, snakeSegmentWidth, snakeSegmentWidth)]
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
// Setup snake
var snakeUpdateTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("updateSnake"), userInfo: nil, repeats: true)
drawSnake()
drawApple()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateSnake() {
addHead()
redrawSnake()
if (!CGRectIntersectsRect(snake[HEAD], apple)) {
snake.removeLast()
} else {
updateApple()
}
}
func redrawSnake() {
var newSnakeHeadView = UIView(frame: snake[HEAD])
newSnakeHeadView.tag = HEAD
newSnakeHeadView.backgroundColor = UIColor.blueColor()
snakeSegmentViews = [newSnakeHeadView] + snakeSegmentViews
view.addSubview(newSnakeHeadView)
if (snake.count != snakeSegmentViews.count) {
snakeSegmentViews.last?.removeFromSuperview()
snakeSegmentViews.removeLast()
}
}
func drawSnake() {
for s in snake {
var snakeSegmentView = UIView(frame: s)
snakeSegmentView.tag = find(snake, s)!
snakeSegmentView.backgroundColor = UIColor.blueColor()
snakeSegmentViews.append(snakeSegmentView)
view.addSubview(snakeSegmentView)
}
}
func addHead() {
var newHead = snake[HEAD]
switch snakeDirection {
case .N:
newHead.origin.y -= snakeSegmentWidth
case .E:
newHead.origin.x += snakeSegmentWidth
case .S:
newHead.origin.y += snakeSegmentWidth
case .W:
newHead.origin.x -= snakeSegmentWidth
}
snake = [newHead] + snake
}
func placeNewApple() -> CGRect {
var x = arc4random_uniform(UInt32(Int(screenWidth) - appleWidth))
var y = arc4random_uniform(UInt32(Int(screenHeight) - appleWidth))
return CGRectMake(CGFloat(x), CGFloat(y), CGFloat(appleWidth), CGFloat(appleWidth))
}
func updateApple() {
removeApple()
apple = placeNewApple()
drawApple()
}
func drawApple() {
appleView = UIView(frame: apple)
appleView.backgroundColor = UIColor.greenColor()
view.addSubview(appleView)
}
func removeApple() {
appleView.removeFromSuperview()
}
@IBAction func didSwipeRight(sender: UISwipeGestureRecognizer) {
if (snakeDirection != Direction.W){
snakeDirection = Direction.E
}
}
@IBAction func didSwipeLeft(sender: UISwipeGestureRecognizer) {
if (snakeDirection != Direction.E){
snakeDirection = Direction.W
}
}
@IBAction func didSwipeUp(sender: UISwipeGestureRecognizer) {
if (snakeDirection != Direction.S){
snakeDirection = Direction.N
}
}
@IBAction func didSwipeDown(sender: UISwipeGestureRecognizer) {
if (snakeDirection != Direction.N){
snakeDirection = Direction.S
}
}
}
| 29.265896 | 259 | 0.621173 |
75d58e41acbaf61d960d967b1738dc1771df34ba | 423 | //
// Double+MinutesSeconds.swift
// Spotify-iOS-Swift-Future
//
// Created by Kevin Johnson on 8/10/18.
// Copyright © 2018 FFR. All rights reserved.
//
import Foundation
extension Double {
func minutesSeconds() -> String {
let secondsInt = Int(self.rounded())
let minutes = secondsInt / 60
let seconds = secondsInt % 60
return String(format: "%i:%02d", minutes, seconds)
}
}
| 22.263158 | 58 | 0.635934 |
699ee356344796347e48a9f9422c9a73358e5477 | 11,496 | import UIKit
class PAPEditPhotoViewController: UIViewController, UITextFieldDelegate, UIScrollViewDelegate {
var scrollView: UIScrollView!
var image: UIImage!
var commentTextField: UITextField!
var photoFile: PFFile?
var thumbnailFile: PFFile?
var fileUploadBackgroundTaskId: UIBackgroundTaskIdentifier!
var photoPostBackgroundTaskId: UIBackgroundTaskIdentifier!
// MARK:- NSObject
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
init(image aImage: UIImage) {
super.init(nibName: nil, bundle: nil)
self.image = aImage
self.fileUploadBackgroundTaskId = UIBackgroundTaskInvalid
self.photoPostBackgroundTaskId = UIBackgroundTaskInvalid
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- UIViewController
override func loadView() {
self.scrollView = UIScrollView(frame: UIScreen.mainScreen().bounds)
self.scrollView.delegate = self
self.scrollView.backgroundColor = UIColor.blackColor()
self.view = self.scrollView
let photoImageView = UIImageView(frame: CGRectMake(0.0, 42.0, 320.0, 320.0))
photoImageView.backgroundColor = UIColor.blackColor()
photoImageView.image = self.image
photoImageView.contentMode = UIViewContentMode.ScaleAspectFit
self.scrollView.addSubview(photoImageView)
var footerRect: CGRect = PAPPhotoDetailsFooterView.rectForView()
footerRect.origin.y = photoImageView.frame.origin.y + photoImageView.frame.size.height
let footerView = PAPPhotoDetailsFooterView(frame: footerRect)
self.commentTextField = footerView.commentField
self.commentTextField!.delegate = self
self.scrollView!.addSubview(footerView)
self.scrollView!.contentSize = CGSizeMake(self.scrollView.bounds.size.width, photoImageView.frame.origin.y + photoImageView.frame.size.height + footerView.frame.size.height)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
self.navigationItem.titleView = UIImageView(image: UIImage(named: "LogoNavigationBar.png"))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("cancelButtonAction:"))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Publish", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction:"))
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
self.shouldUploadImage(self.image)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
print("Memory warning on Edit")
}
// MARK:- UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.doneButtonAction(textField)
textField.resignFirstResponder()
return true
}
// MARK:- UIScrollViewDelegate
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.commentTextField.resignFirstResponder()
}
// MARK:- ()
func shouldUploadImage(anImage: UIImage) -> Bool {
let resizedImage: UIImage = anImage.resizedImageWithContentMode(UIViewContentMode.ScaleAspectFit, bounds: CGSizeMake(560.0, 560.0), interpolationQuality: CGInterpolationQuality.High)
let thumbnailImage: UIImage = anImage.thumbnailImage(86, transparentBorder: 0, cornerRadius: 10, interpolationQuality: CGInterpolationQuality.Default)
// JPEG to decrease file size and enable faster uploads & downloads
guard let imageData: NSData = UIImageJPEGRepresentation(resizedImage, 0.8) else { return false }
guard let thumbnailImageData: NSData = UIImagePNGRepresentation(thumbnailImage) else { return false }
self.photoFile = PFFile(data: imageData)
self.thumbnailFile = PFFile(data: thumbnailImageData)
// Request a background execution task to allow us to finish uploading the photo even if the app is backgrounded
self.fileUploadBackgroundTaskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
UIApplication.sharedApplication().endBackgroundTask(self.fileUploadBackgroundTaskId)
}
print("Requested background expiration task with id \(self.fileUploadBackgroundTaskId) for Anypic photo upload")
self.photoFile!.saveInBackgroundWithBlock { (succeeded, error) in
if (succeeded) {
print("Photo uploaded successfully")
self.thumbnailFile!.saveInBackgroundWithBlock { (succeeded, error) in
if (succeeded) {
print("Thumbnail uploaded successfully")
}
UIApplication.sharedApplication().endBackgroundTask(self.fileUploadBackgroundTaskId)
}
} else {
UIApplication.sharedApplication().endBackgroundTask(self.fileUploadBackgroundTaskId)
}
}
return true
}
func keyboardWillShow(note: NSNotification) {
let keyboardFrameEnd: CGRect = (note.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
var scrollViewContentSize: CGSize = self.scrollView.bounds.size
scrollViewContentSize.height += keyboardFrameEnd.size.height
self.scrollView.contentSize = scrollViewContentSize
var scrollViewContentOffset: CGPoint = self.scrollView.contentOffset
// Align the bottom edge of the photo with the keyboard
scrollViewContentOffset.y = scrollViewContentOffset.y + keyboardFrameEnd.size.height*3.0 - UIScreen.mainScreen().bounds.size.height
self.scrollView.setContentOffset(scrollViewContentOffset, animated: true)
}
func keyboardWillHide(note: NSNotification) {
let keyboardFrameEnd: CGRect = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
var scrollViewContentSize: CGSize = self.scrollView.bounds.size
scrollViewContentSize.height -= keyboardFrameEnd.size.height
UIView.animateWithDuration(0.200, animations: {
self.scrollView.contentSize = scrollViewContentSize
})
}
func doneButtonAction(sender: AnyObject) {
var userInfo: [String: String]?
let trimmedComment: String = self.commentTextField.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if (trimmedComment.length != 0) {
userInfo = [kPAPEditPhotoViewControllerUserInfoCommentKey: trimmedComment]
}
if self.photoFile == nil || self.thumbnailFile == nil {
let alertController = UIAlertController(title: NSLocalizedString("Couldn't post your photo", comment: ""), message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let alertAction = UIAlertAction(title: NSLocalizedString("Dismiss", comment: ""), style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(alertAction)
presentViewController(alertController, animated: true, completion: nil)
return
}
// both files have finished uploading
// create a photo object
let photo = PFObject(className: kPAPPhotoClassKey)
photo.setObject(PFUser.currentUser()!, forKey: kPAPPhotoUserKey)
photo.setObject(self.photoFile!, forKey: kPAPPhotoPictureKey)
photo.setObject(self.thumbnailFile!, forKey: kPAPPhotoThumbnailKey)
// photos are public, but may only be modified by the user who uploaded them
let photoACL = PFACL(user: PFUser.currentUser()!)
photoACL.setPublicReadAccess(true)
photo.ACL = photoACL
// Request a background execution task to allow us to finish uploading the photo even if the app is backgrounded
self.photoPostBackgroundTaskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
UIApplication.sharedApplication().endBackgroundTask(self.photoPostBackgroundTaskId)
}
// save
photo.saveInBackgroundWithBlock { (succeeded, error) in
if succeeded {
print("Photo uploaded")
PAPCache.sharedCache.setAttributesForPhoto(photo, likers: [PFUser](), commenters: [PFUser](), likedByCurrentUser: false)
// userInfo might contain any caption which might have been posted by the uploader
if let userInfo = userInfo {
let commentText = userInfo[kPAPEditPhotoViewControllerUserInfoCommentKey]
if commentText != nil && commentText!.length != 0 {
// create and save photo caption
let comment = PFObject(className: kPAPActivityClassKey)
comment.setObject(kPAPActivityTypeComment, forKey: kPAPActivityTypeKey)
comment.setObject(photo, forKey:kPAPActivityPhotoKey)
comment.setObject(PFUser.currentUser()!, forKey: kPAPActivityFromUserKey)
comment.setObject(PFUser.currentUser()!, forKey: kPAPActivityToUserKey)
comment.setObject(commentText!, forKey: kPAPActivityContentKey)
let ACL = PFACL(user: PFUser.currentUser()!)
ACL.setPublicReadAccess(true)
comment.ACL = ACL
comment.saveEventually()
PAPCache.sharedCache.incrementCommentCountForPhoto(photo)
}
}
NSNotificationCenter.defaultCenter().postNotificationName(PAPTabBarControllerDidFinishEditingPhotoNotification, object: photo)
} else {
print("Photo failed to save: \(error)")
let alertController = UIAlertController(title: NSLocalizedString("Couldn't post your photo", comment: ""), message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let alertAction = UIAlertAction(title: NSLocalizedString("Dismiss", comment: ""), style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(alertAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
UIApplication.sharedApplication().endBackgroundTask(self.photoPostBackgroundTaskId)
}
self.parentViewController!.dismissViewControllerAnimated(true, completion: nil)
}
func cancelButtonAction(sender: AnyObject) {
self.parentViewController!.dismissViewControllerAnimated(true, completion: nil)
}
}
| 50.200873 | 190 | 0.679541 |
11b66c38e29e4be59abcce5d29c61cc2b04c1205 | 233 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
assert(false)
struct B<T where g: T {
typealias F = D
| 25.888889 | 87 | 0.746781 |
6401d7c24c604b373e0557736c95e0ee92e5fda9 | 983 | //
// KoreBotSDKTests.swift
// KoreBotSDKTests
//
// Created by Srinivas Vasadi on 22/04/16.
// Copyright © 2016 Kore. All rights reserved.
//
import XCTest
@testable import KoreBotSDK
class KoreBotSDKTests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.567568 | 111 | 0.637843 |
e9d82db73c598b7994b7b30af0a777f8c8fe938b | 1,147 | //
// SceneDelegate.swift
// Cienemo iOS Task
//
// Created by Omar Bassyouni on 4/5/20.
// Copyright © 2020 Omar Bassyouni. All rights reserved.
//
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 windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
window?.rootViewController = UINavigationController(rootViewController: DocumentsViewController(viewModel: DocumentsViewModel()))
window?.makeKeyAndVisible()
}
}
| 40.964286 | 147 | 0.734961 |
bbe24ed14a29614983b77ec8080362009339ff72 | 12,061 | //
// Supports.swift
// MewTests
//
// Created by tarunon on 2018/08/29.
// Copyright © 2018 Mercari. All rights reserved.
//
import UIKit
import Mew
extension UIView {
private static func contains(_ view: UIView, where condition: (UIView) -> Bool) -> Bool {
if condition(view) { return true }
return view.subviews.contains(where: { contains($0, where: condition) })
}
public func subviewTreeContains(with view: UIView) -> Bool {
return UIView.contains(self, where: { $0 === view })
}
public func subviewTreeContains(where condition: (UIView) -> Bool) -> Bool {
return UIView.contains(self, where: condition)
}
/// addSubview and add constraints/resizingMasks that make frexible size.
public func addSubviewFrexibleSize(_ subview: UIView) {
subview.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints
if translatesAutoresizingMaskIntoConstraints {
subview.frame = bounds
addSubview(subview)
subview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
} else {
addSubview(subview)
NSLayoutConstraint.activate(
[
subview.topAnchor.constraint(equalTo: topAnchor),
subview.leftAnchor.constraint(equalTo: leftAnchor),
subview.rightAnchor.constraint(equalTo: rightAnchor),
subview.bottomAnchor.constraint(equalTo: bottomAnchor)
]
)
}
}
}
final class ViewController: UIViewController, Injectable, Instantiatable, Interactable {
typealias Input = Int
var parameter: Int
var handler: ((Int) -> ())?
let environment: Void
init(with value: Int, environment: Void) {
self.parameter = value
self.environment = environment
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func input(_ value: Int) {
self.parameter = value
}
func output(_ handler: ((Int) -> Void)?) {
self.handler = handler
}
func fire() {
handler?(parameter)
}
}
final class TableViewController: UITableViewController, Instantiatable {
let environment: Void
var elements: [Int]
init(with input: [Int], environment: Void) {
self.environment = environment
self.elements = input
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
TableViewCell<ViewController>.register(to: tableView)
TableViewHeaderFooterView<ViewController>.register(to: tableView)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return elements.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return TableViewCell<ViewController>.dequeued(from: tableView, for: indexPath, input: elements[indexPath.row], parentViewController: self)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return TableViewHeaderFooterView<ViewController>.dequeued(from: tableView, input: elements.count, parentViewController: self)
}
}
final class CollectionViewController: UICollectionViewController, Instantiatable, UICollectionViewDelegateFlowLayout {
let environment: Void
var elements: [Int]
init(with input: [Int], environment: Void) {
self.environment = environment
self.elements = input
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
CollectionViewCell<ViewController>.register(to: collectionView!)
CollectionReusableView<ViewController>.register(to: collectionView!, for: .header)
collectionViewLayout.invalidateLayout()
collectionView?.reloadData()
collectionView?.layoutIfNeeded()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return elements.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return CollectionViewCell<ViewController>.dequeued(from: collectionView, for: indexPath, input: elements[indexPath.row], parentViewController: self)
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return CollectionReusableView<ViewController>.dequeued(from: collectionView, of: kind, for: indexPath, input: elements.count, parentViewController: self)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 44.0)
}
}
final class AutolayoutViewController: UIViewController, Injectable, Instantiatable {
struct Input {
var additionalWidth: CGFloat
var additionalHeight: CGFloat
}
var parameter: Input {
didSet {
updateLayout()
}
}
let environment: Void
init(with input: Input, environment: Void) {
self.parameter = input
self.environment = environment
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var squareRequiredView: UIView!
var additionalWidthView: UIView!
var additionalHeightView: UIView!
var additionalWidthConstraints = [NSLayoutConstraint]()
var additionalHeightConstraints = [NSLayoutConstraint]()
/**
```
┌┬─┐
├┴─┤
└──┘
```
*/
override func viewDidLoad() {
super.viewDidLoad()
squareRequiredView = UIView()
squareRequiredView.translatesAutoresizingMaskIntoConstraints = false
additionalWidthView = UIView()
additionalWidthView.translatesAutoresizingMaskIntoConstraints = false
additionalHeightView = UIView()
additionalHeightView.translatesAutoresizingMaskIntoConstraints = false
additionalWidthConstraints = [
{ let x = additionalWidthView.widthAnchor.constraint(equalToConstant: 0); x.priority = .defaultHigh + 1; return x }(),
additionalWidthView.widthAnchor.constraint(lessThanOrEqualToConstant: 0)
]
additionalHeightConstraints = [
{ let x = additionalHeightView.heightAnchor.constraint(equalToConstant: 0); x.priority = .defaultHigh + 1; return x }(),
additionalHeightView.heightAnchor.constraint(lessThanOrEqualToConstant: 0)
]
view.addSubview(squareRequiredView)
view.addSubview(additionalWidthView)
view.addSubview(additionalHeightView)
NSLayoutConstraint.activate(
[
squareRequiredView.heightAnchor.constraint(equalToConstant: 200.0),
squareRequiredView.widthAnchor.constraint(equalToConstant: 200.0),
squareRequiredView.topAnchor.constraint(equalTo: view.topAnchor),
squareRequiredView.leftAnchor.constraint(equalTo: view.leftAnchor),
squareRequiredView.rightAnchor.constraint(equalTo: additionalWidthView.leftAnchor),
additionalWidthView.topAnchor.constraint(equalTo: view.topAnchor),
additionalWidthView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
additionalWidthView.rightAnchor.constraint(equalTo: view.rightAnchor),
squareRequiredView.bottomAnchor.constraint(equalTo: additionalHeightView.topAnchor),
additionalHeightView.leftAnchor.constraint(equalTo: view.leftAnchor),
additionalHeightView.rightAnchor.constraint(equalTo: view.rightAnchor),
additionalHeightView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
] + additionalWidthConstraints + additionalHeightConstraints
)
updateLayout()
}
func input(_ value: Input) {
self.parameter = value
}
func updateLayout() {
additionalWidthConstraints.forEach { $0.constant = parameter.additionalWidth }
additionalHeightConstraints.forEach { $0.constant = parameter.additionalHeight }
}
}
final class AutolayoutTableViewController: UITableViewController, Instantiatable, Injectable {
let environment: Void
var elements: [AutolayoutViewController.Input]
init(with input: [AutolayoutViewController.Input], environment: Void) {
self.environment = environment
self.elements = input
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
TableViewCell<AutolayoutViewController>.register(to: tableView)
}
func input(_ input: [AutolayoutViewController.Input]) {
self.elements = input
tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return elements.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return TableViewCell<AutolayoutViewController>.dequeued(from: tableView, for: indexPath, input: elements[indexPath.row], parentViewController: self)
}
}
final class AutolayoutCollectionViewController: UICollectionViewController, Instantiatable, Injectable {
let environment: Void
let flowLayout: UICollectionViewFlowLayout
var elements: [AutolayoutViewController.Input]
init(with input: [AutolayoutViewController.Input], environment: Void) {
self.environment = environment
self.elements = input
self.flowLayout = UICollectionViewFlowLayout()
super.init(collectionViewLayout: flowLayout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
CollectionViewCell<AutolayoutViewController>.register(to: collectionView!)
if #available(iOS 10.0, *) {
flowLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize
}
flowLayout.estimatedItemSize = CGSize(width: 200.0, height: 200.0)
flowLayout.sectionInset = UIEdgeInsets(top: 20.0, left: 20.0, bottom: 20.0, right: 20.0)
}
func input(_ input: [AutolayoutViewController.Input]) {
self.elements = input
collectionView!.reloadData()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return elements.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return CollectionViewCell<AutolayoutViewController>.dequeued(from: collectionView, for: indexPath, input: elements[indexPath.row], parentViewController: self)
}
}
| 37.340557 | 171 | 0.689827 |
7a240561b96fc662610550ba291b0573b3b719c3 | 2,507 | /// Input / Output Request identifier for manipulating underlying device parameters of special files.
public protocol IOControlID: RawRepresentable {
/// Create a strongly-typed I/O request from a raw C IO request.
init?(rawValue: CUnsignedLong)
/// The raw C IO request ID.
var rawValue: CUnsignedLong { get }
}
public protocol IOControlInteger {
associatedtype ID: IOControlID
static var id: ID { get }
var intValue: Int32 { get }
}
public protocol IOControlValue {
associatedtype ID: IOControlID
static var id: ID { get }
mutating func withUnsafeMutablePointer<Result>(_ body: (UnsafeMutableRawPointer) throws -> (Result)) rethrows -> Result
}
#if os(Linux)
public extension IOControlID {
init?(type: IOType, direction: IODirection, code: CInt, size: CInt) {
self.init(rawValue: _IOC(direction, type, code, size))
}
}
/// #define _IOC(dir,type,nr,size) \
/// (((dir) << _IOC_DIRSHIFT) | \
/// ((type) << _IOC_TYPESHIFT) | \
/// ((nr) << _IOC_NRSHIFT) | \
/// ((size) << _IOC_SIZESHIFT))
@usableFromInline
internal func _IOC(
_ direction: IODirection,
_ type: IOType,
_ nr: CInt,
_ size: CInt
) -> CUnsignedLong {
let dir = CInt(direction.rawValue)
let dirValue = dir << _DIRSHIFT
let typeValue = type.rawValue << _TYPESHIFT
let nrValue = nr << _NRSHIFT
let sizeValue = size << _SIZESHIFT
let value = CLong(dirValue | typeValue | nrValue | sizeValue)
return CUnsignedLong(bitPattern: value)
}
@_alwaysEmitIntoClient
internal var _NRBITS: CInt { CInt(8) }
@_alwaysEmitIntoClient
internal var _TYPEBITS: CInt { CInt(8) }
@_alwaysEmitIntoClient
internal var _SIZEBITS: CInt { CInt(14) }
@_alwaysEmitIntoClient
internal var _DIRBITS: CInt { CInt(2) }
@_alwaysEmitIntoClient
internal var _NRMASK: CInt { CInt((1 << _NRBITS)-1) }
@_alwaysEmitIntoClient
internal var _TYPEMASK: CInt { CInt((1 << _TYPEBITS)-1) }
@_alwaysEmitIntoClient
internal var _SIZEMASK: CInt { CInt((1 << _SIZEBITS)-1) }
@_alwaysEmitIntoClient
internal var _DIRMASK: CInt { CInt((1 << _DIRBITS)-1) }
@_alwaysEmitIntoClient
internal var _NRSHIFT: CInt { CInt(0) }
@_alwaysEmitIntoClient
internal var _TYPESHIFT: CInt { CInt(_NRSHIFT+_NRBITS) }
@_alwaysEmitIntoClient
internal var _SIZESHIFT: CInt { CInt(_TYPESHIFT+_TYPEBITS) }
@_alwaysEmitIntoClient
internal var _DIRSHIFT: CInt { CInt(_SIZESHIFT+_SIZEBITS) }
#endif
| 26.114583 | 123 | 0.680495 |
0378649ee27ac943eaeb36ab41c01875cd11c0cf | 4,255 | //
// String.swift
// thecareportal
//
// Created by Jayesh on 25/10/17.
// Copyright © 2017 Jiniguru. All rights reserved.
//
import UIKit
import Foundation
func localized(_ string: String) -> String {
return NSLocalizedString(string, comment: "")
}
extension String{
func getWidthofString(font : UIFont) -> CGFloat{
let fontAttributes = [NSAttributedString.Key.font: font]
let size = (self as NSString).size(withAttributes: fontAttributes)
return size.width
}
func getConvertDateString(currentdateformatter : String ,convdateformatter : String) -> String{
//Sunday,July 16 2017
let dateformatter = DateFormatter()
dateformatter.dateFormat = currentdateformatter
let date = dateformatter.date(from: self)
dateformatter.dateFormat = convdateformatter
return dateformatter.string(from:date!)
}
static func random(_ length: Int = 20) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.count))
randomString += "\(base[base.index(base.startIndex, offsetBy: Int(randomValue))])"
}
return randomString
}
func base64Encoded() -> String? {
if let data = self.data(using: .utf8) {
return data.base64EncodedString()
}
return nil
}
func base64Decoded() -> String? {
if let data = Data(base64Encoded: self, options: .ignoreUnknownCharacters) {
return String(data: data, encoding: .utf8)
}
return nil
}
// func sha256() -> String {
// if let stringData = self.data(using: String.Encoding.utf8) {
// return hexStringFromData(input: digest(input: stringData as NSData))
// }
//
// return ""
// }
// private func digest(input: NSData) -> NSData {
// let digestLength = Data(count: Int(CC_SHA256_DIGEST_LENGTH))
// var hash = [UInt8](repeating: 0, count: digestLength)
// CC_SHA256(input.bytes, UInt32(input.length), &hash)
// return NSData(bytes: hash, length: digestLength)
// }
private func hexStringFromData(input: NSData) -> String {
var bytes = [UInt8](repeating: 0, count: input.length)
input.getBytes(&bytes, length: input.length)
var hexString = ""
for byte in bytes {
hexString += String(format: "%02x", UInt8(byte))
}
return hexString
}
func ranges(of string: String) -> [Range<Index>] {
var ranges = [Range<Index>]()
let pCount = string.count
let strCount = self.count
if strCount < pCount { return [] }
for i in 0...(strCount-pCount) {
let from = index(self.startIndex, offsetBy: i)
if let to = index(from, offsetBy: pCount, limitedBy: self.endIndex) {
if string == self[from..<to] {
ranges.append(from..<to)
}
}
}
return ranges
}
func removingWhitespaces() -> String {
return components(separatedBy: .whitespaces).joined()
}
func getDateFromString(dateFormatter : String) -> Date{
let dateformatter = DateFormatter()
dateformatter.dateFormat = dateFormatter
return dateformatter.date(from: self)!
}
func htmlAttributedString(color : UIColor,fontsize : String) -> NSAttributedString? {
let inputText = "\(self)<style>body { font-family: 'Lato-Regular'; font-size:fontsize; \(color.hexDescription())}</style>"
guard let data = inputText.data(using: String.Encoding.utf8, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString (
data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil) else { return nil }
return html
}
}
| 32.234848 | 130 | 0.592714 |
debc22be889879c86a679fc0d779d86d20a5bbd6 | 1,536 | //
// ImageDownloader.swift
// MovieDataBase
//
// Created by Judar Lima on 20/07/19.
// Copyright © 2019 Judar Lima. All rights reserved.
//
import Foundation
import UIKit
protocol ImageDownloaderProtocol {
func loadImage(from url: URL, completion: @escaping ((UIImage?) -> Void))
func cancelDownload()
}
class ImageDownloader: ImageDownloaderProtocol {
private let urlSession: URLSessionProtocol
private let imageCache: ImageCacher
private var dataTask: URLSessionDataTaskProtocol?
init(urlSession: URLSessionProtocol = URLSession.shared,
imageCache: ImageCacher = ImageCacher.shared) {
self.urlSession = urlSession
self.imageCache = imageCache
}
func loadImage(from url: URL, completion: @escaping ((UIImage?) -> Void)) {
if let cachedImage = imageCache.loadImage(for: url.absoluteString as NSString) {
DispatchQueue.main.async {
completion(cachedImage)
}
} else {
self.dataTask = urlSession.dataTask(with: url) { [imageCache] (data, _, _) in
guard
let data = data,
let image = UIImage(data: data)
else { return }
imageCache.cache(image: image, withKey: url.absoluteString as NSString)
DispatchQueue.main.async {
completion(image)
}}
self.dataTask?.resume()
}
}
func cancelDownload() {
self.dataTask?.cancel()
}
}
| 30.117647 | 89 | 0.608073 |
bfdd8f4538a7e122ab523040a9dee244b33daa54 | 979 | //
// ContentView.swift
// EverydayQuran
//
// Created by Shahriar Nasim Nafi on 26/4/21.
//
import SwiftUI
struct ContentView: View {
@State var showSplash = true
init() {
UITabBar.appearance().barTintColor = UIColor.white
}
var body: some View {
ZStack{
TabView {
HomeView()
.tabItem { Image("Quran") }
SurahDetailViewHeader()
.tabItem { Image(systemName: "gear") }
}
.edgesIgnoringSafeArea(.all)
SplashScreen()
.opacity(showSplash ? 1 : 0)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
withAnimation() {
self.showSplash = false
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 22.25 | 71 | 0.48621 |
f438aba351ce8bb4bb267a97f7d33370ef239e0f | 11,315 | //
// UIButton+xbExtension.swift
// PodValide
//
// Created by huadong on 2022/1/25.
//
import UIKit
private var xb_touchAreaEdgeInsets: UIEdgeInsets = .zero
public extension UIButton {
// MARK: 按钮点击去掉过渡效果处理
/** 按钮标题 - 按钮点击去掉过渡效果处理*/
func set(title: String? ,selectedTitle: String?) {
self.setTitle(title, for: .normal)
self.setTitle(title, for: .highlighted)
self.setTitle(selectedTitle, for: .selected)
self.setTitle(selectedTitle, for: [.selected, .highlighted])
}
/** 按钮标题颜色 - 按钮点击去掉过渡效果处理*/
func set(titleColor: UIColor? ,selectedTitleColor: UIColor?) {
self.setTitleColor(titleColor, for: .normal)
self.setTitleColor(titleColor, for: .highlighted)
self.setTitleColor(selectedTitleColor, for: .selected)
self.setTitleColor(selectedTitleColor, for: [.selected, .highlighted])
}
/** 按钮图片 - 按钮点击去掉过渡效果处理*/
func set(image: String? ,selectedImage: String?){
self.setImage(UIImage(named: image ?? ""), for: .normal)
self.setImage(UIImage(named: image ?? ""), for: .highlighted)
self.setImage(UIImage(named: selectedImage ?? ""), for: .selected)
self.setImage(UIImage(named: selectedImage ?? ""), for: [.selected, .highlighted])
}
/// Increase your button touch area.
/// If your button frame is (0,0,40,40). Then call button.ts_touchInsets = UIEdgeInsetsMake(-30, -30, -30, -30), it will Increase the touch area
/// 1. 扩大按钮点击范围 负数为扩大范围,证书为缩小范围
var xb_touchInsets: UIEdgeInsets {
get {
if let value = objc_getAssociatedObject(self, &xb_touchAreaEdgeInsets) as? NSValue {
var edgeInsets: UIEdgeInsets = .zero
value.getValue(&edgeInsets)
return edgeInsets
}else {
return .zero
}
}
set(newValue) {
var newValueCopy = newValue
let objCType = NSValue(uiEdgeInsets: .zero).objCType
let value = NSValue(&newValueCopy, withObjCType: objCType)
objc_setAssociatedObject(self, &xb_touchAreaEdgeInsets, value, .OBJC_ASSOCIATION_RETAIN)
}
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if self.xb_touchInsets == .zero || !self.isEnabled || self.isHidden || !self.isUserInteractionEnabled {
return super.point(inside: point, with: event)
}
let relativeFrame = self.bounds
let hitFrame = relativeFrame.inset(by: self.xb_touchInsets)
return hitFrame.contains(point)
}
//2.子view超出了父view的bounds响应事件
//重载父view的hitTest(_ point: CGPoint, with event: UIEvent?)方法
/*
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
for subView in self.subviews {
// 把父类point点转换成子类坐标系下的点
let convertedPoint = subView.convert(point, from: self)
// 注意点:hitTest方法内部会调用pointInside方法,询问触摸点是否在这个控件上
// 根据point,找到适合响应事件的这个View
let hitTestView = subView.hitTest(convertedPoint, with: event)
if hitTestView != nil {
return hitTestView
}
}
return nil
}
*/
/*
// 2.UIButton超出父视图响应
// 当我们自定义tabbar并放一个异形按钮在上面,这个按钮有一部分又超出了tabbar,超出的部分点击就没有响应,这时候可以用判断控件是否接受事件以及找到最合适的view的方法来实现
- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event {
UIView * view = [super hitTest:point withEvent:event];
if (view == nil) {
for (UIView * subView in self.subviews) {
// 将坐标系转化为自己的坐标系
CGPoint pt = [subView convertPoint:point fromView:self];
/*
if (CGRectContainsPoint(subView.bounds, pt)) {
view = subView;
}
*/
// 这种方式更好 不会影响按钮已设置的扩大范围;通过比较点是否包含会影响已设置的扩大范围
UIView *hitTestView = [subView hitTest:pt withEvent:evevt]
if hitTestView != nil {
return hitTestView
}
}
}
return view;
}
// 如果上面方法无效,可能是你的按钮并不是直接添加在tabbar,这时候来个暴力一点,当找不到view时直接判断那个超出父视图按钮
- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event {
UIView * view = [super hitTest:point withEvent:event];
if (view == nil) {
// 将坐标系转化为自己的坐标系
CGPoint pt = [self.scanButton convertPoint:point fromView:self];
if (CGRectContainsPoint(self.scanButton.bounds, pt)) {
view = subView;
}
}
return view;
}
*/
//3.使部分区域失去响应.
//场景需求:tableView占整个屏幕,tableView底下是一个半透明的HUD,点击下面没有内容区域,要让HUD去响应事件.
//在自定义的tableView中重载hitTest方法
/*
// tableView会拦截底部`backgroundView`事件的响应,
// 实现点击tableViewCell 之外的地方,让tableView底下的backgroundView响应tap事件
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let hitView = super.hitTest(point, with: event) , hitView.isKind(of: BTTableCellContentView.self) {
return hitView
}
// 返回nil 那么事件就不由当前控件处理
return nil;
}
*/
//4.让非scrollView区域响应scrollView拖拽事件
//这是一个使用scrollView自定义实现的卡片式轮播器,如何实现拖拽scrollView两边的view区域,和拖拽中间scrollView一样的效果呢?只需要在scrollView的父类重载hitTest方法
/*
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if self.point(inside: point, with: event) == true {
return scrollView
}
return nil
}
*/
}
public enum xbButtonImageStyle {
case top /// image在上,label在下
case left /// image在左,label在右
case bottom /// image在下,label在上
case right /// image在右,label在左
}
public extension UIButton {
func xb_setButtonImage(style: xbButtonImageStyle = xbButtonImageStyle.left, space: CGFloat = 0.0){
// if #available(iOS 15.0, *) {
// var config = UIButton.Configuration.plain()
// ///这里imagePlacement图片的位置 .leading .trailing .bottom .top
// config.imagePlacement = .top
// config.imagePadding = 10
// config.image = UIImage(named: "imgname")
// self.configuration = config
// }
let imageWith = self.imageView?.bounds.width ?? 0
let imageHeight = self.imageView?.bounds.height ?? 0
let labelWidth = self.titleLabel?.intrinsicContentSize.width ?? 0
let labelHeight = self.titleLabel?.intrinsicContentSize.height ?? 0
var imageEdgeInsets = UIEdgeInsets.zero
var labelEdgeInsets = UIEdgeInsets.zero
var contentEdgeInsets = UIEdgeInsets.zero
let bWidth = self.bounds.width
let min_height = min(imageHeight, labelHeight)
switch style {
case .left:
self.contentVerticalAlignment = .center
imageEdgeInsets = UIEdgeInsets(top: 0,
left: 0,
bottom: 0,
right: 0)
labelEdgeInsets = UIEdgeInsets(top: 0,
left: space,
bottom: 0,
right: -space)
contentEdgeInsets = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: space)
case .right:
self.contentVerticalAlignment = .center
var w_di = labelWidth + space/2
if (labelWidth+imageWith+space) > bWidth{
let labelWidth_f = self.titleLabel?.frame.width ?? 0
w_di = labelWidth_f + space/2
}
imageEdgeInsets = UIEdgeInsets(top: 0,
left: w_di,
bottom: 0,
right: -w_di)
labelEdgeInsets = UIEdgeInsets(top: 0,
left: -(imageWith+space/2),
bottom: 0,
right: imageWith+space/2)
contentEdgeInsets = UIEdgeInsets(top: 0, left: space/2, bottom: 0, right: space/2.0)
case .top:
//img在上或者在下 一版按钮是水平垂直居中的
self.contentHorizontalAlignment = .center
self.contentVerticalAlignment = .center
var w_di = labelWidth/2.0
//如果内容宽度大于button宽度 改变计算方式
if (labelWidth+imageWith+space) > bWidth{
w_di = (bWidth - imageWith)/2
}
//考虑图片+显示文字宽度大于按钮总宽度的情况
let labelWidth_f = self.titleLabel?.frame.width ?? 0
if (imageWith+labelWidth_f+space)>bWidth{
w_di = (bWidth - imageWith)/2
}
imageEdgeInsets = UIEdgeInsets(top: -(labelHeight+space),
left: w_di,
bottom: 0,
right: -w_di)
labelEdgeInsets = UIEdgeInsets(top: 0,
left: -imageWith,
bottom:-(space+imageHeight),
right: 0)
let h_di = (min_height+space)/2.0
contentEdgeInsets = UIEdgeInsets(top:h_di,left: 0,bottom:h_di,right: 0)
case .bottom:
//img在上或者在下 一版按钮是水平垂直居中的
self.contentHorizontalAlignment = .center
self.contentVerticalAlignment = .center
var w_di = labelWidth/2
//如果内容宽度大于button宽度 改变计算方式
if (labelWidth+imageWith+space) > bWidth{
w_di = (bWidth - imageWith)/2
}
//考虑图片+显示文字宽度大于按钮总宽度的情况
let labelWidth_f = self.titleLabel?.frame.width ?? 0
if (imageWith+labelWidth_f+space)>bWidth{
w_di = (bWidth - imageWith)/2
}
imageEdgeInsets = UIEdgeInsets(top: 0,
left: w_di,
bottom: -(labelHeight+space),
right: -w_di)
labelEdgeInsets = UIEdgeInsets(top: -(space+imageHeight),
left: -imageWith,
bottom: 0,
right: 0)
let h_di = (min_height+space)/2.0
contentEdgeInsets = UIEdgeInsets(top:h_di, left: 0,bottom:h_di,right: 0)
}
self.contentEdgeInsets = contentEdgeInsets
self.titleEdgeInsets = labelEdgeInsets
self.imageEdgeInsets = imageEdgeInsets
}
}
| 38.883162 | 148 | 0.521167 |
2167eff7881313db46e11dd9decc19751862b9a5 | 3,598 | // Copyright (c) 2020 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.
//
// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
// distribute, sublicense, create a derivative work, and/or sell copies of the
// Software in any work that is designed, intended, or marketed for pedagogical or
// instructional purposes related to programming, coding, application development,
// or information technology. Permission for such use, copying, modification,
// merger, publication, distribution, sublicensing, creation of derivative works,
// or sale is expressly withheld.
//
// 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 SwiftUI
private enum Layout {
static let lineWidth: CGFloat = 2
}
struct SpinningCircleView: View {
@State private var animateRotation = false
@State private var animateStrokeStart = true
@State private var animateStrokeEnd = true
var body: some View {
ZStack {
background
circleOverlay
}
}
var background: some View {
ZStack(alignment: .center) {
Circle()
.stroke(Color.downloadButtonDownloadingBackground, lineWidth: Layout.lineWidth)
.downloadIconFrame
RoundedRectangle(cornerRadius: 1)
.fill(Color.downloadButtonDownloadingBackground)
.frame(width: 6, height: 6)
}
}
var circleOverlay: some View {
Circle()
.trim(
from: animateStrokeStart ? 0.2 : 0.1,
to: animateStrokeEnd ? 0.2 : 0.5
)
.stroke(Color.downloadButtonDownloadingForeground, lineWidth: Layout.lineWidth)
.downloadIconFrame
.rotationEffect(.degrees(animateRotation ? 360 : 0))
.onAppear {
withAnimation(
Animation
.linear(duration: 1)
.repeatForever(autoreverses: false)
) {
animateRotation.toggle()
}
withAnimation(
Animation
.linear(duration: 1)
.delay(0.5)
.repeatForever(autoreverses: true)
) {
animateStrokeStart.toggle()
}
withAnimation(
Animation
.linear(duration: 1)
.delay(1)
.repeatForever(autoreverses: true)
) {
animateStrokeEnd.toggle()
}
}
}
}
struct SpinningCircleView_Previews: PreviewProvider {
static var previews: some View {
SwiftUI.Group {
spinners.colorScheme(.dark)
spinners.colorScheme(.light)
}
}
static var spinners: some View {
SpinningCircleView()
.padding()
.background(Color.backgroundColor)
}
}
| 32.125 | 87 | 0.675097 |
bf96659668798a611b4dd2cc3faf65cc50c6e35f | 560 | //
// Segment.swift
// TPGHorizontalMenu
//
// Created by David Livadaru on 07/03/2017.
// Copyright © 2017 3Pillar Global. All rights reserved.
//
import Foundation
/// A data structure which provides and implementation for ProgressPoint.
public struct Segment<SegmentPoint: BasicArithmetic>: ProgressPoint {
public typealias Point = SegmentPoint
public let first: SegmentPoint
public let second: SegmentPoint
public init(first: SegmentPoint, second: SegmentPoint) {
self.first = first
self.second = second
}
}
| 24.347826 | 73 | 0.7125 |
3a42313a3e524f141480e08034f01615d86f3b6c | 13,854 | //
// WalletViewController.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 4/21/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import RxCocoa
import RxFeedback
import RxSwift
import UIKit
private extension WalletTypes.DisplayState.Kind {
var name: String {
switch self {
case .assets:
return Localizable.Waves.Wallet.Segmentedcontrol.assets
case .leasing:
return Localizable.Waves.Wallet.Segmentedcontrol.leasing
}
}
}
final class WalletViewController: UIViewController {
@IBOutlet weak var scrolledTablesComponent: ScrolledContainerView!
@IBOutlet var globalErrorView: GlobalErrorView!
private var displayData: WalletDisplayData!
private let disposeBag: DisposeBag = DisposeBag()
private let displays: [WalletTypes.DisplayState.Kind] = [.assets, .leasing]
private var isRefreshing: Bool = false
private var snackError: String? = nil
private var hasAddingViewBanners: Bool = false
private let buttonAddress = UIBarButtonItem(image: Images.walletScanner.image,
style: .plain,
target: nil,
action: nil)
private let buttonSort = UIBarButtonItem(image: Images.walletSort.image,
style: .plain,
target: nil,
action: nil)
private let sendEvent: PublishRelay<WalletTypes.Event> = PublishRelay<WalletTypes.Event>()
var presenter: WalletPresenterProtocol!
override func viewDidLoad() {
super.viewDidLoad()
displayData = WalletDisplayData(scrolledTablesComponent: scrolledTablesComponent)
scrolledTablesComponent.scrollViewDelegate = self
scrolledTablesComponent.containerViewDelegate = self
scrolledTablesComponent.setup(segmentedItems: displays.map{ $0.name }, tableDataSource: displayData, tableDelegate: displayData)
setupLanguages()
setupBigNavigationBar()
createMenuButton()
setupSegmetedControl()
setupTableView()
setupSystem()
globalErrorView.retryDidTap = { [weak self] in
self?.sendEvent.accept(.refresh)
}
NotificationCenter.default.addObserver(self, selector: #selector(changedLanguage), name: .changedLanguage, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
hideTopBarLine()
for table in scrolledTablesComponent.tableViews {
table.startSkeletonCells()
}
scrolledTablesComponent.viewControllerWillAppear()
navigationController?.navigationBar.backgroundColor = view.backgroundColor
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
scrolledTablesComponent.viewControllerWillDissapear()
navigationController?.navigationBar.backgroundColor = nil
}
@objc func changedLanguage() {
setupLanguages()
setupSegmetedControl()
for view in scrolledTablesComponent.topContents {
if let updateView = view as? WalletUpdateAppView {
updateView.update(with: ())
}
else if let clearView = view as? WalletClearAssetsView {
clearView.update(with: ())
}
}
scrolledTablesComponent.reloadData()
}
}
//MARK: - MainTabBarControllerProtocol
extension WalletViewController: MainTabBarControllerProtocol {
func mainTabBarControllerDidTapTab() {
guard isViewLoaded else { return }
scrolledTablesComponent.scrollToTop()
}
}
//MARK: - UIScrollViewDelegate
extension WalletViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == scrolledTablesComponent {
setupSearchBarOffset()
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if scrollView == scrolledTablesComponent {
setupSearchBarOffset()
}
}
}
//MARK: - ScrolledContainerViewDelegate
extension WalletViewController: ScrolledContainerViewDelegate {
func scrolledContainerViewDidScrollToIndex(_ index: Int) {
setupRightButons(kind: displays[index])
sendEvent.accept(.changeDisplay(displays[index]))
DispatchQueue.main.async {
self.scrolledTablesComponent.endRefreshing()
}
}
}
// MARK: UIGestureRecognizerDelegate
extension WalletViewController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
// MARK: Bind UI
extension WalletViewController {
func setupSystem() {
let feedback: WalletPresenterProtocol.Feedback = bind(self) { owner, state in
let subscriptions = owner.subscriptions(state: state)
let events = owner.events()
return Bindings(subscriptions: subscriptions,
events: events)
}
let readyViewFeedback: WalletPresenterProtocol.Feedback = { [weak self] _ in
guard let self = self else { return Signal.empty() }
return self
.rx
.viewWillAppear
.map { _ in WalletTypes.Event.viewWillAppear }
.asSignal(onErrorSignalWith: Signal.empty())
}
let viewDidDisappearFeedback: WalletPresenterProtocol.Feedback = { [weak self] _ in
guard let self = self else { return Signal.empty() }
return self
.rx
.viewDidDisappear
.map { _ in WalletTypes.Event.viewDidDisappear }
.asSignal(onErrorSignalWith: Signal.empty())
}
presenter.system(feedbacks: [feedback,
readyViewFeedback,
viewDidDisappearFeedback])
}
func events() -> [Signal<WalletTypes.Event>] {
let sortTapEvent = buttonSort
.rx
.tap
.map { WalletTypes.Event.tapSortButton }
.asSignal(onErrorSignalWith: Signal.empty())
let addressTapEvent = buttonAddress
.rx
.tap
.map { WalletTypes.Event.tapAddressButton }
.asSignal(onErrorSignalWith: Signal.empty())
let refreshEvent = scrolledTablesComponent
.rx
.didRefreshing(refreshControl: scrolledTablesComponent.refreshControl!)
.map { _ in WalletTypes.Event.refresh }
.asSignal(onErrorSignalWith: Signal.empty())
let tapEvent = displayData
.tapSection
.map { WalletTypes.Event.tapSection($0) }
.asSignal(onErrorSignalWith: Signal.empty())
let changedSpamList = NotificationCenter.default.rx
.notification(.changedSpamList)
.map { _ in WalletTypes.Event.refresh }
.asSignal(onErrorSignalWith: Signal.empty())
let recieverEvents = sendEvent.asSignal()
return [refreshEvent,
tapEvent,
sortTapEvent,
addressTapEvent,
recieverEvents,
changedSpamList]
}
func subscriptions(state: Driver<WalletTypes.State>) -> [Disposable] {
let subscriptionSections = state.drive(onNext: { [weak self] state in
guard let self = self else { return }
if state.action == .none {
return
}
self.addTopViewBanners(hasData: state.hasData,
isShowCleanWalletBanner: state.isShowCleanWalletBanner,
isHasAppUpdate: state.isHasAppUpdate)
self.updateView(with: state.displayState)
})
return [subscriptionSections]
}
func addTopViewBanners(hasData: Bool, isShowCleanWalletBanner: Bool, isHasAppUpdate: Bool) {
if hasData && !hasAddingViewBanners {
hasAddingViewBanners = true
if isHasAppUpdate {
let view = WalletUpdateAppView.loadFromNib()
scrolledTablesComponent.addTopView(view, animation: false)
view.viewTapped = { [weak self] in
self?.sendEvent.accept(.updateApp)
}
}
if isShowCleanWalletBanner {
let view = WalletClearAssetsView.loadFromNib()
scrolledTablesComponent.addTopView(view, animation: false)
view.removeViewTapped = { [weak self] in
self?.scrolledTablesComponent.removeTopView(view, animation: true)
self?.sendEvent.accept(.setCleanWalletBanner)
}
}
}
}
func updateView(with state: WalletTypes.DisplayState) {
displayData.apply(assetsSections: state.assets.visibleSections, leasingSections: state.leasing.visibleSections, animateType: state.animateType) { [weak self] in
if state.isRefreshing == false {
self?.scrolledTablesComponent.endRefreshing()
}
}
switch state.animateType {
case .refreshOnlyError, .refresh:
updateErrorView(with: state.currentDisplay.errorState)
default:
break
}
scrolledTablesComponent.segmentedControl.setSelectedIndex(displays.firstIndex(of: state.kind) ?? 0, animation: false)
setupRightButons(kind: state.kind)
}
func updateErrorView(with state: DisplayErrorState) {
switch state {
case .none:
if let snackError = snackError {
hideSnack(key: snackError)
}
snackError = nil
self.globalErrorView.isHidden = true
case .error(let error):
switch error {
case .globalError(let isInternetNotWorking):
self.globalErrorView.isHidden = false
if isInternetNotWorking {
globalErrorView.update(with: .init(kind: .internetNotWorking))
} else {
globalErrorView.update(with: .init(kind: .serverError))
}
case .internetNotWorking:
globalErrorView.isHidden = true
snackError = showWithoutInternetSnack()
case .message(let message):
globalErrorView.isHidden = true
snackError = showErrorSnack(message)
default:
snackError = showErrorNotFoundSnack()
}
case .waiting:
break
}
}
private func showWithoutInternetSnack() -> String {
return showWithoutInternetSnack { [weak self] in
self?.sendEvent.accept(.refresh)
}
}
private func showErrorSnack(_ message: (String)) -> String {
return showErrorSnack(title: message, didTap: { [weak self] in
self?.sendEvent.accept(.refresh)
})
}
private func showErrorNotFoundSnack() -> String {
return showErrorNotFoundSnack() { [weak self] in
self?.sendEvent.accept(.refresh)
}
}
}
// MARK: Setup Methods
private extension WalletViewController {
func setupSearchBarOffset() {
if isSmallNavigationBar && displayData.isNeedSetupSearchBarPosition {
let diff = (scrolledTablesComponent.topOffset + WalletSearchTableViewCell.viewHeight()) - (scrolledTablesComponent.contentOffset.y + scrolledTablesComponent.smallTopOffset)
var offset: CGFloat = 0
if diff > WalletSearchTableViewCell.viewHeight() / 2 {
offset = -scrolledTablesComponent.smallTopOffset
}
else {
offset = -scrolledTablesComponent.smallTopOffset + WalletSearchTableViewCell.viewHeight()
}
offset += scrolledTablesComponent.topOffset
setupSmallNavigationBar()
scrolledTablesComponent.setContentOffset(.init(x: 0, y: offset), animated: true)
}
}
func setupLanguages() {
navigationItem.title = Localizable.Waves.Wallet.Navigationbar.title
}
func setupRightButons(kind: WalletTypes.DisplayState.Kind) {
switch kind {
case .assets:
navigationItem.rightBarButtonItems = [buttonAddress, buttonSort]
case .leasing:
navigationItem.rightBarButtonItems = [buttonAddress]
}
}
func setupTableView() {
displayData.delegate = self
displayData.balanceCellDelegate = self
}
func setupSegmetedControl() {
scrolledTablesComponent.segmentedControl.items = displays.map{ $0.name }
}
}
//MARK: - WalletLeasingBalanceCellDelegate
extension WalletViewController: WalletLeasingBalanceCellDelegate {
func walletLeasingBalanceCellDidTapStartLease(availableMoney: Money) {
sendEvent.accept(.showStartLease(availableMoney))
}
}
// MARK: WalletDisplayDataDelegate
extension WalletViewController: WalletDisplayDataDelegate {
func showSearchVC(fromStartPosition: CGFloat) {
sendEvent.accept(.presentSearch(startPoint: fromStartPosition))
}
func tableViewDidSelect(indexPath: IndexPath) {
sendEvent.accept(.tapRow(indexPath))
}
}
| 32.521127 | 184 | 0.608849 |
90806ef11f6186668eec164cb8d1c2a32af3bc6b | 1,198 | // Copyright © 2021 Brad Howes. All rights reserved.
import CoreAudioKit
import os
/**
Controller for a knob and text view / label.
*/
final class SwitchController: AUParameterControl {
private let log = Logging.logger("SwitchController")
private let parameterObserverToken: AUParameterObserverToken
let parameter: AUParameter
let _control: Switch
var control: NSObject { _control }
init(parameterObserverToken: AUParameterObserverToken, parameter: AUParameter, control: Switch) {
self.parameterObserverToken = parameterObserverToken
self.parameter = parameter
self._control = control
control.isOn = parameter.value > 0.0 ? true : false
}
}
extension SwitchController {
func controlChanged() {
os_log(.info, log: log, "controlChanged - %d", _control.isOn)
parameter.setValue(_control.isOn ? 1.0 : 0.0, originator: parameterObserverToken)
}
func parameterChanged() {
os_log(.info, log: log, "parameterChanged - %f", parameter.value)
_control.isOn = parameter.value > 0.0 ? true : false
}
func setEditedValue(_ value: AUValue) {
parameter.setValue(_control.isOn ? 1.0 : 0.0, originator: parameterObserverToken)
}
}
| 28.52381 | 99 | 0.722871 |
640a6ecffa60542a06b04c9c7e1b263cf860879d | 5,595 | import CasePaths
import ItemFeature
import Models
import SwiftUI
import SwiftUIHelpers
public class ItemRowViewModel: Hashable, Identifiable, ObservableObject {
@Published public var item: Item
@Published public var route: Route?
@Published var isSaving = false
public func hash(into hasher: inout Hasher) {
hasher.combine(self.item.id)
}
public static func == (lhs: ItemRowViewModel, rhs: ItemRowViewModel) -> Bool {
lhs.item.id == rhs.item.id
}
public enum Route: Equatable {
case deleteAlert
case duplicate(ItemViewModel)
case edit(ItemViewModel)
public static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.deleteAlert, .deleteAlert):
return true
case let (.duplicate(lhs), .duplicate(rhs)):
return lhs === rhs
case let (.edit(lhs), .edit(rhs)):
return lhs === rhs
case (.deleteAlert, _), (.duplicate, _), (.edit, _):
return false
}
}
}
public var onDelete: () -> Void = {}
public var onDuplicate: (Item) -> Void = { _ in }
public var id: Item.ID { self.item.id }
public init(item: Item) {
self.item = item
}
public func deleteButtonTapped() {
self.route = .deleteAlert
}
func deleteConfirmationButtonTapped() {
self.onDelete()
self.route = nil
}
public func setEditNavigation(isActive: Bool) {
self.route = isActive ? .edit(.init(item: self.item)) : nil
}
func edit(item: Item) {
self.isSaving = true
Task { @MainActor in
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
self.isSaving = false
self.item = item
self.route = nil
}
}
public func cancelButtonTapped() {
self.route = nil
}
public func duplicateButtonTapped() {
self.route = .duplicate(.init(item: self.item.duplicate()))
}
func duplicate(item: Item) {
self.onDuplicate(item)
self.route = nil
}
}
extension Item {
public func duplicate() -> Self {
.init(name: self.name, color: self.color, status: self.status)
}
}
public struct ItemRowView: View {
@ObservedObject var viewModel: ItemRowViewModel
public init(
viewModel: ItemRowViewModel
) {
self.viewModel = viewModel
}
public var body: some View {
NavigationLink(
unwrap: self.$viewModel.route,
case: /ItemRowViewModel.Route.edit,
onNavigate: self.viewModel.setEditNavigation(isActive:),
destination: { $itemViewModel in
ItemView(viewModel: itemViewModel)
.navigationBarTitle("Edit")
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") {
self.viewModel.cancelButtonTapped()
}
}
ToolbarItem(placement: .primaryAction) {
HStack {
if self.viewModel.isSaving {
ProgressView()
}
Button("Save") {
self.viewModel.edit(item: itemViewModel.item)
}
}
.disabled(self.viewModel.isSaving)
}
}
}
) {
HStack {
VStack(alignment: .leading) {
Text(self.viewModel.item.name)
switch self.viewModel.item.status {
case let .inStock(quantity):
Text("In stock: \(quantity)")
case let .outOfStock(isOnBackOrder):
Text("Out of stock" + (isOnBackOrder ? ": on back order" : ""))
}
}
Spacer()
if let color = self.viewModel.item.color {
Rectangle()
.frame(width: 30, height: 30)
.foregroundColor(color.swiftUIColor)
.border(Color.black, width: 1)
}
Button(action: { self.viewModel.duplicateButtonTapped() }) {
Image(systemName: "square.fill.on.square.fill")
}
.padding(.leading)
Button(action: { self.viewModel.deleteButtonTapped() }) {
Image(systemName: "trash.fill")
}
.padding(.leading)
}
.buttonStyle(.plain)
.foregroundColor(self.viewModel.item.status.isInStock ? nil : Color.gray)
.alert(
self.viewModel.item.name,
isPresented: self.$viewModel.route.isPresent(/ItemRowViewModel.Route.deleteAlert),
actions: {
Button("Delete", role: .destructive) {
self.viewModel.deleteConfirmationButtonTapped()
}
},
message: {
Text("Are you sure you want to delete this item?")
}
)
.popover(
item: self.$viewModel.route.case(/ItemRowViewModel.Route.duplicate)
) { itemViewModel in
NavigationView {
ItemView(viewModel: itemViewModel)
.navigationBarTitle("Duplicate")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") {
self.viewModel.cancelButtonTapped()
}
}
ToolbarItem(placement: .primaryAction) {
Button("Add") {
self.viewModel.duplicate(item: itemViewModel.item)
}
}
}
}
.frame(minWidth: 300, minHeight: 500)
}
}
}
}
struct ItemRowPreviews: PreviewProvider {
static var previews: some View {
NavigationView {
List {
ItemRowView(
viewModel: .init(
item: .init(name: "Keyboard", status: .inStock(quantity: 1))
)
)
}
}
}
}
| 26.14486 | 90 | 0.571582 |
332096d10b71deb547037e9d0f7d355795293abf | 2,351 | import Foundation
import Swift
import GRPC
import Flow
import SwiftProtobuf
public class RpcResponse<T: FlowEntity> {
public var error: Error?
public var result: T?
public init(result: T?, error: Error?){
self.result = result
self.error = error
}
}
public typealias ResultCallback = (RpcResponse<FlowEntity>) -> Void
public protocol FlowRpcClientProtocol{
func getAccount(account: FlowAddress, completion: @escaping(ResultCallback))
func getAccountAtLatestBlock(account: FlowAddress, completion: @escaping(ResultCallback))
func getAccountAtBlockHeight(account: FlowAddress, height: Int, completion: @escaping(ResultCallback))
func ping(completion: @escaping(ResultCallback))
func getLatestBlock(isSealed: Bool, completion: @escaping(ResultCallback))
func getLatestBlockHeader(isSealed: Bool, completion: @escaping(ResultCallback) )
func getBlockHeaderById(id: FlowIdentifier, completion: @escaping(ResultCallback) )
func getBlockHeaderByHeight(height: Int, completion: @escaping(ResultCallback) )
func getBlockById(id: FlowIdentifier, completion: @escaping(ResultCallback) )
func getBlockByHeight(height: Int, completion: @escaping(ResultCallback) )
func getExecutionResultForBlockId(id: FlowIdentifier, completion: @escaping(ResultCallback) )
func getCollectionById(id: FlowIdentifier, completion: @escaping(ResultCallback))
func getEventsForHeightRange(type: String, start: Int, end:Int,completion: @escaping(ResultCallback))
func getEventsForBlockIds(type: String, blockIds: [FlowIdentifier], completion: @escaping (ResultCallback))
func executeScriptAtLatestBlock(script: String, arguments:[CadenceValue], completion: @escaping(ResultCallback))
func executeScriptAtBlockId(script: String, blockId: FlowIdentifier, arguments:[CadenceValue], completion: @escaping(ResultCallback))
func executeScriptAtBlockHeight(script: String, height: Int, arguments:[CadenceValue], completion: @escaping(ResultCallback))
func getNetworkParameters(completion: @escaping(ResultCallback))
func getLatestProtocolStateSnapshot(completion: @escaping(ResultCallback))
func sendTransaction(transaction: FlowTransaction,completion: @escaping(ResultCallback))
func getTransactionResult(id: FlowIdentifier, completion: @escaping(ResultCallback))
}
| 54.674419 | 137 | 0.783071 |
8fe53870c4cb195e126e0bbd97c8db22c71d910c | 103 | import XCTest
@testable import SocketSwiftTests
XCTMain([
testCase(SocketSwiftTests.allTests),
])
| 14.714286 | 40 | 0.786408 |
e478e552346b32ac8b5b16d57e5377577bee1418 | 1,509 | //
// LoadViewExampleViewController.swift
// FSCalendarSwiftExample
//
// Created by dingwenchao on 10/17/16.
// Copyright © 2016 wenchao. All rights reserved.
//
import UIKit
let FSCalendarStandardLineColor = UIColor.white
class LoadViewExampleViewController: UIViewController, FSCalendarDataSource, FSCalendarDelegate {
private weak var calendar: FSCalendar!
override func loadView() {
let view = UIView(frame: UIScreen.main.bounds)
view.backgroundColor = UIColor.groupTableViewBackground
self.view = view
let height: CGFloat = 600
let calendar = FSCalendar(frame: CGRect(x: 0, y: self.navigationController!.navigationBar.frame.maxY, width: self.view.bounds.width, height: height))
calendar.dataSource = self
calendar.delegate = self
calendar.pagingEnabled = false
calendar.appearance.lineColor = UIColor.clear
calendar.appearance.hideWeekday = true
calendar.backgroundColor = UIColor.white
calendar.clipsToBounds = true
self.view.addSubview(calendar)
self.calendar = calendar
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "FSCalendar"
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
if monthPosition == .previous || monthPosition == .next {
calendar.setCurrentPage(date, animated: true)
}
}
}
| 30.795918 | 157 | 0.673294 |
260f720e5f024a946b583451293e41d432cac44c | 22,643 | //
// PetAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
@objc open class PetAPI : NSObject {
/**
Add a new pet to the store
- parameter body: (body) Pet object that needs to be added to the store
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Add a new pet to the store
- POST /pet
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter body: (body) Pet object that needs to be added to the store
- returns: RequestBuilder<Void>
*/
open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder<Void> {
let localVariablePath = "/pet"
let localVariableURLString = PetstoreClient.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Deletes a pet
- parameter petId: (path) Pet id to delete
- parameter apiKey: (header) (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Deletes a pet
- DELETE /pet/{petId}
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) Pet id to delete
- parameter apiKey: (header) (optional)
- returns: RequestBuilder<Void>
*/
open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder<Void> {
var localVariablePath = "/pet/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClient.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"api_key": apiKey?.encodeToJSON(),
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
* enum for parameter status
*/
public enum Status_findPetsByStatus: String, CaseIterable {
case available = "available"
case pending = "pending"
case sold = "sold"
}
/**
Finds Pets by status
- parameter status: (query) Status values that need to be considered for filter
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) {
findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Finds Pets by status
- GET /pet/findByStatus
- Multiple status values can be provided with comma separated strings
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter status: (query) Status values that need to be considered for filter
- returns: RequestBuilder<[Pet]>
*/
open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> {
let localVariablePath = "/pet/findByStatus"
let localVariableURLString = PetstoreClient.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
var localVariableUrlComponents = URLComponents(string: localVariableURLString)
localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
"status": status.encodeToJSON(),
])
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Finds Pets by tags
- parameter tags: (query) Tags to filter by
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@available(*, deprecated, message: "This operation is deprecated.")
open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) {
findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Finds Pets by tags
- GET /pet/findByTags
- Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter tags: (query) Tags to filter by
- returns: RequestBuilder<[Pet]>
*/
@available(*, deprecated, message: "This operation is deprecated.")
open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> {
let localVariablePath = "/pet/findByTags"
let localVariableURLString = PetstoreClient.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
var localVariableUrlComponents = URLComponents(string: localVariableURLString)
localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
"tags": tags.encodeToJSON(),
])
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClient.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Find pet by ID
- parameter petId: (path) ID of pet to return
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) {
getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Find pet by ID
- GET /pet/{petId}
- Returns a single pet
- API Key:
- type: apiKey api_key
- name: api_key
- parameter petId: (path) ID of pet to return
- returns: RequestBuilder<Pet>
*/
open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder<Pet> {
var localVariablePath = "/pet/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClient.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Pet>.Type = PetstoreClient.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Update an existing pet
- parameter body: (body) Pet object that needs to be added to the store
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Update an existing pet
- PUT /pet
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter body: (body) Pet object that needs to be added to the store
- returns: RequestBuilder<Void>
*/
open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder<Void> {
let localVariablePath = "/pet"
let localVariableURLString = PetstoreClient.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
Updates a pet in the store with form data
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) {
updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result -> Void in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Updates a pet in the store with form data
- POST /pet/{petId}
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet that needs to be updated
- parameter name: (form) Updated name of the pet (optional)
- parameter status: (form) Updated status of the pet (optional)
- returns: RequestBuilder<Void>
*/
open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder<Void> {
var localVariablePath = "/pet/{petId}"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClient.basePath + localVariablePath
let localVariableFormParams: [String: Any?] = [
"name": name?.encodeToJSON(),
"status": status?.encodeToJSON(),
]
let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "application/x-www-form-urlencoded",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClient.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
uploads an image
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) {
uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
uploads an image
- POST /pet/{petId}/uploadImage
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet to update
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter file: (form) file to upload (optional)
- returns: RequestBuilder<ApiResponse>
*/
open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder<ApiResponse> {
var localVariablePath = "/pet/{petId}/uploadImage"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClient.basePath + localVariablePath
let localVariableFormParams: [String: Any?] = [
"additionalMetadata": additionalMetadata?.encodeToJSON(),
"file": file?.encodeToJSON(),
]
let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "multipart/form-data",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<ApiResponse>.Type = PetstoreClient.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
/**
uploads an image (required)
- parameter petId: (path) ID of pet to update
- parameter requiredFile: (form) file to upload
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClient.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) {
uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result -> Void in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
uploads an image (required)
- POST /fake/{petId}/uploadImageWithRequiredFile
- OAuth:
- type: oauth2
- name: petstore_auth
- parameter petId: (path) ID of pet to update
- parameter requiredFile: (form) file to upload
- parameter additionalMetadata: (form) Additional data to pass to server (optional)
- returns: RequestBuilder<ApiResponse>
*/
open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder<ApiResponse> {
var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile"
let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClient.basePath + localVariablePath
let localVariableFormParams: [String: Any?] = [
"additionalMetadata": additionalMetadata?.encodeToJSON(),
"requiredFile": requiredFile.encodeToJSON(),
]
let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
"Content-Type": "multipart/form-data",
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<ApiResponse>.Type = PetstoreClient.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters)
}
}
| 46.494867 | 256 | 0.689485 |
bf6e4a415398f10d4b41b80b213409668ee89a3d | 276 | // 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 d = a( {
func a( ) -> {
var d {
init {
{
var d {
extension NSSet {
protocol B {
class A {
class
case ,
| 17.25 | 87 | 0.692029 |
7109ae8c49c25e51288855f159e77204b35301e1 | 130 | import XCTest
@testable import Strong_Reference_CycleTestSuite
XCTMain([
testCase(Strong_Reference_CycleTests.allTests),
])
| 18.571429 | 52 | 0.823077 |
566792d7be25ffb3f87b427d5b6ce9c74658dc46 | 1,153 | import RxSwift
class GlobalMarketInfoManager {
private let expirationInterval: TimeInterval = 600 // 6 mins
private let provider: HsProvider
private let storage: GlobalMarketInfoStorage
init(provider: HsProvider, storage: GlobalMarketInfoStorage) {
self.provider = provider
self.storage = storage
}
}
extension GlobalMarketInfoManager {
func globalMarketPointsSingle(currencyCode: String, timePeriod: TimePeriod) -> Single<[GlobalMarketPoint]> {
let currentTimestamp = Date().timeIntervalSince1970
if let storedInfo = try? storage.globalMarketInfo(currencyCode: currencyCode, timePeriod: timePeriod), currentTimestamp - storedInfo.timestamp < expirationInterval {
return Single.just(storedInfo.points)
}
return provider.globalMarketPointsSingle(currencyCode: currencyCode, timePeriod: timePeriod)
.do(onNext: { [weak self] points in
let info = GlobalMarketInfo(currencyCode: currencyCode, timePeriod: timePeriod, points: points)
try? self?.storage.save(globalMarketInfo: info)
})
}
}
| 34.939394 | 173 | 0.698179 |
b93220a84e2ac9a11ad5289b90be6165faaff5e0 | 6,474 | //
// ZLGeneralDefine.swift
// ZLPhotoBrowser
//
// Created by long on 2020/8/11.
//
// Copyright (c) 2020 Long Zhang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
let ZLMaxImageWidth: CGFloat = 600
struct ZLLayout {
static let navTitleFont = getFont(17)
static let bottomToolViewH: CGFloat = 55
static let bottomToolBtnH: CGFloat = 34
static let bottomToolTitleFont = getFont(17)
static let bottomToolBtnCornerRadius: CGFloat = 5
static let thumbCollectionViewItemSpacing: CGFloat = 2
static let thumbCollectionViewLineSpacing: CGFloat = 2
}
func zlRGB(_ red: CGFloat, _ green: CGFloat, _ blue: CGFloat) -> UIColor {
return UIColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: 1)
}
func getImage(_ named: String) -> UIImage? {
if ZLCustomImageDeploy.deploy.contains(named) {
return UIImage(named: named)
}
return UIImage(named: named, in: Bundle.zlPhotoBrowserBundle, compatibleWith: nil)
}
func getFont(_ size: CGFloat) -> UIFont {
guard let name = ZLCustomFontDeploy.fontName else {
return UIFont.systemFont(ofSize: size)
}
return UIFont(name: name, size: size) ?? UIFont.systemFont(ofSize: size)
}
func markSelected(source: inout [ZLPhotoModel], selected: inout [ZLPhotoModel]) {
guard selected.count > 0 else {
return
}
var selIds: [String: Bool] = [:]
var selEditImage: [String: UIImage] = [:]
var selEditModel: [String: ZLEditImageModel] = [:]
var selIdAndIndex: [String: Int] = [:]
for (index, m) in selected.enumerated() {
selIds[m.ident] = true
selEditImage[m.ident] = m.editImage
selEditModel[m.ident] = m.editImageModel
selIdAndIndex[m.ident] = index
}
source.forEach { (m) in
if selIds[m.ident] == true {
m.isSelected = true
m.editImage = selEditImage[m.ident]
m.editImageModel = selEditModel[m.ident]
selected[selIdAndIndex[m.ident]!] = m
} else {
m.isSelected = false
}
}
}
func getAppName() -> String {
if let name = Bundle.main.localizedInfoDictionary?["CFBundleDisplayName"] as? String {
return name
}
if let name = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String {
return name
}
if let name = Bundle.main.infoDictionary?["CFBundleName"] as? String {
return name
}
return "App"
}
func deviceIsiPhone() -> Bool {
return UI_USER_INTERFACE_IDIOM() == .phone
}
func deviceIsiPad() -> Bool {
return UI_USER_INTERFACE_IDIOM() == .pad
}
func deviceSafeAreaInsets() -> UIEdgeInsets {
var insets: UIEdgeInsets = .zero
if #available(iOS 11, *) {
insets = UIApplication.shared.keyWindow?.safeAreaInsets ?? .zero
}
return insets
}
func getSpringAnimation() -> CAKeyframeAnimation {
let animate = CAKeyframeAnimation(keyPath: "transform")
animate.duration = 0.3
animate.isRemovedOnCompletion = true
animate.fillMode = .forwards
animate.values = [CATransform3DMakeScale(0.7, 0.7, 1),
CATransform3DMakeScale(1.2, 1.2, 1),
CATransform3DMakeScale(0.8, 0.8, 1),
CATransform3DMakeScale(1, 1, 1)]
return animate
}
func showAlertView(_ message: String, _ sender: UIViewController?) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: localLanguageTextValue(.ok), style: .default, handler: nil)
alert.addAction(action)
if deviceIsiPad() {
alert.popoverPresentationController?.sourceView = sender?.view
}
(sender ?? UIApplication.shared.keyWindow?.rootViewController)?.showDetailViewController(alert, sender: nil)
}
func canAddModel(_ model: ZLPhotoModel, currentSelectCount: Int, sender: UIViewController?, showAlert: Bool = true) -> Bool {
guard (ZLPhotoConfiguration.default().canSelectAsset?(model.asset) ?? true) else {
return false
}
if currentSelectCount >= ZLPhotoConfiguration.default().maxSelectCount {
if showAlert {
let message = String(format: localLanguageTextValue(.exceededMaxSelectCount), ZLPhotoConfiguration.default().maxSelectCount)
showAlertView(message, sender)
}
return false
}
if currentSelectCount > 0 {
if !ZLPhotoConfiguration.default().allowMixSelect, model.type == .video {
return false
}
}
if model.type == .video {
if model.second > ZLPhotoConfiguration.default().maxSelectVideoDuration {
if showAlert {
let message = String(format: localLanguageTextValue(.longerThanMaxVideoDuration), ZLPhotoConfiguration.default().maxSelectVideoDuration)
showAlertView(message, sender)
}
return false
}
if model.second < ZLPhotoConfiguration.default().minSelectVideoDuration {
if showAlert {
let message = String(format: localLanguageTextValue(.shorterThanMaxVideoDuration), ZLPhotoConfiguration.default().minSelectVideoDuration)
showAlertView(message, sender)
}
return false
}
}
return true
}
func zl_debugPrint(_ message: Any) {
// debugPrint(message)
}
| 34.073684 | 153 | 0.665894 |
dd7d2180609af8abf052b8d340a52a1007f54a36 | 1,676 | //
// Copyright (c) 2018 Google 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 UIKit
import Firebase
class ReviewTableViewCell: UITableViewCell {
@IBOutlet var usernameLabel: UILabel?
@IBOutlet var reviewContentsLabel: UILabel!
@IBOutlet var starsView: ImmutableStarsView!
@IBOutlet weak var yumsLabel: UILabel!
@IBOutlet weak var userIcon: UIImageView?
@IBOutlet weak var yumButton: UIButton!
@IBOutlet weak var restaurantNameLabel: UILabel?
var review: Review!
func populate(review: Review) {
self.review = review
restaurantNameLabel?.text = review.restaurantName
usernameLabel?.text = review.userInfo.name
userIcon?.sd_setImage(with: review.userInfo.photoURL)
starsView.rating = review.rating
reviewContentsLabel.text = review.text
showYumText()
}
func showYumText() {
switch review.yumCount {
case 0:
yumsLabel.isHidden = false
yumsLabel.text = "1 yum"
default:
yumsLabel.isHidden = false
yumsLabel.text = "\(review.yumCount) yums"
}
}
@IBAction func yumWasTapped(_ sender: Any) {
// TODO: Let's increment the yumCount!
}
}
| 27.933333 | 76 | 0.7142 |
4ac02694b5cfa92a2e3ac02d0d559351e2ad1995 | 3,841 | //
// JSONBrowserView.swift
// SwiftUI Views
//
// Created by Emma Labbé on 18-05-20.
// Copyright © 2018-2021 Emma Labbé. All rights reserved.
//
import SwiftUI
func asDictionary(_ value: Any?) -> [String:Any] {
if let dict = value as? [String:Any] {
return dict
} else if let arr = value as? [Any] {
var dict = [String:Any]()
for (index, value) in arr.enumerated() {
dict["\(index)"] = value
}
return dict
}
return [:]
}
func sorted(_ arr: [Any], sorted: Bool) -> [String] {
if !sorted {
return (arr as? [String]) ?? []
} else {
return (arr.sorted { (val1, val2) -> Bool in
guard let str1 = val1 as? String, let str2 = val2 as? String else {
return false
}
guard let num1 = Int(str1), let num2 = Int(str2) else {
return false
}
return num1 < num2
} as? [String]) ?? []
}
}
@available(iOS 13.0, *)
public struct JSONBrowserView: View {
let items: [String:Any]
@Binding var navBarMode: NavigationBarItem.TitleDisplayMode
@State var displayMode: NavigationBarItem.TitleDisplayMode = .inline
let title: String
let isArray: Bool
let dismiss: (() -> Void)?
init(title: String = NSLocalizedString("inspector", comment: "The inspector title"), dismiss: (() -> Void)? = nil, navBarMode: Binding<NavigationBarItem.TitleDisplayMode>, items: [String:Any], isArray: Bool = false) {
self.title = title
self.dismiss = dismiss
self._navBarMode = navBarMode
self.items = items
self.isArray = true
}
public var body: some View {
List(sorted(Array(items.keys), sorted: isArray), id:\.self) { item in
if self.items[item] is Dictionary<String, Any> || self.items[item] is Array<Any> {
NavigationLink(destination: JSONBrowserView(title: item, dismiss: self.dismiss, navBarMode: self.$displayMode, items: asDictionary(self.items[item]), isArray: (self.items[item] is Array<Any>))) {
Cell(title: item, detail: String("\(self.items[item] ?? "")".prefix(300)))
}
} else {
NavigationLink(destination: ValueView(title: item, text: "\(self.items[item] ?? "")")) {
Cell(title: item, detail: String("\(self.items[item] ?? "")".prefix(300)))
}
}
}
.id(UUID())
.navigationBarTitle(Text(title), displayMode: navBarMode)
.navigationBarItems(trailing:
Button(action: {
self.dismiss?()
}) {
if self.dismiss != nil {
Text("done").fontWeight(.bold).padding(5)
}
}.hover()
)
}
}
@available(iOS 13.0, *)
public struct JSONBrowserNavigationView: View {
@State var displayMode: NavigationBarItem.TitleDisplayMode = .automatic
let items: [String:Any]
let dismiss: (() -> Void)?
public init(items: [String:Any], dismiss: (() -> Void)? = nil) {
self.items = items
self.dismiss = dismiss
}
public var body: some View {
NavigationView {
JSONBrowserView(dismiss: dismiss, navBarMode: self.$displayMode, items: items)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
@available(iOS 13.0, *)
struct JSONBrowserView_Previews: PreviewProvider {
static var previews: some View {
JSONBrowserNavigationView(items: ["'Foo'":"Bar", "Hello": ["World": "Foo", "Array": [1, 2, "Foo", "Bar", 4]]])
.previewDevice(PreviewDevice(rawValue: "iPad (7th generation)"))
.previewDisplayName("iPad")
}
}
| 30.975806 | 221 | 0.555324 |
87c90b3168f020f2f4dad2ed4cf728e9b376e6b2 | 287 | /// The version of Canvas Native this library can parse.
let supportedNativeVersion = Set<String>(["0.0.0", "0.0.1", "0.1.0"])
/// Is a given Canvas Native version supported?
public func supports(nativeVersion: String) -> Bool {
return supportedNativeVersion.contains(nativeVersion)
}
| 35.875 | 69 | 0.738676 |
f8f0df4e5b19dc5d197bf14879b7796e9243af36 | 2,170 | //
// DBBPersistenceMap.swift
// DBBBuilder
//
// Created by Dennis Birch on 11/5/18.
// Copyright © 2018 Dennis Birch. All rights reserved.
//
import Foundation
import os.log
/**
A struct used by DBBTableObject to define database tables matching subclass type properties.DBBTableObject subclasses must add entries mapping their properties to their persistence table.
*/
public struct DBBPersistenceMap {
// map property names to storage type
var map = [String : DBBPropertyPersistence]()
// map property names to column names
var propertyColumnMap = [String : String]()
var indexer: DBBIndexer?
public var isInitialized = false
private let logger = DBBBuilder.logger(withCategory: "DBBPersistenceMap")
init(_ dict: [String : DBBPropertyPersistence], columnMap: [String : String], indexer: DBBIndexer? = nil) {
self.map = dict
self.indexer = indexer
self.propertyColumnMap = columnMap
}
/**
A method for adding mapping information to a persistenceMap instance, used internally by DBBBuilder.
*/
func appendDictionary(_ dictToAppend: [String : DBBPropertyPersistence], indexer: DBBIndexer? = nil) -> DBBPersistenceMap {
var newMap = self.map
var columnMap = self.propertyColumnMap
for item in dictToAppend {
let key = item.key
if let _ = map[key] {
os_log("Already have an item with the key: %@", log: logger, type: defaultLogType, key)
continue
}
newMap[key] = item.value
if item.value.columnName.isEmpty == false {
columnMap[item.value.columnName] = key
} else {
columnMap[key] = item.key
}
}
return DBBPersistenceMap(newMap, columnMap: columnMap, indexer: indexer)
}
// MARK: - Helpers
func propertyForColumn(named column: String) -> String? {
return propertyColumnMap[column]
}
func columnNameForProperty(_ property: String) -> String? {
return propertyColumnMap.first(where: {$0.value == property})?.key
}
}
| 33.90625 | 191 | 0.636866 |
f728d0f171ec9b90bd0c239eb511cb50e0c8afac | 1,325 | //
// TileMapTests.swift
// TileMapTests
//
// Created by Andrew Molloy on 7/30/15.
// Copyright © 2015 Andrew Molloy. All rights reserved.
//
import XCTest
@testable import TileMap
class TileMapTests: XCTestCase
{
var testMapPath : String
{
get
{
let bundle = NSBundle(forClass: TileMapTests.self)
let testMapPath = bundle.pathForResource("Test", ofType: "fmp")
return testMapPath ?? ""
}
}
func testLoadHeader()
{
guard let tileMapFile = TileMap(path: testMapPath) else
{
XCTFail()
return
}
do
{
try tileMapFile.open()
}
catch let e
{
XCTFail("tileMapFile.load() threw \(e)")
}
}
func testLoadChunks()
{
guard let tileMapFile = TileMap(path: testMapPath) else
{
XCTFail()
return
}
do
{
try tileMapFile.open()
}
catch let e
{
XCTFail("tileMapFile.open() threw \(e)")
}
do
{
try tileMapFile.loadChunks()
}
catch let e
{
XCTFail("tileMapFile.loadChunks() threw \(e)")
}
XCTAssertNotNil(tileMapFile.animationData)
XCTAssertNotNil(tileMapFile.author)
XCTAssertNotNil(tileMapFile.blockData)
XCTAssertNotNil(tileMapFile.blockGraphics)
XCTAssertNotNil(tileMapFile.colorMap)
XCTAssertNotNil(tileMapFile.editorInfo)
XCTAssertNotNil(tileMapFile.mapHeader)
XCTAssertNotEqual(tileMapFile.layers.count, 0)
}
}
| 17.666667 | 66 | 0.689057 |
e690fb041fbc6e2fb7ebaeb9cecd1fc343c76ba1 | 435 | //
// GMLAttributedStringExtension.swift
// MyDrawingBoard
//
// Created by apple on 2020/6/2.
// Copyright © 2020 GML. All rights reserved.
//
import Foundation
public extension NSAttributedString {
var ml_allRange: NSRange {
return NSRange(location: 0, length: self.length)
}
var ml_lastLocation: Int? {
if self.length == 0 {
return nil
}
return self.length - 1
}
}
| 18.913043 | 56 | 0.62069 |
ac86453359a62997e1dc6bcb349beaa1d599f1cd | 2,130 | //
// AppDelegate.swift
// iOSHelloWorld
//
// Created by Madhuri Gummalla on 9/12/17.
//
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: 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:.
}
}
| 45.319149 | 285 | 0.755399 |
d5e5f076c9821a2643846e5d6b1b55e924c74b37 | 1,179 | // swift-tools-version:5.2
import PackageDescription
let package = Package(
// A server-side Swift Lambda Client for Vapor
name: "vapor-lambda-client",
platforms: [
.macOS(.v10_15),
],
products: [
.library(name: "VaporLambdaClient", targets: ["VaporLambdaClient"]),
],
dependencies: [
// 💧 A server-side Swift web framework.
.package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
// 📦 A server-side AWS Swift SDK
.package(name: "AWSSDKSwift", url: "https://github.com/swift-aws/aws-sdk-swift.git", from: "4.0.0"),
],
targets: [
.target(name: "App", dependencies: [
"VaporLambdaClient",
.product(name: "Vapor", package: "vapor"),
]),
.target(name: "VaporLambdaClient", dependencies: [
.product(name: "Lambda", package: "AWSSDKSwift"),
.product(name: "Vapor", package: "vapor"),
]),
.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: [
.target(name: "App"),
.product(name: "XCTVapor", package: "vapor"),
]),
]
)
| 32.75 | 108 | 0.556404 |
eb8b0b841d6c42a3b4b615c17ed91ab0c10e7c98 | 408 | //
// AudioReply.swift
// Aimybox
//
// Created by Vladyslav Popovych on 07.12.2019.
//
import Foundation
/**
Represents a reply with audio content, which should be played.
*/
public protocol AudioReply: Reply {
/**
URL to the audio source.
*/
var url: URL { get }
}
public extension AudioReply {
var audioSpeech: AudioSpeech {
AudioSpeech(audioURL: url)
}
}
| 14.571429 | 63 | 0.629902 |
18fb5dec577a38c8f7c9e08317421eedb01c7970 | 722 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
import Foundation
final class UnlikeReplyOperation: ReplyCommandOperation {
private let likesService: LikesServiceProtocol
init(command: ReplyCommand, likesService: LikesServiceProtocol) {
self.likesService = likesService
super.init(command: command)
}
override func main() {
guard !isCancelled else {
return
}
likesService.unlikeReply(replyHandle: command.reply.replyHandle) { [weak self] _, error in
self?.completeOperation(with: error)
}
}
}
| 26.740741 | 98 | 0.66482 |
e65a327cf1ef895e2387068b4d93a31bdff3190f | 341 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
(t: T
"[]() {
protocol A : a {
public class func e: a
}
}
return d>)
class a<d where S.h : A> String {
a() {
protoc
| 18.944444 | 87 | 0.680352 |
23a290718293e267e729db8964a47ea4d562de39 | 248 | import Foundation
import TSCBasic
@testable import TuistGraph
public extension AnalyzeAction {
static func test(configurationName: String = "Beta Release") -> AnalyzeAction {
AnalyzeAction(configurationName: configurationName)
}
}
| 24.8 | 83 | 0.766129 |
cc270e87efa67c79e3b1350c2b0c72f569c722cd | 848 |
//
// FirstController.swift
// MyFish
//
// Created by cheny on 2017/7/31.
// Copyright © 2017年 LHTW. All rights reserved.
//
import UIKit
class FirstController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 22.918919 | 106 | 0.665094 |
f427fd96a01b099d3f2717659e6a600ae52ff9bc | 4,978 | // Copyright © 2017 Schibsted. All rights reserved.
import XCTest
@testable import Layout
class RuntimeTypeTests: XCTestCase {
// MARK: Sanitized type names
func testSanitizeURLName() {
XCTAssertEqual(sanitizedTypeName("URL"), "url")
}
func testSanitizeURLRequestName() {
XCTAssertEqual(sanitizedTypeName("URLRequest"), "urlRequest")
}
func testSanitizeStringName() {
XCTAssertEqual(sanitizedTypeName("String"), "string")
}
func testSanitizeAttributedStringName() {
XCTAssertEqual(sanitizedTypeName("NSAttributedString"), "nsAttributedString")
}
func testSanitizeUINavigationItem_LargeTitleDisplayModeName() {
XCTAssertEqual(sanitizedTypeName("UINavigationItem.LargeTitleDisplayMode"), "uiNavigationItem_LargeTitleDisplayMode")
}
func testSanitizeEmptyName() {
XCTAssertEqual(sanitizedTypeName(""), "")
}
// MARK: Type classification
func testProtocolType() {
let runtimeType = RuntimeType(UITableViewDelegate.self)
guard case .protocol = runtimeType.type else {
XCTFail()
return
}
}
func testDynamicProtocolType() {
let type: Any.Type = UITableViewDelegate.self
let runtimeType = RuntimeType(type)
guard case .protocol = runtimeType.type else {
XCTFail()
return
}
}
func testArrayType() {
let runtimeType = RuntimeType([Int].self)
guard case .array = runtimeType.type else {
XCTFail()
return
}
}
func testDynamicArrayType() {
let type: Any.Type = [Int].self
let runtimeType = RuntimeType(type)
guard case .array = runtimeType.type else {
XCTFail()
return
}
}
func testArrayTypeByName() {
guard let runtimeType = RuntimeType.type(named: "Array<Int>") else {
XCTFail()
return
}
guard case let .array(subtype) = runtimeType.type else {
XCTFail()
return
}
XCTAssertEqual(subtype, .int)
}
func testArrayTypeByShortName() {
guard let runtimeType = RuntimeType.type(named: "[Int]") else {
XCTFail()
return
}
guard case let .array(subtype) = runtimeType.type else {
XCTFail()
return
}
XCTAssertEqual(subtype, .int)
}
func testNSArrayTypeByName() {
guard let runtimeType = RuntimeType.type(named: "NSArray") else {
XCTFail()
return
}
guard case .array = runtimeType.type else {
XCTFail()
return
}
}
// MARK: Type casting
func testCastProtocol() {
let runtimeType = RuntimeType(UITableViewDelegate.self)
XCTAssertNil(runtimeType.cast(NSObject()))
XCTAssertNil(runtimeType.cast(UITableViewDelegate.self))
XCTAssertNotNil(runtimeType.cast(UITableViewController()))
}
func testCastNSArray() {
let runtimeType = RuntimeType(NSArray.self)
XCTAssertNotNil(runtimeType.cast(NSObject())) // Anything can be array-ified
XCTAssertNotNil(runtimeType.cast(["foo"]))
XCTAssertNotNil(runtimeType.cast([5, "foo"]))
XCTAssertNotNil(runtimeType.cast([5]))
XCTAssertNotNil(runtimeType.cast(NSArray()))
XCTAssertNotNil(runtimeType.cast([(1, 2, 3)]))
}
func testCastDoesntCopyNSArray() {
let runtimeType = RuntimeType(NSArray.self)
let array = NSArray(array: [1, 2, 3, "foo", "bar", "baz"])
XCTAssertTrue(runtimeType.cast(array) as? NSArray === array)
}
func testCastIntArray() {
let runtimeType = RuntimeType([Int].self)
XCTAssertNil(runtimeType.cast(NSObject()))
XCTAssertNil(runtimeType.cast(["foo"]))
XCTAssertNil(runtimeType.cast([5, "foo"]))
XCTAssertNil(runtimeType.cast([[5]])) // Nested arrays are not flattened
XCTAssertNotNil(runtimeType.cast([5]))
XCTAssertNotNil(runtimeType.cast([5.0]))
XCTAssertNotNil(runtimeType.cast(NSArray()))
XCTAssertNotNil(runtimeType.cast([String]()))
XCTAssertEqual(runtimeType.cast(5) as! [Int], [5]) // Stringified and array-ified
}
func testCastStringArray() {
let runtimeType = RuntimeType([String].self)
XCTAssertNotNil(runtimeType.cast(["foo"]))
XCTAssertEqual(runtimeType.cast([5]) as! [String], ["5"]) // Anything can be stringified
XCTAssertEqual(runtimeType.cast("foo") as! [String], ["foo"]) // Is array-ified
XCTAssertEqual(runtimeType.cast(5) as! [String], ["5"]) // Stringified and array-ified
}
func testCastArrayArray() {
let runtimeType = RuntimeType([[Int]].self)
XCTAssertNotNil(runtimeType.cast([[5]]))
XCTAssertNotNil(runtimeType.cast([5]) as? [[Int]]) // Inner values is array-ified
}
}
| 31.707006 | 125 | 0.619325 |
678a67219e57ed47b3ceb88f1c4908bc5b95acd2 | 5,696 | import UIKit
@objc public protocol TextFieldFormHandlerDelegate {
@objc optional func textFieldFormHandlerDoneEnteringData(handler: TextFieldFormHandler)
}
public class TextFieldFormHandler: NSObject {
var textFields: [UITextField]!
var keyboardSize: CGFloat = 0
var animationOffset: CGFloat = 0
var topContainer: UIView!
var _lastTextField: UITextField?
var lastTextField: UITextField? {
get {
return _lastTextField
}
set (newValue){
if let textField = _lastTextField {
setTextField(textField: textField, returnKeyType: .next)
}
_lastTextField = newValue
if let textField = newValue {
setTextField(textField: textField, returnKeyType: .done)
}
else if let textField = textFields.last {
setTextField(textField: textField, returnKeyType: .done)
}
}
}
public weak var delegate: TextFieldFormHandlerDelegate?
public var firstResponderIndex: Int? {
if let firstResponder = self.firstResponder {
return self.textFields.index(of: firstResponder)
}
return nil
}
public var firstResponder: UITextField? {
return self.textFields.filter { textField in textField.isFirstResponder }.first
}
// MARK: - Initialization
init(withTextFields textFields: [UITextField], topContainer: UIView) {
super.init()
self.textFields = textFields
self.topContainer = topContainer
initializeTextFields()
initializeObservers()
}
func initializeTextFields() {
for (index, textField) in self.textFields.enumerated() {
textField.delegate = self
setTextField(textField: textField, returnKeyType: (index == self.textFields.count - 1 ? .done : .next))
}
}
func initializeObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(TextFieldFormHandler.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(TextFieldFormHandler.backgroundTap(sender:)))
self.topContainer.addGestureRecognizer(tapRecognizer)
}
// MARK: - Public Methods
public func resetScroll() {
if let firstResponder = self.firstResponder {
setAnimationOffsetForTextField(textField: firstResponder)
moveScreenUp()
}
}
public func setTextFieldAtIndexAsFirstResponder(index:Int) {
textFields[index].becomeFirstResponder()
}
public func cleanUp() {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Private Methods
func doneEnteringData() {
topContainer.endEditing(true)
moveScreenDown()
delegate?.textFieldFormHandlerDoneEnteringData?(handler: self)
}
func moveScreenUp() {
shiftScreenYPosition(position: -keyboardSize - animationOffset, duration: 0.3, curve: .easeInOut)
}
func moveScreenDown() {
shiftScreenYPosition(position: 0, duration: 0.2, curve: .easeInOut)
}
func shiftScreenYPosition(position: CGFloat, duration: TimeInterval, curve: UIView.AnimationCurve) {
UIView.beginAnimations("moveView", context: nil)
UIView.setAnimationCurve(curve)
UIView.setAnimationDuration(duration)
topContainer.frame.origin.y = position
UIView.commitAnimations()
}
@objc func backgroundTap(sender: UITapGestureRecognizer) {
topContainer.endEditing(true)
moveScreenDown()
}
@objc func keyboardWillShow(notification: NSNotification) {
if (keyboardSize == 0) {
if let keyboardRect = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
keyboardSize = min(keyboardRect.height, keyboardRect.width)
}
}
moveScreenUp()
}
func setAnimationOffsetForTextField(textField: UITextField) {
let screenHeight = UIScreen.main.bounds.size.height
let textFieldHeight = textField.frame.size.height
let textFieldY = textField.convert(CGPoint.zero, to: topContainer).y
animationOffset = -screenHeight + textFieldY + textFieldHeight
}
func setTextField(textField: UITextField, returnKeyType type: UIReturnKeyType) {
if (textField.isFirstResponder) {
textField.resignFirstResponder()
textField.returnKeyType = type
textField.becomeFirstResponder()
}
else {
textField.returnKeyType = type
}
}
deinit {
cleanUp()
}
}
extension TextFieldFormHandler : UITextFieldDelegate {
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let lastTextField = self.lastTextField, textField == lastTextField {
doneEnteringData()
return true
}
else if let lastTextField = self.textFields.last, lastTextField == textField {
doneEnteringData()
return true
}
let index = self.textFields.index(of: textField)
let nextTextField = self.textFields[index! + 1]
nextTextField.becomeFirstResponder()
return true
}
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
setAnimationOffsetForTextField(textField: textField)
return true
}
}
| 32.735632 | 187 | 0.642205 |
8a2adde0f44d5bb81323228b6f69a4e69686ce89 | 2,086 | //
// AppDelegate.swift
// Project1
//
// Created by TwoStraws on 11/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> 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:.
}
}
| 44.382979 | 279 | 0.788111 |
14decbf32358a2c6b7cd06c5364755f08be42099 | 813 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swack open source project
//
// Copyright (c) 2018 e-Sixt
// Licensed under MIT
//
// See LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import Vapor
class AuthService {
private let client: Client
private let token: String
init(client: Client, token: String) {
self.client = client
self.token = token
}
func test() -> Future<AuthTestResponse> {
return client.post("https://slack.com/api/auth.test", headers: HTTPHeaders([("Authorization", "Bearer \(token)")])).flatMap { response in
return try response.content.decode(AuthTestResponse.self)
}
}
}
| 26.225806 | 145 | 0.519065 |
e4611884e98a3d5760a4b1bb59f8e1440ea5723d | 499 | public struct SafariPasswordGenerator: RandomStringGenerator {
public let usableCharacters: UsableCharacters = .alphanumeric
public let length: Int = 12
public var count: Int
public init(count: Int = 1) {
self.count = count
}
public func generate() -> [String] {
let generator = PseudoRandomPasswordGenerator(length: 3, usableCharacters: usableCharacters, count: length / 3)
return (0 ..< count).map { _ in
generator.generate().joined(separator: "-")
}
}
}
| 29.352941 | 115 | 0.691383 |
693e8760d397781d4d2265e2cadddf1e913e4b0d | 184 | //
// Optional+Extensions.swift
//
//
// Created by Yuhan Chen on 2022/02/23.
//
extension Optional where Wrapped == String {
var orEmpty: String {
self ?? ""
}
}
| 14.153846 | 44 | 0.576087 |
eb2c545b9bcdd56c7ce3cba5bd76b891c6478ede | 2,990 | //
// AppDelegate.swift
// AcnSDKSample
//
// Copyright (c) 2017 Arrow Electronics, Inc.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Apache License 2.0
// which accompanies this distribution, and is available at
// http://apache.org/licenses/LICENSE-2.0
//
// Contributors: Arrow Electronics, Inc.
//
import UIKit
import AcnSDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
IotConnectService.sharedInstance.setupConnection(http: Connection.IoTConnectUrl,
mqtt: Connection.MQTTServerHost,
mqttPort: Connection.MQTTServerPort,
mqttVHost: Connection.MQTTVHost)
IotConnectService.sharedInstance.setKeys(apiKey: Constants.Keys.DefaultApiKey,
secretKey: Constants.Keys.DefaultSecretKey)
IotDataPublisher.sharedInstance.start()
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:.
}
}
| 47.460317 | 285 | 0.698328 |
de327613b30cef8c3c3aa222261a055758644615 | 2,181 | //
// AppDelegate.swift
// Yelp
//
// Created by Timothy Lee on 9/19/14.
// Copyright (c) 2017 Timothy Lee, Nghia Nguyen. 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 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:.
}
}
| 46.404255 | 285 | 0.753324 |
ed6d3979fb8c1892d6f58a4a1e751589a42146ad | 5,189 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 AVFoundation
import Foundation
import UIKit
public struct LiveCameraCellAppearance {
public var backgroundColor: UIColor
public var cameraImageProvider: () -> UIImage?
public var cameraLockImageProvider: () -> UIImage?
public let accessibilityIdentifier = "chatto.inputbar.photos.cell.livecamera"
public init(backgroundColor: UIColor,
cameraImage: @autoclosure @escaping () -> UIImage?,
cameraLockImage: @autoclosure @escaping () -> UIImage?) {
self.backgroundColor = backgroundColor
self.cameraImageProvider = cameraImage
self.cameraLockImageProvider = cameraLockImage
}
public static func createDefaultAppearance() -> LiveCameraCellAppearance {
return LiveCameraCellAppearance(
backgroundColor: UIColor(red: 24.0/255.0, green: 101.0/255.0, blue: 245.0/255.0, alpha: 1),
cameraImage: UIImage(named: "camera", in: Bundle(for: LiveCameraCell.self), compatibleWith: nil),
cameraLockImage: UIImage(named: "camera_lock", in: Bundle(for: LiveCameraCell.self), compatibleWith: nil)
)
}
}
class LiveCameraCell: UICollectionViewCell {
private var iconImageView: UIImageView!
var appearance: LiveCameraCellAppearance = LiveCameraCellAppearance.createDefaultAppearance() {
didSet {
self.updateAppearance()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
self.configureIcon()
self.contentView.backgroundColor = self.appearance.backgroundColor
}
var captureLayer: CALayer? {
didSet {
if oldValue !== self.captureLayer {
oldValue?.removeFromSuperlayer()
if let captureLayer = self.captureLayer {
self.contentView.layer.insertSublayer(captureLayer, below: self.iconImageView.layer)
let animation = CABasicAnimation.bma_fadeInAnimationWithDuration(0.25)
let animationKey = "fadeIn"
captureLayer.removeAnimation(forKey: animationKey)
captureLayer.add(animation, forKey: animationKey)
}
self.setNeedsLayout()
}
}
}
typealias CellCallback = (_ cell: LiveCameraCell) -> Void
var onWasAddedToWindow: CellCallback?
var onWasRemovedFromWindow: CellCallback?
override func didMoveToWindow() {
if self.window != nil {
self.onWasAddedToWindow?(self)
} else {
self.onWasRemovedFromWindow?(self)
}
}
func updateWithAuthorizationStatus(_ status: AVAuthorizationStatus) {
self.authorizationStatus = status
self.updateIcon()
}
private var authorizationStatus: AVAuthorizationStatus = .notDetermined
private func configureIcon() {
self.iconImageView = UIImageView()
self.iconImageView.contentMode = .center
self.contentView.addSubview(self.iconImageView)
}
private func updateAppearance() {
self.contentView.backgroundColor = self.appearance.backgroundColor
self.accessibilityIdentifier = self.appearance.accessibilityIdentifier
self.updateIcon()
}
private func updateIcon() {
switch self.authorizationStatus {
case .notDetermined, .authorized:
self.iconImageView.image = self.appearance.cameraImageProvider()
case .restricted, .denied:
self.iconImageView.image = self.appearance.cameraLockImageProvider()
@unknown default:
fatalError()
}
self.setNeedsLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
self.captureLayer?.frame = self.contentView.bounds
self.iconImageView.sizeToFit()
self.iconImageView.center = self.contentView.bounds.bma_center
}
}
| 36.286713 | 117 | 0.682983 |
e00e4698dc780fcde124cd0c88e5148befb8297a | 741 | //
// RemoteFetchShowByIdUseCase.swift
// TVMazeApp
//
// Created by marcos.brito on 03/09/21.
//
import Foundation
import Combine
public class RemoteFetchShowByIdUseCase: FetchShowByIdUseCase {
private let httpClient: HTTPClient
public init(httpClient: HTTPClient) {
self.httpClient = httpClient
}
public func execute(id: Int) -> AnyPublisher<Show, DomainError> {
guard let urlRequest = ShowByIdRequest(id: id).asURLRequest() else {
return Fail(outputType: Show.self, failure: DomainError.unknown).eraseToAnyPublisher()
}
return httpClient.dispatch(request: urlRequest).mapError { _ -> DomainError in
return .fetchError
}.eraseToAnyPublisher()
}
}
| 26.464286 | 98 | 0.688259 |
3987556bef16bad110af7733f9aa408d65589431 | 528 | //
// SecondTutorialFilterView.swift
// SwiftUI_Mask_Sample
//
// Created by Tsuruta, Hiromu | ECID on 2021/09/21.
//
import SwiftUI
// MARK: - View
struct SecondTutorialFilterView: View {
var body: some View {
Color.black
.opacity(0.7)
.mask(SecondTutorialHoleView())
.edgesIgnoringSafeArea(.all)
}
}
// MARK: - PreviewProvider
struct SecondTutorialFilterView_Previews: PreviewProvider {
static var previews: some View {
SecondTutorialFilterView()
}
}
| 19.555556 | 59 | 0.653409 |
f4a6d2a2c9fb25d04bfa719995e2a9245b71d574 | 146 | import ProjectDescription
import ProjectDescriptionHelpers
// MARK: - Project
let project = Project.app(name: "AddExtraDataMessageOpenChannel")
| 20.857143 | 65 | 0.821918 |
33dc9487336c10af4eb2af082ee9e52c2cd5acae | 1,493 | //
// BusinessCell.swift
// Yelp
//
// Created by mac on 2/24/17.
// Copyright © 2017 CoderSchool. All rights reserved.
//
import UIKit
import AFNetworking
class BusinessCell: UITableViewCell {
@IBOutlet weak var businessImageView: UIImageView!
@IBOutlet weak var businessNameLabel: UILabel!
@IBOutlet weak var businessdDistanceLabel: UILabel!
@IBOutlet weak var businessReviewCountLabel: UILabel!
@IBOutlet weak var businessReviewImageView: UIImageView!
@IBOutlet weak var businessAddressLabel: UILabel!
@IBOutlet weak var businessCategoryLabel: 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
}
func loadDataFromModel(_ business: Business) {
if let imageUrl = business.imageURL {
businessImageView.setImageWith(imageUrl)
}
if let ratingImageUrl = business.ratingImageURL {
businessReviewImageView.setImageWith(ratingImageUrl)
}
businessNameLabel.text = business.name
businessdDistanceLabel.text = business.distance
businessReviewCountLabel.text = "\(business.reviewCount!) reviews"
businessAddressLabel.text = business.address
businessCategoryLabel.text = business.categories
}
}
| 29.86 | 74 | 0.693235 |
4a1834f7c557b8395d35cb9b8776ea4f91a2372d | 2,167 | // MIT License
//
// Copyright (c) 2017-present qazyn951230 [email protected]
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
private final class AutoconnectPipe<Downstream>: UpstreamPipe where Downstream: Subscriber {
typealias Input = Downstream.Input
typealias Failure = Downstream.Failure
var stop = false
let downstream: Downstream
var upstream: Subscription?
init(_ downstream: Downstream) {
self.downstream = downstream
}
var description: String {
return "Autoconnect"
}
}
public extension Publishers {
// TODO: Remove final
final class Autoconnect<Upstream>: Publisher where Upstream: ConnectablePublisher {
public typealias Output = Upstream.Output
public typealias Failure = Upstream.Failure
public final let upstream: Upstream
public init(_ upstream: Upstream) {
self.upstream = upstream
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
let pipe = AutoconnectPipe(subscriber)
upstream.subscribe(pipe)
}
}
}
| 37.362069 | 108 | 0.718505 |
bf52e4eb4088e7e4faca77d6f89b49d3270f9960 | 3,411 | //
// FormVCRootView.swift
// SmartStaff
//
// Created by artem on 28.03.2020.
// Copyright © 2020 DIT. All rights reserved.
//
import UIKit
class FormVCRootView: UIView, ScrollViewWrapper {
// MARK: Dependencies
weak var controller: FormVC?
// MARK: Properties
let rootFormView = FormView()
let footer = ButtonCell()
private var _footerHeight: NSLayoutConstraint?
var footerHeight: CGFloat {
_footerHeight?.constant ?? 0
}
var scrollView: UIScrollView? {
rootFormView
}
// MARK: Initialization
override init(frame: CGRect) {
super.init(frame: frame)
configureUI()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configureUI()
}
// MARK: UI Configuration
private func configureUI() {
themeProvider.register(observer: self)
configureFormView()
configureFooter()
}
func configureFormView() {
addSubview(rootFormView)
rootFormView.anchor(top: safeAreaLayoutGuide.topAnchor,
left: safeAreaLayoutGuide.leftAnchor,
right: safeAreaLayoutGuide.rightAnchor)
rootFormView.didReload {[weak self] in
guard let self = self else { return }
self.controller?.viewDidReloadCollection(with: self.fullContentHeight())
}
}
func configureFooter() {
addSubview(footer)
footer.anchor(top: rootFormView.bottomAnchor,
left: safeAreaLayoutGuide.leftAnchor,
bottom: safeAreaLayoutGuide.bottomAnchor,
right: safeAreaLayoutGuide.rightAnchor)
_footerHeight = footer.anchorWithReturnAnchors(heightConstant: 44).first
}
// MARK: Controller's output
func display(_ sections: [FormSection]) {
if let emptySection = sections.first(where: { $0 is EmptySection }) as? EmptySection {
emptySection.height = footerHeight
}
rootFormView.sections = sections
}
func display(_ footerViewModel: ButtonCell.ViewModel?, animated: Bool) {
_footerHeight?.constant = footerViewModel == nil ? 0.5 : footer.sizeWith(bounds.size, data: footerViewModel)?.height ?? 0
footer.configure(with: footerViewModel)
if animated {
UIView.animate(withDuration: 0.3) {[weak self] in
guard let self = self else { return }
self.layoutIfNeeded()
}
} else {
layoutIfNeeded()
}
}
func fullContentHeight() -> CGFloat {
let height = ((controller?.navigationController?.navigationBar.isHidden ?? true)
? 0
: controller?.navigationController?.navigationBar.frame.height ?? 0) +
rootFormView.contentSize.height + footerHeight
return min(height, fullEdgesHeight)
}
func displayEmptyView(_ viewModel: EmptyView.ViewModel) {
rootFormView.displayEmptyView(model: viewModel, height: footerHeight)
self.controller?.viewDidReloadCollection(with: self.fullEdgesHeight)
}
}
// MARK: Themeable
extension FormVCRootView: Themeable {
func apply(theme: Theme) {
backgroundColor = theme.tableViewBackground
rootFormView.backgroundColor = theme.tableViewBackground
}
}
| 29.66087 | 130 | 0.620053 |
f4c29ba42967003722c74f0c58538b1c01e5d6fd | 5,418 | //
// HomeCollectionViewCell.swift
// Alamofire
//
// Created by owen on 2018/7/16.
//
import UIKit
import Kingfisher
protocol HomeCollectionViewCellDelegate: class {
func homeCollectionViewCellMoreAction()
func homeCollectionViewCellGotoQRCodePage()
}
class HomeCollectionViewCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(titleLabel)
contentView.addSubview(moreBtn)
contentView.addSubview(subTitleLbl)
contentView.addSubview(accountNumLbl)
contentView.addSubview(unitLbl)
contentView.addSubview(walletNameLbl)
contentView.addSubview(walletCodeLbl)
contentView.addSubview(qrCodeBtn)
layoutViews()
layerMask.frame = contentView.bounds
contentView.layer.insertSublayer(layerMask, at: 0)
contentView.layer.cornerRadius = 3
contentView.clipsToBounds = true
layer.shadowOpacity = 0.3
layer.shadowOffset = CGSize(width: 0, height: 5)
moreBtn.addTarget(self, action: #selector(moreAction), for: .touchUpInside)
qrCodeBtn.addTarget(self, action: #selector(gotoQRCodePage), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func layoutViews() {
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(20)
make.top.equalTo(14)
}
moreBtn.snp.makeConstraints { (make) in
make.top.right.equalTo(0)
make.width.height.equalTo(44)
}
subTitleLbl.snp.makeConstraints { (make) in
make.left.equalTo(titleLabel)
make.top.equalTo(titleLabel.snp.bottom).offset(6)
}
accountNumLbl.snp.makeConstraints { (make) in
make.top.equalTo(subTitleLbl.snp.bottom).offset(5)
make.left.equalTo(titleLabel)
}
unitLbl.snp.makeConstraints { (make) in
make.left.equalTo(accountNumLbl.snp.right).offset(5)
make.bottom.equalTo(accountNumLbl).offset(-4)
make.right.lessThanOrEqualTo(-20)
}
walletNameLbl.snp.makeConstraints { (make) in
make.left.equalTo(titleLabel)
make.top.equalTo(accountNumLbl.snp.bottom).offset(8)
}
walletCodeLbl.snp.makeConstraints { (make) in
make.left.equalTo(titleLabel)
make.width.lessThanOrEqualTo(140)
make.top.equalTo(walletNameLbl.snp.bottom).offset(3)
}
qrCodeBtn.snp.makeConstraints { (make) in
make.centerY.equalTo(walletCodeLbl)
make.width.height.equalTo(44)
make.left.equalTo(walletCodeLbl.snp.right).offset(-8)
}
}
func configData(title: String, subTitle: String, accountNum: String, unitStr: String, walletName: String, walletCode: String, showMoreBtn: Bool, showQRCodeBtn: Bool, gradientColors: [CGColor]) {
titleLabel.text = title
subTitleLbl.text = subTitle
accountNumLbl.text = accountNum
unitLbl.text = unitStr
walletNameLbl.text = walletName
walletCodeLbl.text = walletCode
moreBtn.isHidden = !showMoreBtn
qrCodeBtn.isHidden = !showQRCodeBtn
layerMask.colors = gradientColors
layer.shadowColor = gradientColors.first
}
// MARK: - event response
@objc func moreAction() {
delegate?.homeCollectionViewCellMoreAction()
}
@objc func gotoQRCodePage() {
delegate?.homeCollectionViewCellGotoQRCodePage()
}
// MARK: - getter and setter
weak var delegate: HomeCollectionViewCellDelegate?
let titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.textColor = .white
titleLabel.font = UIFont.systemFont(ofSize: 17)
return titleLabel
}()
let moreBtn: UIButton = {
let button = UIButton()
button.setImage(#imageLiteral(resourceName: "home_more_icon"), for: .normal)
return button
}()
let subTitleLbl: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 13)
label.textColor = .white
return label
}()
let accountNumLbl: UILabel = {
let label = UILabel()
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 28)
return label
}()
let unitLbl: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 18)
label.textColor = .white
return label
}()
let walletNameLbl: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 11)
label.textColor = .white
label.alpha = 0.9
return label
}()
let walletCodeLbl: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 11)
label.textColor = .white
label.alpha = 0.9
label.lineBreakMode = .byTruncatingMiddle
return label
}()
let qrCodeBtn: UIButton = {
let button = UIButton()
button.setImage(#imageLiteral(resourceName: "home_qrcode_icon"), for: .normal)
return button
}()
let layerMask: CAGradientLayer = {
let layer = CAGradientLayer()
layer.startPoint = CGPoint(x: 0.5, y: 0.5)
layer.endPoint = CGPoint(x: 1, y: 0.5)
return layer
}()
}
| 34.075472 | 198 | 0.63086 |
ef998a16d30da1252bebe2148a7f612a0e22c5fe | 5,406 | import AppKit
import Core
final class Bar: NSVisualEffectView {
private(set) weak var edit: Control!
private(set) weak var style: Control!
private(set) weak var preview: Control!
private(set) weak var share: Control!
required init?(coder: NSCoder) { nil }
init(website: Website) {
super.init(frame: .zero)
wantsLayer = true
translatesAutoresizingMaskIntoConstraints = false
material = .sidebar
let icon = NSImageView(image: NSImage(named: website.icon)!)
icon.contentTintColor = .systemIndigo
icon.translatesAutoresizingMaskIntoConstraints = false
icon.imageScaling = .scaleProportionallyDown
addSubview(icon)
let title = Label(website.model.name, .bold())
title.alignment = .center
title.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
addSubview(title)
let edit = Item(icon: "hammer", title: .key("Edit"))
addSubview(edit)
self.edit = edit
let style = Item(icon: "paintbrush", title: .key("Style"))
addSubview(style)
self.style = style
let preview = Item(icon: "paperplane", title: .key("Preview"))
addSubview(preview)
self.preview = preview
let share = Item(icon: "square.and.arrow.up", title: .key("Share"))
addSubview(share)
self.share = share
widthAnchor.constraint(equalToConstant: 180).isActive = true
icon.topAnchor.constraint(equalTo: topAnchor, constant: 60).isActive = true
icon.centerXAnchor.constraint(equalTo: centerXAnchor, constant: -5).isActive = true
icon.widthAnchor.constraint(equalToConstant: 30).isActive = true
icon.heightAnchor.constraint(equalToConstant: 30).isActive = true
title.topAnchor.constraint(equalTo: icon.bottomAnchor, constant: 20).isActive = true
title.centerXAnchor.constraint(equalTo: centerXAnchor, constant: -5).isActive = true
title.leftAnchor.constraint(greaterThanOrEqualTo: leftAnchor, constant: 20).isActive = true
title.rightAnchor.constraint(lessThanOrEqualTo: rightAnchor, constant: -20).isActive = true
edit.bottomAnchor.constraint(equalTo: style.topAnchor, constant: -20).isActive = true
edit.leftAnchor.constraint(equalTo: preview.leftAnchor).isActive = true
edit.rightAnchor.constraint(equalTo: preview.rightAnchor).isActive = true
style.bottomAnchor.constraint(equalTo: preview.topAnchor, constant: -20).isActive = true
style.leftAnchor.constraint(equalTo: preview.leftAnchor).isActive = true
style.rightAnchor.constraint(equalTo: preview.rightAnchor).isActive = true
preview.bottomAnchor.constraint(equalTo: share.topAnchor, constant: -20).isActive = true
preview.leftAnchor.constraint(equalTo: leftAnchor, constant: 20).isActive = true
preview.rightAnchor.constraint(equalTo: rightAnchor, constant: -25).isActive = true
share.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -30).isActive = true
share.leftAnchor.constraint(equalTo: leftAnchor, constant: 20).isActive = true
share.rightAnchor.constraint(equalTo: rightAnchor, constant: -25).isActive = true
}
func select(control: Control) {
subviews.compactMap { $0 as? Item }.forEach {
$0.enabled = $0 != control
}
}
}
private final class Item: Control {
override var enabled: Bool {
didSet {
if enabled {
hoverOff()
} else {
hoverOn()
}
}
}
private weak var icon: NSImageView!
private weak var label: Label!
private weak var blur: NSVisualEffectView!
required init?(coder: NSCoder) { nil }
init(icon: String, title: String) {
super.init()
wantsLayer = true
layer!.cornerRadius = 6
let icon = NSImageView(image: NSImage(named: icon)!)
icon.translatesAutoresizingMaskIntoConstraints = false
icon.imageScaling = .scaleNone
addSubview(icon)
self.icon = icon
let label = Label(title, .medium())
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
addSubview(label)
self.label = label
bottomAnchor.constraint(equalTo: label.bottomAnchor, constant: 8).isActive = true
icon.leftAnchor.constraint(equalTo: leftAnchor, constant: 11).isActive = true
icon.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
label.leftAnchor.constraint(equalTo: icon.rightAnchor, constant: 5).isActive = true
label.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
label.rightAnchor.constraint(lessThanOrEqualTo: rightAnchor, constant: -11).isActive = true
hoverOff()
}
override func hoverOn() {
label.textColor = .controlBackgroundColor
icon.contentTintColor = .controlBackgroundColor
layer!.backgroundColor = NSColor.labelColor.cgColor
}
override func hoverOff() {
label.textColor = .labelColor
icon.contentTintColor = .secondaryLabelColor
layer!.backgroundColor = .clear
}
}
| 40.044444 | 99 | 0.651683 |
b98dfcbfaadb3870b3ba00711b26cfed28c3c3d7 | 3,339 | //
// BeerChipViewController.swift
// BeerChipFrameWork
//
// Created by Vmoksha on 06/02/18.
// Copyright © 2018 Srinivas. All rights reserved.
//
import UIKit
public class BeerChipViewController: UIViewController {
var beerchipFrameWorkVC = UIViewController()
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
public func openBeerChipFrameWork(viewController: UIViewController , withLocation:CGRect){
beerchipFrameWorkVC = viewController
let location:CGRect = withLocation
let mainView = UIView(frame:CGRect(x: location.origin.x , y: location.origin.y, width: UIScreen.main.bounds.width-20 , height: location.size.height))
mainView.backgroundColor = UIColor(red: 0.0 ,green: 94.0/255.0, blue: 163.0/255.0, alpha:1.0 )
viewController.view.addSubview(mainView)
// let webViewButton = UIButton(frame: CGRect(x: 15 ,y: 7, width: 150, height: 26))
let webViewButton = UIButton()
let buttonHeight = location.size.height * 0.75
webViewButton.frame = CGRect(x:15 ,y: ((mainView.center.y-location.origin.y)-(buttonHeight/2)), width: 150, height: buttonHeight )
webViewButton.setTitle("Open WebView", for: .normal)
webViewButton.backgroundColor = .white
webViewButton.setTitleColor(UIColor(red: 0.0 ,green: 94.0/255.0, blue: 163.0/255.0, alpha:1.0 ), for: .normal)
webViewButton.layer.cornerRadius = 8.0
webViewButton.addTarget(self, action: #selector(gotoWebView), for: .touchUpInside)
mainView.addSubview(webViewButton)
// let alertButton = UIButton(frame: CGRect(x: 185 ,y: 7, width: 150, height: 26))
let alertButton = UIButton( )
alertButton.frame = CGRect(x:185 ,y: ((mainView.center.y-location.origin.y)-(buttonHeight/2)), width: 150, height: buttonHeight )
alertButton.setTitle("Click Here", for: .normal)
alertButton.backgroundColor = .white
alertButton.setTitleColor(UIColor(red: 0.0 ,green: 94.0/255.0, blue: 163.0/255.0, alpha:1.0 ), for: .normal)
alertButton.layer.cornerRadius = 8.0
alertButton.addTarget(self, action: #selector(showTheAlertMessage), for: .touchUpInside)
mainView.addSubview(alertButton)
}
@objc func gotoWebView () {
let webVC = WebViewController()
beerchipFrameWorkVC.navigationController?.pushViewController(webVC , animated: true)
}
@objc func showTheAlertMessage() {
let alertController = UIAlertController(title: "Welcome..!" , message: "BeerChip has Claimed" , preferredStyle:UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title:"OK" , style:.default , handler:{ (action) in
alertController.dismiss(animated: true, completion: nil)
})
let cancelAction = UIAlertAction(title:"Cancel" , style:.destructive , handler:{(action) in
alertController.dismiss(animated: true, completion: nil)
})
alertController.addAction(cancelAction)
alertController.addAction(okAction)
beerchipFrameWorkVC.present(alertController, animated: true, completion: nil)
}
}
| 38.825581 | 157 | 0.659778 |
e980b36de99e365358bde721af7b1f30d26b259c | 4,896 | //
// ViewController.swift
// cicePractica2
//
// Created by MAC on 4/5/21.
//
import UIKit
import CoreServices
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var photoCollection: UICollectionView!
var imagePicked : UIImage = UIImage()
var ac : UIAlertController!
let viewModel = PhotoViewModel()
var newPhoto = PhotoModel()
override func viewDidLoad() {
super.viewDidLoad()
title = "Photo Manager"
ac = UIAlertController(title: "Nombre", message: nil, preferredStyle: .alert)
alert()
viewModel.getAllPhotos()
print("\(viewModel.photos.count)")
}
@IBAction func addPhotoTapped(_ sender: Any) {
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.mediaTypes = [kUTTypeMovie as String, kUTTypeImage as String]
picker.delegate = self
picker.allowsEditing = true
present(picker,animated: true,completion: nil)
}
func alert() {
self.ac.addTextField(configurationHandler: {(action) in
self.ac.textFields![0].delegate = self
})
self.ac.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: {(action) in
}))
ac.addAction(UIAlertAction(title: "Ok", style: .default, handler: {(action) in
if !self.ac.textFields![0].text!.isEmpty
{
if let text = self.ac.textFields?[0].text {
self.newPhoto.title = text
}
self.viewModel.addPhoto(image: self.newPhoto)
self.viewModel.getAllPhotos()
self.photoCollection.reloadData()
}
else{
self.ac.message = "Error"
}
}))
self.ac.actions[1].isEnabled = false
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
imagePicked = image
dismiss(animated: true, completion: nil) //Cierra cualquer ventana modal
let timestamp = NSDate().timeIntervalSince1970
let timestampString = String(format: "%.0f", timestamp)
let fileName = String(timestampString + ".jpg")
let completeFilePath = getDocsDirectory().appendingPathComponent(fileName)
print(completeFilePath)
if let jpegData = image.jpegData(compressionQuality: 0.8)
{
do {
try? jpegData.write(to: completeFilePath)
}
// catch {
// print("Error de escritura")
// }
}
newPhoto = PhotoModel(uid: 0, filename: fileName, title: "", description: "", tags: "")
print(fileName)
present(self.ac, animated: true, completion: nil)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let userEnteredString = textField.text
let newString = (userEnteredString! as NSString).replacingCharacters(in: range, with: string) as NSString
if newString != ""{
ac.actions[1].isEnabled = true
} else {
ac.actions[1].isEnabled = false
}
return true
}
func getDocsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
}
extension ViewController : UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
viewModel.photos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! PhotoCollectionViewCell
cell.title.text = viewModel.photos[indexPath.row].title
let imagePath = getDocsDirectory().appendingPathComponent(viewModel.photos[indexPath.row].filename)
cell.image.image = UIImage(contentsOfFile: imagePath.path)
return cell
}
}
| 30.409938 | 144 | 0.581291 |
16312528bdeb52446993b5367fa9415a5146cc3c | 1,235 | //
// LoginViewController.swift
// Twitter
//
// Created by Utkarsh Sengar on 4/13/17.
// Copyright © 2017 Area42. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
class LoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLoginButton(_ sender: Any) {
let twitter = TwitterClient.sharedInstance
twitter?.login(success: {
print("I have logged in!")
self.performSegue(withIdentifier: "loginSegue", sender: nil)
}, failure: { (error) in
print(error.localizedDescription)
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 26.847826 | 106 | 0.649393 |
5b4ca1da12c9d95df768b579eab0611095c9d235 | 13,034 | //
// EthViteExchangeViewController.swift
// ViteBusiness
//
// Created by Stone on 2019/4/24.
//
import UIKit
import web3swift
import BigInt
import PromiseKit
import ViteWallet
class EthViteExchangeViewController: BaseViewController {
let myEthAddress = ETHWalletManager.instance.account!.address
var balance = Amount(0)
override func viewDidLoad() {
super.viewDidLoad()
setupView()
bind()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
kas_activateAutoScrollingForView(scrollView)
ETHBalanceInfoManager.instance.registerFetch(tokenCodes: [TokenInfo.BuildIn.eth_vite.value.tokenCode])
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
let key = "tipShowed"
let collection = "EthViewExchange"
if let hasShowTip = UserDefaultsService.instance.objectForKey(key, inCollection: collection) as? Bool,
hasShowTip {
// do nothing
} else {
UserDefaultsService.instance.setObject(true, forKey: key, inCollection: collection)
DispatchQueue.main.async {
self.showTip()
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
ETHBalanceInfoManager.instance.unregisterFetch(tokenCodes: [TokenInfo.BuildIn.eth_vite.value.tokenCode])
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
}
// View
lazy var scrollView = ScrollableView(insets: UIEdgeInsets(top: 10, left: 24, bottom: 50, right: 24)).then {
$0.layer.masksToBounds = false
if #available(iOS 11.0, *) {
$0.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
}
// headerView
lazy var headerView = EthSendPageTokenInfoView(address: myEthAddress).then {
$0.addressTitleLabel.text = R.string.localizable.ethViteExchangePageMyAddressTitle()
}
let addressView = AddressTextViewView().then {
$0.textView.text = HDWalletManager.instance.account?.address ?? ""
}
let amountView = EthViteExchangeAmountView().then {
$0.textField.keyboardType = .decimalPad
}
let gasSliderView = EthGasFeeSliderView(gasLimit: TokenInfo.BuildIn.eth_vite.value.ethChainGasLimit).then {
$0.value = 1.0
}
let exchangeButton = UIButton(style: .blue, title: R.string.localizable.ethViteExchangePageSendButtonTitle())
func setupView() {
setupNavBar()
view.addSubview(scrollView)
view.addSubview(exchangeButton)
scrollView.snp.makeConstraints { (m) in
m.top.equalTo(navigationTitleView!.snp.bottom)
m.left.right.equalTo(view)
}
exchangeButton.snp.makeConstraints { (m) in
m.top.greaterThanOrEqualTo(scrollView.snp.bottom).offset(10)
m.left.equalTo(view).offset(24)
m.right.equalTo(view).offset(-24)
m.bottom.equalTo(view.safeAreaLayoutGuideSnpBottom).offset(-24)
m.height.equalTo(50)
}
scrollView.stackView.addArrangedSubview(headerView)
scrollView.stackView.addPlaceholder(height: 20)
scrollView.stackView.addArrangedSubview(addressView)
scrollView.stackView.addArrangedSubview(amountView)
scrollView.stackView.addPlaceholder(height: 21)
scrollView.stackView.addArrangedSubview(gasSliderView)
let toolbar = UIToolbar()
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: R.string.localizable.finish(), style: .done, target: nil, action: nil)
toolbar.items = [flexSpace, done]
toolbar.sizeToFit()
done.rx.tap.bind { [weak self] in self?.amountView.textField.resignFirstResponder() }.disposed(by: rx.disposeBag)
amountView.textField.inputAccessoryView = toolbar
amountView.textField.delegate = self
}
private func setupNavBar() {
navigationTitleView = createNavigationTitleView()
let title = R.string.localizable.ethViteExchangePageExchangeHistoryButtonTitle()
let rightItem = UIBarButtonItem(title: title, style: .plain, target: self, action: nil)
rightItem.setTitleTextAttributes([NSAttributedString.Key.font: Fonts.Font14, NSAttributedString.Key.foregroundColor: Colors.blueBg], for: .normal)
rightItem.setTitleTextAttributes([NSAttributedString.Key.font: Fonts.Font14, NSAttributedString.Key.foregroundColor: Colors.blueBg], for: .highlighted)
self.navigationItem.rightBarButtonItem = rightItem
self.navigationItem.rightBarButtonItem?.rx.tap.bind { [weak self] in
var infoUrl = "\(ViteConst.instance.eth.explorer)/address/\(ETHWalletManager.instance.account?.address ?? "")#tokentxns"
guard let url = URL(string: infoUrl) else { return }
let vc = WKWebViewController.init(url: url)
UIViewController.current?.navigationController?.pushViewController(vc, animated: true)
}.disposed(by: rx.disposeBag)
}
func bind() {
addressView.addButton.rx.tap.bind { [weak self] in
guard let `self` = self else { return }
FloatButtonsView(targetView: self.addressView.addButton, delegate: self, titles:
[R.string.localizable.sendPageMyAddressTitle(CoinType.vite.rawValue),
R.string.localizable.sendPageViteContactsButtonTitle(),
R.string.localizable.sendPageScanAddressButtonTitle()]).show()
}.disposed(by: rx.disposeBag)
exchangeButton.rx.tap.bind { [weak self] in
guard let `self` = self else { return }
let address = self.addressView.textView.text ?? ""
guard address.isViteAddress else {
Toast.show(R.string.localizable.sendPageToastAddressError())
return
}
guard let amountString = self.amountView.textField.text, !amountString.isEmpty,
let amount = amountString.toAmount(decimals: TokenInfo.BuildIn.eth_vite.value.decimals) else {
Toast.show(R.string.localizable.sendPageToastAmountEmpty())
return
}
guard amount > Amount(0) else {
Toast.show(R.string.localizable.sendPageToastAmountZero())
return
}
guard amount <= self.balance else {
Toast.show(R.string.localizable.sendPageToastAmountError())
return
}
self.exchangeErc20ViteTokenToViteCoin(viteAddress: address, amount: amount, gasPrice: Float(self.gasSliderView.value))
}.disposed(by: rx.disposeBag)
ETHBalanceInfoManager.instance.balanceInfoDriver(for: TokenInfo.BuildIn.eth_vite.value.tokenCode)
.drive(onNext: { [weak self] ret in
guard let `self` = self else { return }
self.balance = ret?.balance ?? self.balance
let text = self.balance.amountFullWithGroupSeparator(decimals: TokenInfo.BuildIn.eth_vite.value.decimals)
self.headerView.balanceLabel.text = text
self.amountView.textField.placeholder = R.string.localizable.ethViteExchangePageAmountPlaceholder(text)
}).disposed(by: rx.disposeBag)
amountView.button.rx.tap.bind { [weak self] in
guard let `self` = self else { return }
self.amountView.textField.text = self.balance.amountFull(decimals: TokenInfo.BuildIn.eth_vite.value.decimals)
}.disposed(by: rx.disposeBag)
let tokenInfo = TokenInfo.BuildIn.eth_vite.value
amountView.textField.rx.text.bind { [weak self] text in
guard let `self` = self else { return }
let rateMap = ExchangeRateManager.instance.rateMap
if let amount = text?.toAmount(decimals: tokenInfo.decimals) {
self.amountView.symbolLabel.text = "≈" + rateMap.priceString(for: tokenInfo, balance: amount)
} else {
self.amountView.symbolLabel.text = "≈ 0.0"
}
}
.disposed(by: rx.disposeBag)
}
func createNavigationTitleView() -> UIView {
let view = UIView().then {
$0.backgroundColor = UIColor.white
}
let titleLabel = LabelTipView(R.string.localizable.ethViteExchangePageTitle()).then {
$0.titleLab.font = UIFont.systemFont(ofSize: 24)
$0.titleLab.numberOfLines = 1
$0.titleLab.adjustsFontSizeToFitWidth = true
$0.titleLab.textColor = UIColor(netHex: 0x24272B)
}
let tokenIconView = UIImageView(image: R.image.icon_vite_exchange())
view.addSubview(titleLabel)
view.addSubview(tokenIconView)
titleLabel.snp.makeConstraints { (m) in
m.top.equalTo(view).offset(6)
m.left.equalTo(view).offset(24)
m.bottom.equalTo(view).offset(-20)
m.height.equalTo(29)
}
tokenIconView.snp.makeConstraints { (m) in
m.right.equalToSuperview().offset(-22)
m.top.equalToSuperview()
m.size.equalTo(CGSize(width: 50, height: 50))
}
titleLabel.tipButton.rx.tap.bind { [weak self] in
self?.showTip()
}.disposed(by: rx.disposeBag)
return view
}
func showTip() {
var htmlString = R.string.localizable.popPageTipEthViteExchange()
let vc = PopViewController(htmlString: htmlString)
vc.modalPresentationStyle = .overCurrentContext
let delegate = StyleActionSheetTranstionDelegate()
vc.transitioningDelegate = delegate
present(vc, animated: true, completion: nil)
}
func exchangeErc20ViteTokenToViteCoin(viteAddress: String, amount: Amount, gasPrice: Float) {
Workflow.ethViteExchangeWithConfirm(viteAddress: viteAddress, amount: amount, gasPrice: gasPrice, completion: { [weak self] (r) in
guard let `self` = self else { return }
if case .success = r {
AlertControl.showCompletion(R.string.localizable.workflowToastSubmitSuccess())
GCD.delay(1) { self.dismiss() }
} else if case .failure(let error) = r {
guard ViteError.conversion(from: error) != ViteError.cancel else { return }
Alert.show(title: R.string.localizable.sendPageEthFailed(error.localizedDescription),
message: nil,
actions: [
(.cancel, nil),
(.default(title: R.string.localizable.confirm()), { _ in
})
])
}
})
}
}
extension EthViteExchangeViewController: FloatButtonsViewDelegate {
func didClick(at index: Int, targetView: UIView) {
if index == 0 {
let viewModel = AddressListViewModel.createMyAddressListViewModel(for: CoinType.vite)
let vc = AddressListViewController(viewModel: viewModel)
vc.selectAddressDrive.drive(addressView.textView.rx.text).disposed(by: rx.disposeBag)
UIViewController.current?.navigationController?.pushViewController(vc, animated: true)
} else if index == 1 {
let viewModel = AddressListViewModel.createAddressListViewModel(for: CoinType.vite)
let vc = AddressListViewController(viewModel: viewModel)
vc.selectAddressDrive.drive(addressView.textView.rx.text).disposed(by: rx.disposeBag)
UIViewController.current?.navigationController?.pushViewController(vc, animated: true)
} else if index == 2 {
let scanViewController = ScanViewController()
_ = scanViewController.rx.result.bind {[weak self, scanViewController] result in
if case .success(let uri) = ViteURI.parser(string: result) {
self?.addressView.textView.text = uri.address
scanViewController.navigationController?.popViewController(animated: true)
} else {
scanViewController.showAlertMessage(result)
}
}
UIViewController.current?.navigationController?.pushViewController(scanViewController, animated: true)
}
}
}
extension EthViteExchangeViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == amountView.textField {
return InputLimitsHelper.canDecimalPointWithDigitalText(textField.text ?? "", shouldChangeCharactersIn: range, replacementString: string, decimals: min(8, TokenInfo.BuildIn.eth_vite.value.decimals))
} else {
return true
}
}
}
| 43.302326 | 210 | 0.649685 |
e4e90a6754d5a3b0986699910c4b7e9e81af9878 | 1,713 | // Atom
//
// Copyright (c) 2020 Alaska Airlines
//
// 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
/// The `TokenCredentialWritable` protocol declares an interface used for reading from / writing to `TokenCredential`.
///
/// Atom can be configured to automatically apply authorization header to any `Requestable` instance. Once properly configured, Atom will read
/// credentials from the storage specified by the client and apply them to `Requestable` instance if `requiresAuthentication` property
/// is set to `true`. Values will be set as `Authorization: Bearer token-credential` header value.
///
/// Proper configuration requires that the client conform and implement `TokenCredentialWritable` protocol where the conforming type is a class.
///
/// ```
/// class SSOCredential: TokenCredentialWritable {
/// var tokenCredential: TokenCredential {
/// get { keychain.value() }
/// set { keychain.save(newValue) }
/// }
/// }
/// ```
///
/// For more information see `Configuration` documentation.
public protocol TokenCredentialWritable: AnyObject {
/// Returns conforming type as `TokenCredential`.
var tokenCredential: TokenCredential { get set }
}
| 41.780488 | 144 | 0.736135 |
1c7d034da8d737e7f7dde8751be3e158732e7a9c | 524 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// ApplicableScheduleProtocol is schedules applicable to a virtual machine. The schedules may have been defined on a VM
// or on lab level.
public protocol ApplicableScheduleProtocol : ResourceProtocol {
var properties: ApplicableSchedulePropertiesProtocol { get set }
}
| 47.636364 | 120 | 0.776718 |
91feaf494f3c1ee53e8e4a0a03246fc1534e9885 | 337 | //
// CollectionCollectionAnimator.swift
// Tetrapak
//
// Created by mapmelad on 03/04/2018.
// Copyright © 2018 Anvics. All rights reserved.
//
import UIKit
//import Animatics
extension FriendPhotosCollectionController {
// func hideView(view: UIView) -> AnimaticsReady{
// return AlphaAnimator(0).to(view)
// }
}
| 17.736842 | 52 | 0.691395 |
20b4e4c19e54899696bb813f92dc0e31a27f4c32 | 2,114 | //
// Exercise7.swift
// Exercise 10 Auto Layout
//
// Created by Abhishek Maurya on 11/03/19.
// Copyright © 2019 Abhishek Maurya. All rights reserved.
//
import UIKit
class Exercise10: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func openQuestion1() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "Question1")
self.navigationController!.pushViewController(controller, animated: true)
}
@IBAction func openQuestion2() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "Question2")
self.navigationController!.pushViewController(controller, animated: true)
}
@IBAction func openQuestion3() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "Question3")
self.navigationController!.pushViewController(controller, animated: true)
}
@IBAction func openQuestion4() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "Question4")
self.navigationController!.pushViewController(controller, animated: true)
}
@IBAction func openQuestion5() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "Question5")
self.navigationController!.pushViewController(controller, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 37.087719 | 106 | 0.698202 |
16804e858ea01a6958fb1c1f491102840cccdd9f | 3,378 | //
// MyDealsViewController.swift
// DailyDeals
//
// Description:
// In this ViewController a user with a company account can view their added deals and delete them if needed.
//
// Created by practicum on 31/01/17.
// Copyright © 2017 Jill de Ron. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
class MyDealsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: Outlet.
@IBOutlet weak var myDealsTableView: UITableView!
// MARK: Variables.
var dealsOfUser = [Deal]()
var ref = FIRDatabase.database().reference(withPath: "deals")
let currentUser = (FIRAuth.auth()?.currentUser?.uid)!
var nameDeal = String()
var nameCompany = String()
// MARK: Standard functions.
override func viewDidLoad() {
super.viewDidLoad()
loadDealsUser()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: TableView functions.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(dealsOfUser.count)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let deal = dealsOfUser[indexPath.row]
nameDeal = deal.nameDeal
nameCompany = deal.nameCompany
self.performSegue(withIdentifier: "toMoreInformation", sender: self)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
let deal = dealsOfUser[indexPath.row]
cell.textLabel?.text = deal.nameDeal
return(cell)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
// Delete deal in Firebase.
if editingStyle == .delete {
let deal = dealsOfUser[indexPath.row]
deal.ref?.removeValue()
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "deletedDeals"), object: nil)
}
// MARK: Get deals of the company account from the current user.
private func loadDealsUser() {
ref.observe(.value, with: { snapshot in
var ownDeals: [Deal] = []
for item in snapshot.children {
let ownDeal = Deal(snapshot: item as! FIRDataSnapshot)
if ownDeal.uid == self.currentUser {
ownDeals.append(ownDeal)
}
}
self.dealsOfUser = ownDeals
self.myDealsTableView.reloadData()
})
}
// MARK: Segues.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMoreInformation" {
let destination = segue.destination as? InformationDealViewController
// Define variables you want to sent to next ViewController.
destination?.nameDealReceiver = self.nameDeal
destination?.nameCompanyReceiver = self.nameCompany
}
}
}
| 32.480769 | 127 | 0.630847 |
648305524819a87a4030524b94b5fca0751542aa | 1,225 | //
// BaiYueUITests.swift
// BaiYueUITests
//
// Created by qcj on 2017/12/7.
// Copyright © 2017年 qcj. All rights reserved.
//
import XCTest
class BaiYueUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.108108 | 182 | 0.658776 |
Subsets and Splits