repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
TBXark/Ruler | Ruler/Modules/Ruler/Classes/MeasurementUnit.swift | 1 | 3810 | //
// Distance.swift
// Ruler
//
// Created by Tbxark on 19/09/2017.
// Copyright © 2017 Tbxark. All rights reserved.
//
import UIKit
struct MeasurementUnit {
enum Unit: String {
static let all: [Unit] = [.inch, .foot, .centimeter, .meter]
case inch = "inch"
case foot = "foot"
case centimeter = "centimeter"
case meter = "meter"
func next() -> Unit {
switch self {
case .inch:
return .foot
case .foot:
return .centimeter
case .centimeter:
return .meter
case .meter:
return .inch
}
}
func meterScale(isArea: Bool = false) -> Float {
let scale: Float = isArea ? 2 : 1
switch self {
case .meter: return pow(1, scale)
case .centimeter: return pow(100, scale)
case .inch: return pow(39.370, scale)
case .foot: return pow(3.2808399, scale)
}
}
func unitStr(isArea: Bool = false) -> String {
switch self {
case .meter:
return isArea ? "m^2" : "m"
case .centimeter:
return isArea ? "cm^2" : "cm"
case .inch:
return isArea ? "in^2" : "in"
case .foot:
return isArea ? "ft^2" : "ft"
}
}
}
private let rawValue: Float
private let isArea: Bool
init(meterUnitValue value: Float, isArea: Bool = false) {
self.rawValue = value
self.isArea = isArea
}
func string(type: Unit) -> String {
let unit = type.unitStr(isArea: isArea)
let scale = type.meterScale(isArea: isArea)
let res = rawValue * scale
if res < 0.1 {
return String(format: "%.3f", res) + unit
} else if res < 1 {
return String(format: "%.2f", res) + unit
} else if res < 10 {
return String(format: "%.1f", res) + unit
} else {
return String(format: "%.0f", res) + unit
}
}
func attributeString(type: Unit,
valueFont: UIFont = UIFont.boldSystemFont(ofSize: 60),
unitFont: UIFont = UIFont.systemFont(ofSize: 20),
color: UIColor = UIColor.black) -> NSAttributedString {
func buildAttributeString(value: String, unit: String) -> NSAttributedString {
let main = NSMutableAttributedString()
let v = NSMutableAttributedString(string: value,
attributes: [NSAttributedStringKey.font: valueFont,
NSAttributedStringKey.foregroundColor: color])
let u = NSMutableAttributedString(string: unit,
attributes: [NSAttributedStringKey.font: unitFont,
NSAttributedStringKey.foregroundColor: color])
main.append(v)
main.append(u)
return main
}
let unit = type.unitStr(isArea: isArea)
let scale = type.meterScale(isArea: isArea)
let res = rawValue * scale
if res < 0.1 {
return buildAttributeString(value: String(format: "%.3f", res), unit: unit)
} else if res < 1 {
return buildAttributeString(value: String(format: "%.2f", res), unit: unit)
} else if res < 10 {
return buildAttributeString(value: String(format: "%.1f", res), unit: unit)
} else {
return buildAttributeString(value: String(format: "%.0f", res), unit: unit)
}
}
}
| mit |
practicalswift/swift | test/SILOptimizer/definite_init_diagnostics_globals.swift | 8 | 2842 | // RUN: %target-swift-frontend -emit-sil -enable-sil-ownership -primary-file %s -o /dev/null -verify
import Swift
// Tests for definite initialization of globals.
var x: Int // expected-note {{variable defined here}}
// expected-note@-1 {{variable defined here}}
// expected-note@-2 {{variable defined here}}
// expected-note@-3 {{variable defined here}}
let y: Int // expected-note {{constant defined here}}
// expected-note@-1 {{constant defined here}}
// expected-note@-2 {{constant defined here}}
// Test top-level defer.
defer { print(x) } // expected-error {{variable 'x' used in defer before being initialized}}
defer { print(y) } // expected-error {{constant 'y' used in defer before being initialized}}
// Test top-level functions.
func testFunc() { // expected-error {{variable 'x' used by function definition before being initialized}}
defer { print(x) } // expected-warning {{'defer' statement before end of scope always executes immediately}}{{3-8=do}}
}
// Test top-level closures.
let clo: () -> Void = { print(y) } // expected-error {{constant 'y' captured by a closure before being initialized}}
clo()
({ () -> Void in print(x) })() // expected-error {{variable 'x' captured by a closure before being initialized}}
let clo2: () -> Void = { [x] in print(x) } // expected-error {{variable 'x' used before being initialized}}
clo2()
class C {
var f = 0
}
var c: C // expected-note {{variable defined here}}
let clo3: () -> Void = { [weak c] in // expected-error {{variable 'c' used before being initialized}}
guard let cref = c else{ return }
print(cref)
}
clo3()
// Test inner functions.
func testFunc2() { // expected-error {{constant 'y' used by function definition before being initialized}}
func innerFunc() {
print(y)
}
}
// Test class initialization and methods.
var w: String // expected-note {{variable defined here}}
// expected-note@-1 {{variable defined here}}
// expected-note@-2 {{variable defined here}}
// FIXME: the error should blame the class definition: <rdar://41490541>.
class TestClass1 { // expected-error {{variable 'w' used by function definition before being initialized}}
let fld = w
}
class TestClass2 {
init() { // expected-error {{variable 'w' used by function definition before being initialized}}
print(w)
}
func bar() { // expected-error {{variable 'w' used by function definition before being initialized}}
print(w)
}
}
// Test initialization of global variables of protocol type.
protocol P {
var f: Int { get }
}
var p: P // expected-note {{variable defined here}}
defer { print(p.f) } // expected-error {{variable 'p' used in defer before being initialized}}
| apache-2.0 |
geojow/beeryMe | beeryMe/PubView.swift | 1 | 955 | //
// PubViews.swift
// beeryMe
//
// Created by George Jowitt on 23/11/2017.
// Copyright © 2017 George Jowitt. All rights reserved.
//
import Foundation
import MapKit
class PubView: MKAnnotationView {
override var annotation: MKAnnotation? {
willSet {
guard let pub = newValue as? Pub else { return }
canShowCallout = true
calloutOffset = CGPoint(x: -5, y: 5)
if let pubImage = pub.image {
image = pubImage
} else {
image = nil
}
let btn = UIButton(type: .infoLight)
btn.setImage(image, for: .normal)
btn.tintColor = nil
leftCalloutAccessoryView = btn
let mapsButton = UIButton(frame: CGRect(origin: CGPoint.zero,
size: CGSize(width: 30, height: 30)))
mapsButton.setBackgroundImage(UIImage(named: "maps-icon"), for: UIControlState())
rightCalloutAccessoryView = mapsButton
}
}
}
| mit |
Mattmlm/codepathInstagramFeed | InstagramFeed/PhotoDetailsViewController.swift | 1 | 2064 | //
// PhotoDetailsViewController.swift
// InstagramFeed
//
// Created by admin on 9/17/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
class PhotoDetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var imageURL : String?
@IBOutlet weak var photoDetailsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.photoDetailsTableView.delegate = self;
self.photoDetailsTableView.dataSource = self;
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 320;
} else {
return tableView.rowHeight;
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("photoDetailsCell")
if indexPath.row == 0 {
if let imageURL = self.imageURL {
cell!.imageView?.contentMode = .ScaleAspectFit;
cell!.imageView?.setImageWithURL(NSURL(string: imageURL)!);
}
}
return cell!;
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
DrabWeb/Azusa | Azusa.Previous/Azusa/Utilities/AZMusicUtilities.swift | 1 | 2328 | //
// AZMusicUtilities.swift
// Azusa
//
// Created by Ushio on 12/7/16.
//
import Foundation
/// General music related utilities for Azusa
struct AZMusicUtilities {
// MARK: - Functions
/// Returns the hours, minutes and seconds from the given amount of seconds
///
/// - Parameter seconds: The seconds to use
/// - Returns: The hours, minutes and seconds of `seconds`
static func hoursMinutesSeconds(from seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60);
}
/// Returns the display string for given seconds
///
/// - Parameter seconds: The seconds to get the display time from
/// - Returns: The display string for the given seconds(e.g. 1:40, 0:32, 1:05:42, etc.)
static func secondsToDisplayTime(_ seconds : Int) -> String {
/// The hours, minutes and seconds from `seconds`
let hoursMinutesSeconds = AZMusicUtilities.hoursMinutesSeconds(from: seconds);
/// The display string for the hours
var hoursString : String = "";
/// The display string for the minutes
var minutesString : String = "";
/// The display string for the seconds
var secondsString : String = "";
// If there is at least one hour...
if(hoursMinutesSeconds.0 > 0) {
// Set the hours string to the hour count
hoursString = String(hoursMinutesSeconds.0);
}
// Set the minutes string to minutes, zero padded by one
minutesString = String(format: "%01d", hoursMinutesSeconds.1);
// Set the seconds string to seconds, zero padded by two
secondsString = String(format: "%02d", hoursMinutesSeconds.2);
// If the hours string is set...
if(hoursString != "") {
// Set minutes string to have two zero padding
minutesString = String(format: "%02d", hoursMinutesSeconds.1);
// Return the display string
return "\(hoursString):\(minutesString):\(secondsString)";
}
// If the hours string isn't set...
else {
// Return the display string as is
return "\(minutesString):\(secondsString)";
}
}
}
| gpl-3.0 |
AlesTsurko/AudioKit | Tests/Tests/AKDecimator.swift | 2 | 1482 | //
// main.swift
// AudioKit
//
// Created by Aurelius Prochazka on 2/2/15.
// Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: Float = 10.0
class Instrument : AKInstrument {
override init() {
super.init()
let filename = "CsoundLib64.framework/Sounds/PianoBassDrumLoop.wav"
let audio = AKFileInput(filename: filename)
let mono = AKMix(monoAudioFromStereoInput: audio)
let bitDepth = AKLine(
firstPoint: 24.ak,
secondPoint: 18.ak,
durationBetweenPoints: testDuration.ak
)
let sampleRate = AKLine(
firstPoint: 5000.ak,
secondPoint: 1000.ak,
durationBetweenPoints: testDuration.ak
)
let decimator = AKDecimator(input: mono)
decimator.bitDepth = bitDepth
decimator.sampleRate = sampleRate
setAudioOutput(decimator)
enableParameterLog(
"Bit Depth = ",
parameter: decimator.bitDepth,
timeInterval:0.1
)
enableParameterLog(
"Sample Rate = ",
parameter: decimator.sampleRate,
timeInterval:0.1
)
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
instrument.play()
let manager = AKManager.sharedManager()
while(manager.isRunning) {} //do nothing
println("Test complete!")
| lgpl-3.0 |
biohazardlover/ROer | Roer/Monster+DatabaseRecord.swift | 1 | 14649 |
import CoreData
import CoreSpotlight
import MobileCoreServices
extension Monster {
var displayRace: String? {
guard let race = race else { return nil }
switch race {
case 0:
return "Monster.Race.Formless".localized
case 1:
return "Monster.Race.Undead".localized
case 2:
return "Monster.Race.Brute".localized
case 3:
return "Monster.Race.Plant".localized
case 4:
return "Monster.Race.Insect".localized
case 5:
return "Monster.Race.Fish".localized
case 6:
return "Monster.Race.Demon".localized
case 7:
return "Monster.Race.DemiHuman".localized
case 8:
return "Monster.Race.Angel".localized
case 9:
return "Monster.Race.Dragon".localized
case 10:
return "Monster.Race.Player".localized
default:
return nil
}
}
var displayProperty: String? {
guard let element = element else { return nil }
let level = element.intValue / 20
switch element {
case 20, 40, 60, 80:
return "Property.Neutral".localized + " \(level)"
case 21, 41, 61, 81:
return "Property.Water".localized + " \(level)"
case 22, 42, 62, 82:
return "Property.Earth".localized + " \(level)"
case 23, 43, 63, 83:
return "Property.Fire".localized + " \(level)"
case 24, 44, 64, 84:
return "Property.Wind".localized + " \(level)"
case 25, 45, 65, 85:
return "Property.Poison".localized + " \(level)"
case 26, 46, 66, 86:
return "Property.Holy".localized + " \(level)"
case 27, 47, 67, 87:
return "Property.Shadow".localized + " \(level)"
case 28, 48, 68, 88:
return "Property.Ghost".localized + " \(level)"
case 29, 49, 69, 89:
return "Property.Undead".localized + " \(level)"
default:
return nil
}
}
var displaySize: String? {
guard let scale = scale else { return nil }
switch scale {
case 0:
return "Monster.Size.Small".localized
case 1:
return "Monster.Size.Medium".localized
case 2:
return "Monster.Size.Large".localized
default:
return nil
}
}
var displayAttackDelay: String? {
guard let aDelay = aDelay else { return nil }
let attackDelay = aDelay.floatValue / 1000.0
return "\(attackDelay)s"
}
var displayAttack: String? {
guard let atk1 = atk1, let atk2 = atk2 else { return nil }
return "\(atk1)-\(atk2)"
}
var displayBaseExperiencePerHP: String? {
guard let exp = exp, let hp = hp else { return nil }
let baseExperiencePerHP = exp.floatValue / hp.floatValue
return NSString(format: "%.3f:1", baseExperiencePerHP) as String
}
var displayJobExperiencePerHP: String? {
guard let jexp = jexp, let hp = hp else { return nil }
let jobExperiencePerHP = jexp.floatValue / hp.floatValue
return NSString(format: "%.3f:1", jobExperiencePerHP) as String
}
var displayModes: NSAttributedString? {
guard let mode = mode else { return nil }
var modes = [String]()
let modeMask = mode.intValue
if modeMask & 1 << 0 == 0 {
modes.append("Monster.Mode.Immovable".localized)
}
if modeMask & 1 << 1 != 0 {
modes.append("Monster.Mode.Looter".localized)
}
if modeMask & 1 << 2 != 0 {
modes.append("Monster.Mode.Aggressive".localized)
}
if modeMask & 1 << 3 != 0 {
modes.append("Monster.Mode.Assist".localized)
}
if modeMask & 1 << 4 != 0 {
modes.append("Monster.Mode.CastSensorIdle".localized)
}
if modeMask & 1 << 5 != 0 {
modes.append("Monster.Mode.ImmuneToStatusChange".localized)
}
if modeMask & 1 << 6 != 0 {
modes.append("Monster.Mode.Plant".localized)
}
if modeMask & 1 << 7 == 0 {
modes.append("Monster.Mode.NonAttacker".localized)
}
if modeMask & 1 << 8 != 0 {
modes.append("Monster.Mode.Detector".localized)
}
if modeMask & 1 << 9 != 0 {
modes.append("Monster.Mode.CastSensorChase".localized)
}
if modeMask & 1 << 10 != 0 {
modes.append("Monster.Mode.ChangeChase".localized)
}
if modeMask & 1 << 11 != 0 {
modes.append("Monster.Mode.Angry".localized)
}
if modeMask & 1 << 12 != 0 {
modes.append("Monster.Mode.ChangeTargetAttack".localized)
}
if modeMask & 1 << 13 != 0 {
modes.append("Monster.Mode.ChangeTargetChase".localized)
}
if modeMask & 1 << 14 != 0 {
modes.append("Monster.Mode.TargetWeak".localized)
}
if modeMask & 1 << 15 != 0 {
modes.append("Monster.Mode.RandomTarget".localized)
}
if modeMask & 1 << 16 != 0 {
modes.append("Monster.Mode.IgnoreMelee".localized)
}
if modeMask & 1 << 17 != 0 {
modes.append("Monster.Mode.IgnoreMagic".localized)
}
if modeMask & 1 << 18 != 0 {
modes.append("Monster.Mode.IgnoreRange".localized)
}
if modeMask & 1 << 19 != 0 {
modes.append("Monster.Mode.BossTypeImmunityToSkills".localized)
}
if modeMask & 1 << 20 != 0 {
modes.append("Monster.Mode.IgnoreMisc".localized)
}
if modeMask & 1 << 21 != 0 {
modes.append("Monster.Mode.KnockbackImmune".localized)
}
if modeMask & 1 << 22 != 0 {
modes.append("Monster.Mode.NoRandomWalk".localized)
}
if modeMask & 1 << 23 != 0 {
modes.append("Monster.Mode.NoCastSkill".localized)
}
modes = modes.map { "- " + $0 }
return NSAttributedString(string: modes.joined(separator: "\n"))
}
}
extension Monster {
var onMaps: [DatabaseRecordCellInfo] {
guard let monsterSpawnGroups = monsterSpawnGroups else {return [] }
var onMaps = [DatabaseRecordCellInfo]()
for monsterSpawnGroup in monsterSpawnGroups {
guard let map = monsterSpawnGroup.map else {
continue
}
onMaps.append((map, monsterSpawnGroup.displaySpawn))
}
return onMaps
}
var drops: [(id: NSNumber, per: NSNumber)] {
var drops: [(id: NSNumber?, per: NSNumber?)] = [(drop1id, drop1per), (drop2id, drop2per), (drop3id, drop3per), (drop4id, drop4per), (drop5id, drop5per), (drop6id, drop6per), (drop7id, drop7per), (drop8id, drop8per), (drop9id, drop9per), (dropCardid, dropCardper), (mvp1id, mvp1per), (mvp2id, mvp2per), (mvp3id, mvp3per)]
drops = drops.filter { $0.id != nil && $0.per != nil && $0.id != 0 }
return drops.map { ($0.id!, $0.per!) }
}
var dropItems: [DatabaseRecordCellInfo] {
var dropItems = [DatabaseRecordCellInfo]()
let drops: [(id: NSNumber?, per: NSNumber?)] = [(drop1id, drop1per), (drop2id, drop2per), (drop3id, drop3per), (drop4id, drop4per), (drop5id, drop5per), (drop6id, drop6per), (drop7id, drop7per), (drop8id, drop8per), (drop9id, drop9per), (dropCardid, dropCardper)]
for drop in drops {
if let dropId = drop.id , dropId != 0, let dropPer = drop.per {
let fetchRequest = NSFetchRequest<Item>(entityName: "Item")
fetchRequest.predicate = NSPredicate(format: "id == %@", dropId)
if let item = (try? managedObjectContext?.fetch(fetchRequest))??.first {
dropItems.append((item, dropRateWithPer(dropPer)))
}
}
}
dropItems.sort { (dropItem1, dropItem2) -> Bool in
return (dropItem1.databaseRecord as! Item).id?.intValue ?? 0 < (dropItem2.databaseRecord as! Item).id?.intValue ?? 0
}
return dropItems
}
var mvpDropItems: [DatabaseRecordCellInfo] {
var mvpDropItems = [DatabaseRecordCellInfo]()
let mvpDrops: [(id: NSNumber?, per: NSNumber?)] = [(mvp1id, mvp1per), (mvp2id, mvp2per), (mvp3id, mvp3per)]
for mvpDrop in mvpDrops {
if let mvpDropId = mvpDrop.id , mvpDropId != 0, let mvpDropPer = mvpDrop.per {
let fetchRequest = NSFetchRequest<Item>(entityName: "Item")
fetchRequest.predicate = NSPredicate(format: "id == %@", mvpDropId)
if let item = (try? managedObjectContext?.fetch(fetchRequest))??.first {
mvpDropItems.append((item, dropRateWithPer(mvpDropPer)))
}
}
}
mvpDropItems.sort { (mvpDropItem1, mvpDropItem2) -> Bool in
return (mvpDropItem1.databaseRecord as! Item).id?.intValue ?? 0 < (mvpDropItem2.databaseRecord as! Item).id?.intValue ?? 0
}
return mvpDropItems
}
}
extension Monster {
var monsterSpawnGroups: [MonsterSpawnGroup]? {
guard let id = id else { return nil }
let fetchRequest = NSFetchRequest<MonsterSpawn>(entityName: "MonsterSpawn")
fetchRequest.predicate = NSPredicate(format: "monsterID == %@", id)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "mapName", ascending: true)]
guard let monsterSpawns = (try? managedObjectContext?.fetch(fetchRequest)) ?? nil else { return nil }
return MonsterSpawnGroup.monsterSpawnGroupsWithMonsterSpawns(monsterSpawns)
}
}
extension Monster {
var localizedName: String? {
if let id = id {
if let localizedName = Localization.preferred.monsters[id.stringValue] {
return localizedName
}
}
return kROName
}
}
extension Monster: DatabaseRecord {
var smallImageURL: URL? {
return nil
}
var largeImageURL: URL? {
if let id = id {
return URL(string: "http://file5.ratemyserver.net/mobs/\(id).gif")
} else {
return nil
}
}
var displayName: String? {
return localizedName
}
var recordDetails: DatabaseRecordDetails {
var attributeGroups = [DatabaseRecordAttributeGroup]()
attributeGroups.appendAttribute(("Monster.HP".localized, hp))
attributeGroups.appendAttribute(("Monster.Level".localized, lv))
attributeGroups.appendAttribute(("Monster.Race".localized, displayRace?.utf8))
attributeGroups.appendAttribute(("Monster.Property".localized, displayProperty?.utf8))
attributeGroups.appendAttribute(("Monster.Size".localized, displaySize?.utf8))
attributeGroups.appendAttribute(("Monster.Hit100".localized, hit100))
attributeGroups.appendAttribute(("Monster.Flee95".localized, flee95))
attributeGroups.appendAttribute(("Monster.WalkSpeed".localized, speed))
attributeGroups.appendAttribute(("Monster.AttackDelay".localized, displayAttackDelay?.utf8))
attributeGroups.appendAttribute(("Monster.Attack".localized, displayAttack?.utf8))
attributeGroups.appendAttribute(("Monster.Defence".localized, def))
attributeGroups.appendAttribute(("Monster.MagicDefence".localized, mdef))
attributeGroups.appendAttribute(("Monster.AttackRange".localized, range1)) { $0 + " " + "Cells".localized }
attributeGroups.appendAttribute(("Monster.SpellRange".localized, range2)) { $0 + " " + "Cells".localized }
attributeGroups.appendAttribute(("Monster.SightRange".localized, range3)) { $0 + " " + "Cells".localized }
attributeGroups.appendAttribute(("Monster.BaseExperience".localized, exp))
attributeGroups.appendAttribute(("Monster.JobExperience".localized, jexp))
attributeGroups.appendAttribute(("Monster.MVPExperience".localized, mexp != nil && mexp!.intValue > 0 ? mexp : nil))
attributeGroups.appendAttribute(("Monster.BaseExperiencePerHP".localized, displayBaseExperiencePerHP?.utf8))
attributeGroups.appendAttribute(("Monster.JobExperiencePerHP".localized, displayJobExperiencePerHP?.utf8))
attributeGroups.appendAttribute(("Monster.DelayAfterHit".localized, dMotion))
attributeGroups.appendAttributes([("Monster.Str".localized, str), ("Monster.Agi".localized, agi), ("Monster.Vit".localized, vit)])
attributeGroups.appendAttributes([("Monster.Int".localized, int), ("Monster.Dex".localized, dex), ("Monster.Luk".localized, luk)])
var recordDetails = DatabaseRecordDetails()
recordDetails.appendTitle(displayName != nil && id != nil ? "\(displayName!) #\(id!)" : "", section: .attributeGroups(attributeGroups))
recordDetails.appendTitle("Monster.OnMaps".localized, section: .databaseRecords(onMaps))
recordDetails.appendTitle("Monster.Modes".localized, section: .description(displayModes))
recordDetails.appendTitle("Monster.Drops".localized, section: .databaseRecords(dropItems))
recordDetails.appendTitle("Monster.MVPDrops".localized, section: .databaseRecords(mvpDropItems))
return recordDetails
}
func correspondingDatabaseRecord(in managedObjectContext: NSManagedObjectContext) -> DatabaseRecord? {
guard let id = id else { return nil }
let request = NSFetchRequest<Monster>(entityName: "Monster")
request.predicate = NSPredicate(format: "%K == %@", "id", id)
let results = try? managedObjectContext.fetch(request)
return results?.first
}
}
extension Monster: Searchable {
var searchableItem: CSSearchableItem {
let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeData as String)
searchableItemAttributeSet.title = localizedName
searchableItemAttributeSet.contentDescription = nil
searchableItemAttributeSet.thumbnailData = nil
return CSSearchableItem(uniqueIdentifier: "Monster/" + (id?.stringValue ?? ""), domainIdentifier: nil, attributeSet: searchableItemAttributeSet)
}
}
| mit |
CNKCQ/oschina | OSCHINA/Protocol/SignupProtocol.swift | 1 | 914 | //
// Copyright © 2016年 KingCQ. All rights reserved.
// Created by KingCQ on 16/9/3.
//
import RxSwift
enum ValidationResult {
case ok(message: String)
case empty
case validating
case failed(message: String)
}
enum SignupState {
case signedUp(signedUp: Bool)
}
protocol SignupAPI {
func usernameAvailable(_ username: String) -> Observable<Bool>
func signup(_ username: String, password: String) -> Observable<Bool>
}
protocol SignupValidationService {
func validateUsername(_ username: String) -> Observable<ValidationResult>
func validatePassword(_ password: String) -> ValidationResult
func validateRepeatedPassword(_ password: String, repeatedPassword: String) -> ValidationResult
}
extension ValidationResult {
var isValid: Bool {
switch self {
case .ok:
return true
default:
return false
}
}
}
| mit |
mattiasjahnke/arduino-projects | matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/examples/login/Example/AppDelegate.swift | 1 | 1539 | //
// AppDelegate.swift
// LoginSample
//
// Created by Måns Bernhardt on 2018-04-12.
// Copyright © 2018 iZettle. All rights reserved.
//
import UIKit
import Flow
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let bag = DisposeBag()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let vc = UIViewController()
let loginButton = UIButton(type: UIButtonType.system)
loginButton.setTitle("Show Login Controller", for: .normal)
let stack = UIStackView(arrangedSubviews: [loginButton])
stack.alignment = .center
vc.view = stack
let window = UIWindow(frame: UIScreen.main.bounds)
self.window = window
window.backgroundColor = .white
window.rootViewController = vc
window.makeKeyAndVisible()
bag += loginButton.onValue {
let login = LoginController()
let nc = UINavigationController(rootViewController: login)
vc.present(nc, animated: true, completion: nil)
login.runLogin().onValue { user in
print("Login succeeded with user", user)
}.onError { error in
print("Login failed with error", error)
}.always {
nc.dismiss(animated: true, completion: nil)
}
}
return true
}
}
| mit |
rafattouqir/RRNotificationBar | RRNotificationBar/ViewController.swift | 1 | 798 | //
// ViewController.swift
// RRNotificationBar
//
// Created by RAFAT TOUQIR RAFSUN on 2/6/17.
// Copyright © 2017 RAFAT TOUQIR RAFSUN. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = .green
}
@IBAction func showNotification(_ sender: Any) {
RRNotificationBar().show(title: "New vote", message: "Someone voted you",onTap:{
print("tapped")
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
crossroadlabs/ExpressCommandLine | swift-express/Core/Steps/CopyDirectoryContents.swift | 1 | 4005 | //===--- CopyDirectoryContents.swift ----------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express Command Line is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===------------------------------------------------------------------===//
import Foundation
import Regex
//Copy contents of directory into another. Ignoring .git folder
//Input: inputFolder
//Input: outputFolder
//Output:
// copiedItems: Array<String>
// outputFolder: String
struct CopyDirectoryContents : Step {
let dependsOn = [Step]()
let excludeList:[Regex]
let alreadyExistsError = "CopyDirectoryContents: Output folder already exists."
func run(params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] {
guard let inputFolder = params["inputFolder"] as? String else {
throw SwiftExpressError.BadOptions(message: "CopyDirectoryContents: No inputFolder option.")
}
guard let outputFolder = params["outputFolder"] as? String else {
throw SwiftExpressError.BadOptions(message: "CopyDirectoryContents: No outputFolder option.")
}
do {
if FileManager.isDirectoryExists(outputFolder) || FileManager.isFileExists(outputFolder) {
throw SwiftExpressError.BadOptions(message: alreadyExistsError)
} else {
try FileManager.createDirectory(outputFolder, createIntermediate: true)
}
var copiedItems = [String]()
let contents = try FileManager.listDirectory(inputFolder)
for item in contents {
let ignore = excludeList.reduce(false, combine: { (prev, r) -> Bool in
return prev || r.matches(item)
})
if ignore {
continue
}
try FileManager.copyItem(inputFolder.addPathComponent(item), toDirectory: outputFolder)
copiedItems.append(item)
}
return ["copiedItems": copiedItems, "outputFolder": outputFolder]
} catch let err as SwiftExpressError {
throw err
} catch let err as NSError {
throw SwiftExpressError.SomeNSError(error: err)
} catch {
throw SwiftExpressError.UnknownError(error: error)
}
}
func cleanup(params: [String : Any], output: StepResponse) throws {
}
func revert(params: [String : Any], output: [String : Any]?, error: SwiftExpressError?) {
switch error {
case .BadOptions(let message)?:
if message == alreadyExistsError {
return
}
fallthrough
default:
if let outputFolder = params["outputFolder"] as? String {
do {
try FileManager.removeItem(outputFolder)
} catch {
print("CopyDirectoryContents: Can't remove output folder on revert \(outputFolder)")
}
}
}
}
init(excludeList: [String]? = nil) {
if excludeList != nil {
self.excludeList = excludeList!.map({ str -> Regex in
return str.r!
})
} else {
self.excludeList = ["\\.git$".r!]
}
}
} | gpl-3.0 |
ted005/iOS-Programming-in-Swift | Hypnosister/HypnosisterTests/HypnosisterTests.swift | 1 | 905 | //
// HypnosisterTests.swift
// HypnosisterTests
//
// Created by Robbie on 15/7/9.
// Copyright (c) 2015年 Ted Wei. All rights reserved.
//
import UIKit
import XCTest
class HypnosisterTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
yellowChao/beverly | DTMaster/Pods/HanekeSwift/Haneke/Cache.swift | 1 | 11132 | //
// Cache.swift
// Haneke
//
// Created by Luis Ascorbe on 23/07/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
// Used to add T to NSCache
class ObjectWrapper: NSObject {
let value: Any
init(value: Any) {
self.value = value
}
}
extension HanekeGlobals {
// It'd be better to define this in the Cache class but Swift doesn't allow statics in a generic type
public struct Cache {
public static let OriginalFormatName = "original"
public enum ErrorCode: Int {
case ObjectNotFound = -100
case FormatNotFound = -101
}
}
}
public class Cache<T: DataConvertible where T.Result == T, T : DataRepresentable> {
let name: String
var memoryWarningObserver: NSObjectProtocol!
public init(name: String) {
self.name = name
let notifications = NSNotificationCenter.defaultCenter()
// Using block-based observer to avoid subclassing NSObject
memoryWarningObserver = notifications.addObserverForName(UIApplicationDidReceiveMemoryWarningNotification,
object: nil,
queue: NSOperationQueue.mainQueue(),
usingBlock: { [unowned self] (notification: NSNotification!) -> Void in
self.onMemoryWarning()
})
let originalFormat = Format<T>(name: HanekeGlobals.Cache.OriginalFormatName)
self.addFormat(originalFormat)
}
deinit {
let notifications = NSNotificationCenter.defaultCenter()
notifications.removeObserver(memoryWarningObserver, name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
}
public func set(value value: T, key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed: ((T) -> ())? = nil) {
if let (format, memoryCache, diskCache) = self.formats[formatName] {
self.format(value: value, format: format) { formattedValue in
let wrapper = ObjectWrapper(value: formattedValue)
memoryCache.setObject(wrapper, forKey: key)
// Value data is sent as @autoclosure to be executed in the disk cache queue.
diskCache.setData(self.dataFromValue(formattedValue, format: format), key: key)
succeed?(formattedValue)
}
} else {
assertionFailure("Can't set value before adding format")
}
}
public func fetch(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail: Fetch<T>.Failer? = nil, success succeed: Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetch = Cache.buildFetch(failure: fail, success: succeed)
if let (format, memoryCache, diskCache) = self.formats[formatName] {
if let wrapper = memoryCache.objectForKey(key) as? ObjectWrapper, let result = wrapper.value as? T {
fetch.succeed(result)
diskCache.updateAccessDate(self.dataFromValue(result, format: format), key: key)
return fetch
}
self.fetchFromDiskCache(diskCache, key: key, memoryCache: memoryCache, failure: { error in
fetch.fail(error)
}) { value in
fetch.succeed(value)
}
} else {
let localizedFormat = NSLocalizedString("Format %@ not found", comment: "Error description")
let description = String(format:localizedFormat, formatName)
let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue, description: description)
fetch.fail(error)
}
return fetch
}
public func fetch(fetcher fetcher: Fetcher<T>, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail: Fetch<T>.Failer? = nil, success succeed: Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let key = fetcher.key
let fetch = Cache.buildFetch(failure: fail, success: succeed)
self.fetch(key: key, formatName: formatName, failure: { error in
if error?.code == HanekeGlobals.Cache.ErrorCode.FormatNotFound.rawValue {
fetch.fail(error)
}
if let (format, _, _) = self.formats[formatName] {
self.fetchAndSet(fetcher, format: format, failure: {error in
fetch.fail(error)
}) {value in
fetch.succeed(value)
}
}
// Unreachable code. Formats can't be removed from Cache.
}) { value in
fetch.succeed(value)
}
return fetch
}
public func remove(key key: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName) {
if let (_, memoryCache, diskCache) = self.formats[formatName] {
memoryCache.removeObjectForKey(key)
diskCache.removeData(key)
}
}
public func removeAll() {
for (_, (_, memoryCache, diskCache)) in self.formats {
memoryCache.removeAllObjects()
diskCache.removeAllData()
}
}
// MARK: Notifications
func onMemoryWarning() {
for (_, (_, memoryCache, _)) in self.formats {
memoryCache.removeAllObjects()
}
}
// MARK: Formats
var formats: [String : (Format<T>, NSCache, DiskCache)] = [:]
public func addFormat(format: Format<T>) {
let name = format.name
let formatPath = self.formatPath(formatName: name)
let memoryCache = NSCache()
let diskCache = DiskCache(path: formatPath, capacity : format.diskCapacity)
self.formats[name] = (format, memoryCache, diskCache)
}
// MARK: Internal
lazy var cachePath: String = {
let basePath = DiskCache.basePath()
let cachePath = (basePath as NSString).stringByAppendingPathComponent(self.name)
return cachePath
}()
func formatPath(formatName formatName: String) -> String {
let formatPath = (self.cachePath as NSString).stringByAppendingPathComponent(formatName)
do {
try NSFileManager.defaultManager().createDirectoryAtPath(formatPath, withIntermediateDirectories: true, attributes: nil)
} catch {
Log.error("Failed to create directory \(formatPath)", error as NSError)
}
return formatPath
}
// MARK: Private
func dataFromValue(value: T, format: Format<T>) -> NSData? {
if let data = format.convertToData?(value) {
return data
}
return value.asData()
}
private func fetchFromDiskCache(diskCache: DiskCache, key: String, memoryCache: NSCache, failure fail: ((NSError?) -> ())?, success succeed: (T) -> ()) {
diskCache.fetchData(key: key, failure: { error in
if let block = fail {
if (error?.code == NSFileReadNoSuchFileError) {
let localizedFormat = NSLocalizedString("Object not found for key %@", comment: "Error description")
let description = String(format:localizedFormat, key)
let error = errorWithCode(HanekeGlobals.Cache.ErrorCode.ObjectNotFound.rawValue, description: description)
block(error)
} else {
block(error)
}
}
}) { data in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let value = T.convertFromData(data)
if let value = value {
let descompressedValue = self.decompressedImageIfNeeded(value)
dispatch_async(dispatch_get_main_queue(), {
succeed(descompressedValue)
let wrapper = ObjectWrapper(value: descompressedValue)
memoryCache.setObject(wrapper, forKey: key)
})
}
})
}
}
private func fetchAndSet(fetcher: Fetcher<T>, format: Format<T>, failure fail: ((NSError?) -> ())?, success succeed: (T) -> ()) {
fetcher.fetch(failure: { error in
let _ = fail?(error)
}) { value in
self.set(value: value, key: fetcher.key, formatName: format.name, success: succeed)
}
}
private func format(value value: T, format: Format<T>, success succeed: (T) -> ()) {
// HACK: Ideally Cache shouldn't treat images differently but I can't think of any other way of doing this that doesn't complicate the API for other types.
if format.isIdentity && !(value is UIImage) {
succeed(value)
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
var formatted = format.apply(value)
if let formattedImage = formatted as? UIImage {
let originalImage = value as? UIImage
if formattedImage === originalImage {
formatted = self.decompressedImageIfNeeded(formatted)
}
}
dispatch_async(dispatch_get_main_queue()) {
succeed(formatted)
}
}
}
}
private func decompressedImageIfNeeded(value: T) -> T {
if let image = value as? UIImage {
let decompressedImage = image.hnk_decompressedImage() as? T
return decompressedImage!
}
return value
}
private class func buildFetch(failure fail: Fetch<T>.Failer? = nil, success succeed: Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetch = Fetch<T>()
if let succeed = succeed {
fetch.onSuccess(succeed)
}
if let fail = fail {
fetch.onFailure(fail)
}
return fetch
}
// MARK: Convenience fetch
// Ideally we would put each of these in the respective fetcher file as a Cache extension. Unfortunately, this fails to link when using the framework in a project as of Xcode 6.1.
public func fetch(key key: String, @autoclosure(escaping) value getValue : () -> T.Result, formatName: String = HanekeGlobals.Cache.OriginalFormatName, success succeed: Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = SimpleFetcher<T>(key: key, value: getValue)
return self.fetch(fetcher: fetcher, formatName: formatName, success: succeed)
}
public func fetch(path path: String, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail: Fetch<T>.Failer? = nil, success succeed: Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = DiskFetcher<T>(path: path)
return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed)
}
public func fetch(URL URL: NSURL, formatName: String = HanekeGlobals.Cache.OriginalFormatName, failure fail: Fetch<T>.Failer? = nil, success succeed: Fetch<T>.Succeeder? = nil) -> Fetch<T> {
let fetcher = NetworkFetcher<T>(URL: URL)
return self.fetch(fetcher: fetcher, formatName: formatName, failure: fail, success: succeed)
}
}
| mit |
ZulwiyozaPutra/Alien-Adventure-Tutorial | Alien Adventure/MostCommonCharacter.swift | 1 | 1106 | //
// MostCommonCharacter.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
extension Hero {
func mostCommonCharacter(inventory: [UDItem]) -> Character? {
var characters = [Character: Int]()
var mostCommonCharacter: Character? = nil
var mostCommonCharacterOccurance: Int = 0
for item in inventory {
for character in item.name.characters {
if characters[character] == nil {
characters[character] = 1
} else {
characters[character]! += 1
}
}
}
for item in characters {
if item.value >= mostCommonCharacterOccurance {
mostCommonCharacter = item.key
mostCommonCharacterOccurance = item.value
}
}
print("mostCommonCharacter is \(mostCommonCharacter!)")
return mostCommonCharacter
}
}
| mit |
anatoliyv/navigato | Navigato/Classes/SourceApps/NavigatoGoogleMaps.swift | 1 | 617 | //
// NavigatoGoogleMaps.swift
// Navigato
//
// Created by Anatoliy Voropay on 10/26/17.
//
import Foundation
/// Google Maps source app for `Navigato`
public class NavigatoGoogleMaps: NavigatoSourceApp {
public override var name: String {
return "Google Maps"
}
public override func path(forRequest request: Navigato.RequestType) -> String {
switch request {
case .address:
return "comgooglemaps://?saddr="
case .location:
return "comgooglemaps://?center="
case .search:
return "comgooglemaps://?q="
}
}
}
| mit |
wolffan/chatExample | chatExample/simpleChatTests/ChatViewModelTests.swift | 1 | 1402 | //
// ChatViewModelTests.swift
// simpleChat
//
// Created by Raimon Lapuente on 02/11/2016.
// Copyright © 2016 Raimon Lapuente. All rights reserved.
//
import XCTest
@testable import simpleChat
class ChatViewModelTests: 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 testChatViewModelShowsTimeAsUserAndTimeWhenNotmainUser() {
//given
let chat = Chat(username: "user1", content: "random content", userImage: "RandomString", time: "12:43")
let chatViewModel = ChatViewModel.init(chat: chat, username: "Olivia")
//then
XCTAssertEqual(chatViewModel.time, "user1 - 12:43")
XCTAssertFalse(chatViewModel.me)
}
func testChatViewModelShowsTimeOnlyWhenUserIsMe() {
//given
let chat = Chat(username: "user1", content: "random content", userImage: "RandomString", time: "12:43")
let chatViewModel = ChatViewModel.init(chat: chat, username: "user1")
//then
XCTAssertEqual(chatViewModel.time, "12:43")
XCTAssertTrue(chatViewModel.me)
}
}
| mit |
IntrepidPursuits/swift-wisdom | SwiftWisdom/Rx/Rx+DelayElements.swift | 1 | 1064 | //
// Rx+DelayElements.swift
// SwiftWisdom
//
// Created by Son Le on 1/30/17.
// Copyright © 2017 Intrepid. All rights reserved.
//
import RxSwift
extension ObservableType {
/**
Delays elements from the source observable that match a given predicate.
Every other element from the source is emitted immediately upon arrival.
- parameter predicate: A closure that returns true if an element should be delayed.
- parameter delayTime: Time before each matching element is emitted.
- parameter scheduler: Scheduler to run the delay timer on.
- returns: New observable sequence as described.
*/
public func ip_delayElements(
matching predicate: @escaping (E) -> Bool,
by delayTime: RxTimeInterval,
scheduler: SchedulerType = MainScheduler.instance
) -> Observable<E> {
return
Observable.of(
filter(predicate).delay(delayTime, scheduler: scheduler),
filter { !predicate($0) }
)
.merge()
}
}
| mit |
bitboylabs/selluv-ios | selluv-ios/Pods/RealmSwift/RealmSwift/Util.swift | 32 | 4656 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm 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 Foundation
import Realm
// MARK: Internal Helpers
// Swift 3.1 provides fixits for some of our uses of unsafeBitCast
// to use unsafeDowncast instead, but the bitcast is required.
internal func noWarnUnsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
return unsafeBitCast(x, to: type)
}
internal func notFoundToNil(index: UInt) -> Int? {
if index == UInt(NSNotFound) {
return nil
}
return Int(index)
}
internal func throwRealmException(_ message: String, userInfo: [AnyHashable: Any]? = nil) {
NSException(name: NSExceptionName(rawValue: RLMExceptionName), reason: message, userInfo: userInfo).raise()
}
internal func throwForNegativeIndex(_ int: Int, parameterName: String = "index") {
if int < 0 {
throwRealmException("Cannot pass a negative value for '\(parameterName)'.")
}
}
internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? {
let regex = try? NSRegularExpression(pattern: pattern, options: [])
return regex?.stringByReplacingMatches(in: string, options: [],
range: NSRange(location: 0, length: string.utf16.count),
withTemplate: template)
}
extension Object {
// Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject`
// but actually operate on `RLMObjectBase`. Do not expose cast value to user.
internal func unsafeCastToRLMObject() -> RLMObject {
return unsafeBitCast(self, to: RLMObject.self)
}
}
// MARK: CustomObjectiveCBridgeable
internal func dynamicBridgeCast<T>(fromObjectiveC x: Any) -> T {
if let BridgeableType = T.self as? CustomObjectiveCBridgeable.Type {
return BridgeableType.bridging(objCValue: x) as! T
} else {
return x as! T
}
}
internal func dynamicBridgeCast<T>(fromSwift x: T) -> Any {
if let x = x as? CustomObjectiveCBridgeable {
return x.objCValue
} else {
return x
}
}
// Used for conversion from Objective-C types to Swift types
internal protocol CustomObjectiveCBridgeable {
/* FIXME: Remove protocol once SR-2393 bridges all integer types to `NSNumber`
* At this point, use `as! [SwiftType]` to cast between. */
static func bridging(objCValue: Any) -> Self
var objCValue: Any { get }
}
extension Int8: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int8 {
return (objCValue as! NSNumber).int8Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int16: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int16 {
return (objCValue as! NSNumber).int16Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int32: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int32 {
return (objCValue as! NSNumber).int32Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int64: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int64 {
return (objCValue as! NSNumber).int64Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Optional: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Optional {
if objCValue is NSNull {
return nil
} else {
return .some(dynamicBridgeCast(fromObjectiveC: objCValue))
}
}
var objCValue: Any {
if let value = self {
return value
} else {
return NSNull()
}
}
}
// MARK: AssistedObjectiveCBridgeable
internal protocol AssistedObjectiveCBridgeable {
static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self
var bridged: (objectiveCValue: Any, metadata: Any?) { get }
}
| mit |
lightsprint09/LADVSwift | LADVSwift/ResultAttachment+JSONDecodeable.swift | 1 | 561 | //
// ResultAttachment+JSONDecodeable.swift
// LADVSwift
//
// Created by Lukas Schmidt on 01.06.17.
// Copyright © 2017 freiraum. All rights reserved.
//
import Foundation
extension ResultAttachement: JSONCodable {
public init(object: JSONObject) throws {
let decoder = JSONDecoder(object: object)
name = try decoder.decode("name")
let urlString: String = try decoder.decode("url")
url = URL(string: urlString)!
fileType = try decoder.decode("type")
obsolete = try decoder.decode("obsolete")
}
}
| mit |
AirHelp/Mimus | Tests/MimusTests/MatcherExtensionsTests.swift | 1 | 1259 | //
// MatcherExtensionsTests.swift
// Mimus
//
// Created by Pawel Dudek on 14/08/2017.
// Copyright © 2017 AirHelp. All rights reserved.
//
import XCTest
import Mimus
struct User: Equatable {
let firstName: String
let lastName: String
let id: String
}
class MatcherExtensionsTests: XCTestCase {
func testPassingMatcher() {
let firstUser = User(firstName: "Fixture First Name", lastName: "Fixture Last Name", id: "42")
let secondUser = User(firstName: "Fixture First Name", lastName: "Fixture Last Name", id: "42")
XCTAssertTrue(firstUser.matches(argument: secondUser), "Expected users to match")
}
func testFailingMatcher() {
let firstUser = User(firstName: "Fixture First Name", lastName: "Fixture Last Name", id: "42")
let secondUser = User(firstName: "Fixture First Name", lastName: "Fixture Last Name", id: "43")
XCTAssertFalse(firstUser.matches(argument: secondUser), "Expected users to match")
}
}
extension User: Matcher {
func matches(argument: Any?) -> Bool {
return compare(other: argument as? User)
}
}
func ==(lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id && lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
}
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/View/DefaultCompositionalNewsSceneFactory.swift | 1 | 236 | import UIKit
struct DefaultCompositionalNewsSceneFactory: CompositionalNewsSceneFactory {
func makeCompositionalNewsScene() -> UIViewController & CompositionalNewsScene {
CompositionalNewsViewController()
}
}
| mit |
theappbusiness/TABScrollingContentView | Pods/TABSwiftLayout/Sources/Deprecations.swift | 1 | 4780 | //
// Deprecations.swift
// TABSwiftLayout
//
// Created by Daniela Bulgaru on 13/09/2016.
// Copyright © 2016 TheAppBusiness. All rights reserved.
//
import Foundation
extension View {
@available(*, deprecated:2.0.0, renamed: "pin(edges:toView:relation:margins:priority:)")
public func pin(_ edges: EdgeMask, toView view: View, relation: NSLayoutRelation = .equal, margins: EdgeMargins = EdgeMargins(), priority: LayoutPriority = LayoutPriorityRequired) -> [NSLayoutConstraint] {
return pin(edges: edges, toView: view, relation: relation, margins: margins, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "pin(edge:toEdge:ofView:relation:margin:priority:)")
public func pin(_ edge: Edge, toEdge: Edge, ofView view: View, relation: NSLayoutRelation = .equal, margin: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return pin(edge: edge, toEdge: toEdge, ofView: view, relation: relation, margin: margin, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "align(axis:relativeTo:offset:priority:)")
public func align(_ axis: Axis, relativeTo view: View, offset: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return align(axis: axis, relativeTo: view, offset: offset, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "size(axis:ofViews:ratio:priority:)")
public func size(_ axis: Axis, ofViews views: [View], ratio: CGFloat = 1, priority: LayoutPriority = LayoutPriorityRequired) -> [NSLayoutConstraint] {
return size(axis: axis, ofViews: views, ratio: ratio, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "size(axis:relatedBy:size:priority:)")
public func size(_ axis: Axis, relatedBy relation: NSLayoutRelation, size: CGFloat, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return self.size(axis: axis, relatedBy: relation, size: size, priority: priority)
}
@available(*, deprecated:2.0.0, renamed: "size(axis:relativeTo:ofView:ratio:priority:)")
public func size(_ axis: Axis, relativeTo otherAxis: Axis, ofView view: View, ratio: CGFloat = 1, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return size(axis: axis, relativeTo: otherAxis, ofView: view, ratio: ratio, priority: priority)
}
}
extension View {
@available(*, deprecated:2.0.0, renamed: "alignEdges(edges:toView:)")
public func alignEdges(_ edges: EdgeMask, toView: View) {
align(edges: edges, toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignTop(toView:)")
public func alignTop(_ toView: View) -> NSLayoutConstraint {
return alignTop(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignLeft(toView:)")
public func alignLeft(_ toView: View) -> NSLayoutConstraint {
return alignLeft(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignBottom(toView:)")
public func alignBottom(_ toView: View) -> NSLayoutConstraint {
return alignBottom(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignRight(toView:)")
public func alignRight(_ toView: View) -> NSLayoutConstraint {
return alignRight(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignHorizontally(toView:)")
public func alignHorizontally(_ toView: View) -> NSLayoutConstraint {
return alignHorizontally(toView: toView)
}
@available(*, deprecated:2.0.0, renamed: "alignVertically(toView:)")
public func alignVertically(_ toView: View) -> NSLayoutConstraint {
return alignVertically(toView: toView)
}
}
extension View {
@available(*, deprecated: 1.0, obsoleted: 1.1, renamed: "align") public func center(_ axis: Axis, relativeTo view: View, offset: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired) -> NSLayoutConstraint {
return align(axis, relativeTo: view, offset: offset, priority: priority)
}
@available(*, deprecated: 1.0, obsoleted: 1.1, renamed: "alignVertically") public func centerVertically(toView: View) -> NSLayoutConstraint {
return alignVertically(toView: toView)
}
@available(*, deprecated: 1.0, obsoleted: 1.1, renamed: "alignHorizontally") public func centerHorizontally(toView: View) -> NSLayoutConstraint {
return alignHorizontally(toView: toView)
}
}
public extension View {
@available(*, deprecated:2.0.0, renamed: "constraints(forTrait:)")
public func constraintsForTrait(_ trait: ConstraintsTraitMask) -> [NSLayoutConstraint] {
return constraints(forTrait: trait)
}
@available(*, deprecated:2.0.0, renamed: "contains(trait:)")
public func containsTraits(_ trait: ConstraintsTraitMask) -> Bool {
return contains(trait: trait)
}
}
| mit |
ello/ello-ios | Sources/Controllers/Stream/ResponderChainableController.swift | 1 | 165 | ////
/// ResponderChainableController.swift
//
struct ResponderChainableController {
weak var controller: UIViewController?
var next: () -> UIResponder?
}
| mit |
austinzheng/swift-compiler-crashes | fixed/01434-std-function-func-swift-typebase-gettypevariables.swift | 11 | 210 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum A{let a=h>(}protocol e:A{typealias A | mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/03062-swift-sourcemanager-getmessage.swift | 11 | 369 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let f = {
case c,
let i(f: a {
protocol A : e : Int -> () {
class a {
protocol P {
let t: a {
}
struct Q<T: Int -> U)"""\() {
println(f: b: e
return "[1)
println() {
func f: Int -> () {
class
case c,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/12495-swift-sourcemanager-getmessage.swift | 11 | 269 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g { {
let a {
extension String {
struct A {
var d = a( [ {
class A {
protocol P {
class
case ,
| mit |
bitrise-io/sample-test-ios-quick | BitriseTestingSample/BitriseTestingSample/ConnectionHelper.swift | 2 | 841 | //
// ConnectionHelper.swift
// BitriseTestingSample
//
// Created by Tamás Bazsonyi on 6/19/15.
// Copyright (c) 2015 Bitrise. All rights reserved.
//
import UIKit
class ConnectionHelper: NSObject {
static func pingServer() -> Bool {
let urlPath: String = "http://google.com"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url)
var response: NSURLResponse?
var error: NSError?
let urlData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)
if let httpResponse = response as? NSHTTPURLResponse {
if(httpResponse.statusCode == 200)
{
return true
} else {
return false
}
}
return false
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/18261-no-stacktrace.swift | 11 | 312 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum A {
protocol A {
{
}
let end = {
{
{
{
}
}
}
{
{
}
case
{
struct A {
{
}
{
{
}
{
}
}
let h = {
{
( [ {
let a {
{
{
{
{
{
}
}
class
case ,
| mit |
hollance/swift-algorithm-club | Tree/Tree.playground/Contents.swift | 3 | 1442 | //: Playground - noun: a place where people can play
let tree = TreeNode<String>(value: "beverages")
let hotNode = TreeNode<String>(value: "hot")
let coldNode = TreeNode<String>(value: "cold")
let teaNode = TreeNode<String>(value: "tea")
let coffeeNode = TreeNode<String>(value: "coffee")
let chocolateNode = TreeNode<String>(value: "cocoa")
let blackTeaNode = TreeNode<String>(value: "black")
let greenTeaNode = TreeNode<String>(value: "green")
let chaiTeaNode = TreeNode<String>(value: "chai")
let sodaNode = TreeNode<String>(value: "soda")
let milkNode = TreeNode<String>(value: "milk")
let gingerAleNode = TreeNode<String>(value: "ginger ale")
let bitterLemonNode = TreeNode<String>(value: "bitter lemon")
tree.addChild(hotNode)
tree.addChild(coldNode)
hotNode.addChild(teaNode)
hotNode.addChild(coffeeNode)
hotNode.addChild(chocolateNode)
coldNode.addChild(sodaNode)
coldNode.addChild(milkNode)
teaNode.addChild(blackTeaNode)
teaNode.addChild(greenTeaNode)
teaNode.addChild(chaiTeaNode)
sodaNode.addChild(gingerAleNode)
sodaNode.addChild(bitterLemonNode)
tree
teaNode.parent
teaNode.parent!.parent
extension TreeNode where T: Equatable {
func search(_ value: T) -> TreeNode? {
if value == self.value {
return self
}
for child in children {
if let found = child.search(value) {
return found
}
}
return nil
}
}
tree.search("cocoa")
tree.search("chai")
tree.search("bubbly")
| mit |
emilstahl/swift | validation-test/compiler_crashers_fixed/0261-swift-parser-parseexprpostfix.swift | 13 | 346 | // 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
func h(f: Int = j) {
}
let i = h
i() -> f {
{
func e(#i: d, g: d) {
for f in h {
f.i(i, g)
} }
| apache-2.0 |
idomizrachi/Regen | regen/Images/ImagesClassGeneratorSwift.swift | 1 | 2309 | //
// ImagesClassGeneratorSwift.swift
// regen
//
// Created by Ido Mizrachi on 5/10/17.
//
import Foundation
class ImagesClassGeneratorSwift: ImagesClassGenerator {
func generateClass(fromImagesTree imagesTree: Tree<ImageNodeItem>, generatedFile: String) {
Logger.debug("\tGenerating images swift class: started")
let filename = generatedFile + ".swift"
var file = ""
FileUtils.deleteFileAt(filePath: filename)
let className = String(NSString(string: generatedFile).lastPathComponent)
file += "import Foundation\n\n"
for folder in imagesTree.children {
generateClassX(node: folder, file: &file)
}
file += "\n"
file += "class \(className) {\n"
file += " static let shared = \(className)()\n"
file += " private init() {}\n"
file += "\n"
generateFoldersProperties(node: imagesTree, file: &file)
file += "\n"
generateAssetsProperties(node: imagesTree, file: &file)
file += "}\n"
FileUtils.append(filePath: filename, content: file)
Logger.debug("\tGenerating images swift class: finished")
Logger.info("\tCreated: \(filename)")
}
func generateClassX(node: TreeNode<ImageNodeItem>, file: inout String) {
for folder in node.children {
generateClassX(node: folder, file: &file)
}
file += "class \(node.item.folderClass) {\n\n"
generateFoldersProperties(node: node, file: &file)
if (node.children.count > 0) {
file += "\n"
}
generateAssetsProperties(node: node, file: &file)
file += "}\n"
}
func generateFoldersProperties(node: TreeNode<ImageNodeItem>, file: inout String) {
for folder in node.children {
file += " let \(folder.item.folder.propertyName()) = \(folder.item.folderClass)()\n"
}
}
func generateAssetsProperties(node: TreeNode<ImageNodeItem>, file: inout String) {
for image in node.item.images {
file += " let \(image.propertyName) = \"\(image.name)\"\n"
}
}
}
| mit |
maxoll90/FSwift | ios8-example/FSwift-Sample/Pods/FSwift/FSwift/Time/Timer.swift | 3 | 1198 | //
// Timer.swift
// FSwift
//
// Created by Kelton Person on 10/4/14.
// Copyright (c) 2014 Kelton. All rights reserved.
//
import Foundation
public class Timer {
let interval: NSTimeInterval
let repeats: Bool
let f: (Timer) -> Void
var isRunning: Bool = false
private var timer: NSTimer?
public init(interval: NSTimeInterval, repeats: Bool, f: (Timer) -> Void) {
self.interval = interval
self.repeats = repeats
self.f = f
}
@objc func tick() {
if self.timer != nil {
self.f(self)
}
if !self.repeats {
self.stop()
}
}
public func start() {
if self.timer == nil {
self.timer = NSTimer(timeInterval: interval, target:self, selector: Selector("tick"), userInfo: nil, repeats: repeats)
NSRunLoop.currentRunLoop().addTimer(self.timer!, forMode: NSDefaultRunLoopMode)
self.isRunning = true
}
}
public func stop() {
self.timer?.invalidate()
self.timer = nil
self.isRunning = false
}
public var running: Bool {
return self.isRunning
}
}
| mit |
ChristianKienle/highway | Sources/HWKit/Command Helper/XCProjectGenerator.swift | 1 | 1044 | import HighwayCore
import ZFile
import Url
// MARK: - Types
public typealias GeneratedXCProject = SwiftPackageTool.XCProjectOptions
public class XCProjectGenerator {
// MARK: - Init
public init(context: Context, bundle: HighwayBundle) {
self.context = context
self.bundle = bundle
}
// MARK: - Properties
public let context: Context
public let bundle: HighwayBundle
// MARK: - Command
public func generate() throws -> FolderProtocol {
let swift_package = SwiftPackageTool(context: context)
let xcconfigName = bundle.configuration.xcconfigName
let projectUrl = try bundle.xcodeprojectUrl()
let options = SwiftPackageTool.XCProjectOptions(swiftProjectDirectory: bundle.url,
xcprojectDestinationDirectory: projectUrl,
xcconfigFileName: xcconfigName)
try swift_package.generateXcodeproj(with: options)
return projectUrl
}
}
| mit |
SuperAwesomeLTD/sa-mobile-sdk-ios | Example/SuperAwesomeExampleTests/Common/Mocks/MoatRepositoryMock.swift | 1 | 596 | //
// MoatRepositoryMock.swift
// SuperAwesome-Unit-Full-Tests
//
// Created by Gunhan Sancar on 28/10/2020.
//
import WebKit
import AVKit
@testable import SuperAwesome
struct MoatRepositoryMock: MoatRepositoryType {
func startMoatTracking(forDisplay webView: WKWebView?) -> String? {
""
}
func stopMoatTrackingForDisplay() -> Bool {
true
}
func startMoatTracking(forVideoPlayer player: AVPlayer?, with layer: AVPlayerLayer?, andView view: UIView?) -> Bool {
true
}
func stopMoatTrackingForVideoPlayer() -> Bool {
true
}
}
| lgpl-3.0 |
zbw209/- | StudyNotes/Pods/Alamofire/Source/AFError.swift | 5 | 36558 | //
// AFError.swift
//
// Copyright (c) 2014-2018 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
/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
/// their own associated reasons.
public enum AFError: Error {
/// The underlying reason the `.multipartEncodingFailed` error occurred.
public enum MultipartEncodingFailureReason {
/// The `fileURL` provided for reading an encodable body part isn't a file `URL`.
case bodyPartURLInvalid(url: URL)
/// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension.
case bodyPartFilenameInvalid(in: URL)
/// The file at the `fileURL` provided was not reachable.
case bodyPartFileNotReachable(at: URL)
/// Attempting to check the reachability of the `fileURL` provided threw an error.
case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
/// The file at the `fileURL` provided is actually a directory.
case bodyPartFileIsDirectory(at: URL)
/// The size of the file at the `fileURL` provided was not returned by the system.
case bodyPartFileSizeNotAvailable(at: URL)
/// The attempt to find the size of the file at the `fileURL` provided threw an error.
case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
/// An `InputStream` could not be created for the provided `fileURL`.
case bodyPartInputStreamCreationFailed(for: URL)
/// An `OutputStream` could not be created when attempting to write the encoded data to disk.
case outputStreamCreationFailed(for: URL)
/// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`.
case outputStreamFileAlreadyExists(at: URL)
/// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`.
case outputStreamURLInvalid(url: URL)
/// The attempt to write the encoded body data to disk failed with an underlying error.
case outputStreamWriteFailed(error: Error)
/// The attempt to read an encoded body part `InputStream` failed with underlying system error.
case inputStreamReadFailed(error: Error)
}
/// The underlying reason the `.parameterEncodingFailed` error occurred.
public enum ParameterEncodingFailureReason {
/// The `URLRequest` did not have a `URL` to encode.
case missingURL
/// JSON serialization failed with an underlying system error during the encoding process.
case jsonEncodingFailed(error: Error)
/// Custom parameter encoding failed due to the associated `Error`.
case customEncodingFailed(error: Error)
}
/// The underlying reason the `.parameterEncoderFailed` error occurred.
public enum ParameterEncoderFailureReason {
/// Possible missing components.
public enum RequiredComponent {
/// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding.
case url
/// The `HTTPMethod` could not be extracted from the passed `URLRequest`.
case httpMethod(rawValue: String)
}
/// A `RequiredComponent` was missing during encoding.
case missingRequiredComponent(RequiredComponent)
/// The underlying encoder failed with the associated error.
case encoderFailed(error: Error)
}
/// The underlying reason the `.responseValidationFailed` error occurred.
public enum ResponseValidationFailureReason {
/// The data file containing the server response did not exist.
case dataFileNil
/// The data file containing the server response at the associated `URL` could not be read.
case dataFileReadFailed(at: URL)
/// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a
/// wildcard type.
case missingContentType(acceptableContentTypes: [String])
/// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`.
case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
/// The response status code was not acceptable.
case unacceptableStatusCode(code: Int)
/// Custom response validation failed due to the associated `Error`.
case customValidationFailed(error: Error)
}
/// The underlying reason the response serialization error occurred.
public enum ResponseSerializationFailureReason {
/// The server response contained no data or the data was zero length.
case inputDataNilOrZeroLength
/// The file containing the server response did not exist.
case inputFileNil
/// The file containing the server response could not be read from the associated `URL`.
case inputFileReadFailed(at: URL)
/// String serialization failed using the provided `String.Encoding`.
case stringSerializationFailed(encoding: String.Encoding)
/// JSON serialization failed with an underlying system error.
case jsonSerializationFailed(error: Error)
/// A `DataDecoder` failed to decode the response due to the associated `Error`.
case decodingFailed(error: Error)
/// A custom response serializer failed due to the associated `Error`.
case customSerializationFailed(error: Error)
/// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type.
case invalidEmptyResponse(type: String)
}
/// Underlying reason a server trust evaluation error occurred.
public enum ServerTrustFailureReason {
/// The output of a server trust evaluation.
public struct Output {
/// The host for which the evaluation was performed.
public let host: String
/// The `SecTrust` value which was evaluated.
public let trust: SecTrust
/// The `OSStatus` of evaluation operation.
public let status: OSStatus
/// The result of the evaluation operation.
public let result: SecTrustResultType
/// Creates an `Output` value from the provided values.
init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) {
self.host = host
self.trust = trust
self.status = status
self.result = result
}
}
/// No `ServerTrustEvaluator` was found for the associated host.
case noRequiredEvaluator(host: String)
/// No certificates were found with which to perform the trust evaluation.
case noCertificatesFound
/// No public keys were found with which to perform the trust evaluation.
case noPublicKeysFound
/// During evaluation, application of the associated `SecPolicy` failed.
case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus)
/// During evaluation, setting the associated anchor certificates failed.
case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate])
/// During evaluation, creation of the revocation policy failed.
case revocationPolicyCreationFailed
/// `SecTrust` evaluation failed with the associated `Error`, if one was produced.
case trustEvaluationFailed(error: Error?)
/// Default evaluation failed with the associated `Output`.
case defaultEvaluationFailed(output: Output)
/// Host validation failed with the associated `Output`.
case hostValidationFailed(output: Output)
/// Revocation check failed with the associated `Output` and options.
case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options)
/// Certificate pinning failed.
case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate])
/// Public key pinning failed.
case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey])
/// Custom server trust evaluation failed due to the associated `Error`.
case customEvaluationFailed(error: Error)
}
/// The underlying reason the `.urlRequestValidationFailed`
public enum URLRequestValidationFailureReason {
/// URLRequest with GET method had body data.
case bodyDataInGETRequest(Data)
}
/// `UploadableConvertible` threw an error in `createUploadable()`.
case createUploadableFailed(error: Error)
/// `URLRequestConvertible` threw an error in `asURLRequest()`.
case createURLRequestFailed(error: Error)
/// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL.
case downloadedFileMoveFailed(error: Error, source: URL, destination: URL)
/// `Request` was explicitly cancelled.
case explicitlyCancelled
/// `URLConvertible` type failed to create a valid `URL`.
case invalidURL(url: URLConvertible)
/// Multipart form encoding failed.
case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
/// `ParameterEncoding` threw an error during the encoding process.
case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
/// `ParameterEncoder` threw an error while running the encoder.
case parameterEncoderFailed(reason: ParameterEncoderFailureReason)
/// `RequestAdapter` threw an error during adaptation.
case requestAdaptationFailed(error: Error)
/// `RequestRetrier` threw an error during the request retry process.
case requestRetryFailed(retryError: Error, originalError: Error)
/// Response validation failed.
case responseValidationFailed(reason: ResponseValidationFailureReason)
/// Response serialization failed.
case responseSerializationFailed(reason: ResponseSerializationFailureReason)
/// `ServerTrustEvaluating` instance threw an error during trust evaluation.
case serverTrustEvaluationFailed(reason: ServerTrustFailureReason)
/// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope.
case sessionDeinitialized
/// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`.
case sessionInvalidated(error: Error?)
/// `URLSessionTask` completed with error.
case sessionTaskFailed(error: Error)
/// `URLRequest` failed validation.
case urlRequestValidationFailed(reason: URLRequestValidationFailureReason)
}
extension Error {
/// Returns the instance cast as an `AFError`.
public var asAFError: AFError? {
return self as? AFError
}
/// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown.
public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError {
guard let afError = self as? AFError else {
fatalError(message(), file: file, line: line)
}
return afError
}
/// Casts the instance as `AFError` or returns `defaultAFError`
func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError {
return self as? AFError ?? defaultAFError()
}
}
// MARK: - Error Booleans
extension AFError {
/// Returns whether the instance is `.sessionDeinitialized`.
public var isSessionDeinitializedError: Bool {
if case .sessionDeinitialized = self { return true }
return false
}
/// Returns whether the instance is `.sessionInvalidated`.
public var isSessionInvalidatedError: Bool {
if case .sessionInvalidated = self { return true }
return false
}
/// Returns whether the instance is `.explicitlyCancelled`.
public var isExplicitlyCancelledError: Bool {
if case .explicitlyCancelled = self { return true }
return false
}
/// Returns whether the instance is `.invalidURL`.
public var isInvalidURLError: Bool {
if case .invalidURL = self { return true }
return false
}
/// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isParameterEncodingError: Bool {
if case .parameterEncodingFailed = self { return true }
return false
}
/// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isParameterEncoderError: Bool {
if case .parameterEncoderFailed = self { return true }
return false
}
/// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError`
/// properties will contain the associated values.
public var isMultipartEncodingError: Bool {
if case .multipartEncodingFailed = self { return true }
return false
}
/// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isRequestAdaptationError: Bool {
if case .requestAdaptationFailed = self { return true }
return false
}
/// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values.
public var isResponseValidationError: Bool {
if case .responseValidationFailed = self { return true }
return false
}
/// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and
/// `underlyingError` properties will contain the associated values.
public var isResponseSerializationError: Bool {
if case .responseSerializationFailed = self { return true }
return false
}
/// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isServerTrustEvaluationError: Bool {
if case .serverTrustEvaluationFailed = self { return true }
return false
}
/// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isRequestRetryError: Bool {
if case .requestRetryFailed = self { return true }
return false
}
/// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isCreateUploadableError: Bool {
if case .createUploadableFailed = self { return true }
return false
}
/// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isCreateURLRequestError: Bool {
if case .createURLRequestFailed = self { return true }
return false
}
/// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will
/// contain the associated values.
public var isDownloadedFileMoveError: Bool {
if case .downloadedFileMoveFailed = self { return true }
return false
}
/// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isSessionTaskError: Bool {
if case .sessionTaskFailed = self { return true }
return false
}
}
// MARK: - Convenience Properties
extension AFError {
/// The `URLConvertible` associated with the error.
public var urlConvertible: URLConvertible? {
guard case let .invalidURL(url) = self else { return nil }
return url
}
/// The `URL` associated with the error.
public var url: URL? {
guard case let .multipartEncodingFailed(reason) = self else { return nil }
return reason.url
}
/// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`,
/// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`,
/// `.responseSerializationFailed`, `.requestRetryFailed` errors.
public var underlyingError: Error? {
switch self {
case let .multipartEncodingFailed(reason):
return reason.underlyingError
case let .parameterEncodingFailed(reason):
return reason.underlyingError
case let .parameterEncoderFailed(reason):
return reason.underlyingError
case let .requestAdaptationFailed(error):
return error
case let .requestRetryFailed(retryError, _):
return retryError
case let .responseValidationFailed(reason):
return reason.underlyingError
case let .responseSerializationFailed(reason):
return reason.underlyingError
case let .serverTrustEvaluationFailed(reason):
return reason.underlyingError
case let .sessionInvalidated(error):
return error
case let .createUploadableFailed(error):
return error
case let .createURLRequestFailed(error):
return error
case let .downloadedFileMoveFailed(error, _, _):
return error
case let .sessionTaskFailed(error):
return error
case .explicitlyCancelled,
.invalidURL,
.sessionDeinitialized,
.urlRequestValidationFailed:
return nil
}
}
/// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
public var acceptableContentTypes: [String]? {
guard case let .responseValidationFailed(reason) = self else { return nil }
return reason.acceptableContentTypes
}
/// The response `Content-Type` of a `.responseValidationFailed` error.
public var responseContentType: String? {
guard case let .responseValidationFailed(reason) = self else { return nil }
return reason.responseContentType
}
/// The response code of a `.responseValidationFailed` error.
public var responseCode: Int? {
guard case let .responseValidationFailed(reason) = self else { return nil }
return reason.responseCode
}
/// The `String.Encoding` associated with a failed `.stringResponse()` call.
public var failedStringEncoding: String.Encoding? {
guard case let .responseSerializationFailed(reason) = self else { return nil }
return reason.failedStringEncoding
}
/// The `source` URL of a `.downloadedFileMoveFailed` error.
public var sourceURL: URL? {
guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil }
return source
}
/// The `destination` URL of a `.downloadedFileMoveFailed` error.
public var destinationURL: URL? {
guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil }
return destination
}
}
extension AFError.ParameterEncodingFailureReason {
var underlyingError: Error? {
switch self {
case let .jsonEncodingFailed(error),
let .customEncodingFailed(error):
return error
case .missingURL:
return nil
}
}
}
extension AFError.ParameterEncoderFailureReason {
var underlyingError: Error? {
switch self {
case let .encoderFailed(error):
return error
case .missingRequiredComponent:
return nil
}
}
}
extension AFError.MultipartEncodingFailureReason {
var url: URL? {
switch self {
case let .bodyPartURLInvalid(url),
let .bodyPartFilenameInvalid(url),
let .bodyPartFileNotReachable(url),
let .bodyPartFileIsDirectory(url),
let .bodyPartFileSizeNotAvailable(url),
let .bodyPartInputStreamCreationFailed(url),
let .outputStreamCreationFailed(url),
let .outputStreamFileAlreadyExists(url),
let .outputStreamURLInvalid(url),
let .bodyPartFileNotReachableWithError(url, _),
let .bodyPartFileSizeQueryFailedWithError(url, _):
return url
case .outputStreamWriteFailed,
.inputStreamReadFailed:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .bodyPartFileNotReachableWithError(_, error),
let .bodyPartFileSizeQueryFailedWithError(_, error),
let .outputStreamWriteFailed(error),
let .inputStreamReadFailed(error):
return error
case .bodyPartURLInvalid,
.bodyPartFilenameInvalid,
.bodyPartFileNotReachable,
.bodyPartFileIsDirectory,
.bodyPartFileSizeNotAvailable,
.bodyPartInputStreamCreationFailed,
.outputStreamCreationFailed,
.outputStreamFileAlreadyExists,
.outputStreamURLInvalid:
return nil
}
}
}
extension AFError.ResponseValidationFailureReason {
var acceptableContentTypes: [String]? {
switch self {
case let .missingContentType(types),
let .unacceptableContentType(types, _):
return types
case .dataFileNil,
.dataFileReadFailed,
.unacceptableStatusCode,
.customValidationFailed:
return nil
}
}
var responseContentType: String? {
switch self {
case let .unacceptableContentType(_, responseType):
return responseType
case .dataFileNil,
.dataFileReadFailed,
.missingContentType,
.unacceptableStatusCode,
.customValidationFailed:
return nil
}
}
var responseCode: Int? {
switch self {
case let .unacceptableStatusCode(code):
return code
case .dataFileNil,
.dataFileReadFailed,
.missingContentType,
.unacceptableContentType,
.customValidationFailed:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .customValidationFailed(error):
return error
case .dataFileNil,
.dataFileReadFailed,
.missingContentType,
.unacceptableContentType,
.unacceptableStatusCode:
return nil
}
}
}
extension AFError.ResponseSerializationFailureReason {
var failedStringEncoding: String.Encoding? {
switch self {
case let .stringSerializationFailed(encoding):
return encoding
case .inputDataNilOrZeroLength,
.inputFileNil,
.inputFileReadFailed(_),
.jsonSerializationFailed(_),
.decodingFailed(_),
.customSerializationFailed(_),
.invalidEmptyResponse:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .jsonSerializationFailed(error),
let .decodingFailed(error),
let .customSerializationFailed(error):
return error
case .inputDataNilOrZeroLength,
.inputFileNil,
.inputFileReadFailed,
.stringSerializationFailed,
.invalidEmptyResponse:
return nil
}
}
}
extension AFError.ServerTrustFailureReason {
var output: AFError.ServerTrustFailureReason.Output? {
switch self {
case let .defaultEvaluationFailed(output),
let .hostValidationFailed(output),
let .revocationCheckFailed(output, _):
return output
case .noRequiredEvaluator,
.noCertificatesFound,
.noPublicKeysFound,
.policyApplicationFailed,
.settingAnchorCertificatesFailed,
.revocationPolicyCreationFailed,
.trustEvaluationFailed,
.certificatePinningFailed,
.publicKeyPinningFailed,
.customEvaluationFailed:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .customEvaluationFailed(error):
return error
case let .trustEvaluationFailed(error):
return error
case .noRequiredEvaluator,
.noCertificatesFound,
.noPublicKeysFound,
.policyApplicationFailed,
.settingAnchorCertificatesFailed,
.revocationPolicyCreationFailed,
.defaultEvaluationFailed,
.hostValidationFailed,
.revocationCheckFailed,
.certificatePinningFailed,
.publicKeyPinningFailed:
return nil
}
}
}
// MARK: - Error Descriptions
extension AFError: LocalizedError {
public var errorDescription: String? {
switch self {
case .explicitlyCancelled:
return "Request explicitly cancelled."
case let .invalidURL(url):
return "URL is not valid: \(url)"
case let .parameterEncodingFailed(reason):
return reason.localizedDescription
case let .parameterEncoderFailed(reason):
return reason.localizedDescription
case let .multipartEncodingFailed(reason):
return reason.localizedDescription
case let .requestAdaptationFailed(error):
return "Request adaption failed with error: \(error.localizedDescription)"
case let .responseValidationFailed(reason):
return reason.localizedDescription
case let .responseSerializationFailed(reason):
return reason.localizedDescription
case let .requestRetryFailed(retryError, originalError):
return """
Request retry failed with retry error: \(retryError.localizedDescription), \
original error: \(originalError.localizedDescription)
"""
case .sessionDeinitialized:
return """
Session was invalidated without error, so it was likely deinitialized unexpectedly. \
Be sure to retain a reference to your Session for the duration of your requests.
"""
case let .sessionInvalidated(error):
return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")"
case let .serverTrustEvaluationFailed(reason):
return "Server trust evaluation failed due to reason: \(reason.localizedDescription)"
case let .urlRequestValidationFailed(reason):
return "URLRequest validation failed due to reason: \(reason.localizedDescription)"
case let .createUploadableFailed(error):
return "Uploadable creation failed with error: \(error.localizedDescription)"
case let .createURLRequestFailed(error):
return "URLRequest creation failed with error: \(error.localizedDescription)"
case let .downloadedFileMoveFailed(error, source, destination):
return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)"
case let .sessionTaskFailed(error):
return "URLSessionTask failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.ParameterEncodingFailureReason {
var localizedDescription: String {
switch self {
case .missingURL:
return "URL request to encode was missing a URL"
case let .jsonEncodingFailed(error):
return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
case let .customEncodingFailed(error):
return "Custom parameter encoder failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.ParameterEncoderFailureReason {
var localizedDescription: String {
switch self {
case let .missingRequiredComponent(component):
return "Encoding failed due to a missing request component: \(component)"
case let .encoderFailed(error):
return "The underlying encoder failed with the error: \(error)"
}
}
}
extension AFError.MultipartEncodingFailureReason {
var localizedDescription: String {
switch self {
case let .bodyPartURLInvalid(url):
return "The URL provided is not a file URL: \(url)"
case let .bodyPartFilenameInvalid(url):
return "The URL provided does not have a valid filename: \(url)"
case let .bodyPartFileNotReachable(url):
return "The URL provided is not reachable: \(url)"
case let .bodyPartFileNotReachableWithError(url, error):
return """
The system returned an error while checking the provided URL for reachability.
URL: \(url)
Error: \(error)
"""
case let .bodyPartFileIsDirectory(url):
return "The URL provided is a directory: \(url)"
case let .bodyPartFileSizeNotAvailable(url):
return "Could not fetch the file size from the provided URL: \(url)"
case let .bodyPartFileSizeQueryFailedWithError(url, error):
return """
The system returned an error while attempting to fetch the file size from the provided URL.
URL: \(url)
Error: \(error)
"""
case let .bodyPartInputStreamCreationFailed(url):
return "Failed to create an InputStream for the provided URL: \(url)"
case let .outputStreamCreationFailed(url):
return "Failed to create an OutputStream for URL: \(url)"
case let .outputStreamFileAlreadyExists(url):
return "A file already exists at the provided URL: \(url)"
case let .outputStreamURLInvalid(url):
return "The provided OutputStream URL is invalid: \(url)"
case let .outputStreamWriteFailed(error):
return "OutputStream write failed with error: \(error)"
case let .inputStreamReadFailed(error):
return "InputStream read failed with error: \(error)"
}
}
}
extension AFError.ResponseSerializationFailureReason {
var localizedDescription: String {
switch self {
case .inputDataNilOrZeroLength:
return "Response could not be serialized, input data was nil or zero length."
case .inputFileNil:
return "Response could not be serialized, input file was nil."
case let .inputFileReadFailed(url):
return "Response could not be serialized, input file could not be read: \(url)."
case let .stringSerializationFailed(encoding):
return "String could not be serialized with encoding: \(encoding)."
case let .jsonSerializationFailed(error):
return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
case let .invalidEmptyResponse(type):
return """
Empty response could not be serialized to type: \(type). \
Use Empty as the expected type for such responses.
"""
case let .decodingFailed(error):
return "Response could not be decoded because of error:\n\(error.localizedDescription)"
case let .customSerializationFailed(error):
return "Custom response serializer failed with error:\n\(error.localizedDescription)"
}
}
}
extension AFError.ResponseValidationFailureReason {
var localizedDescription: String {
switch self {
case .dataFileNil:
return "Response could not be validated, data file was nil."
case let .dataFileReadFailed(url):
return "Response could not be validated, data file could not be read: \(url)."
case let .missingContentType(types):
return """
Response Content-Type was missing and acceptable content types \
(\(types.joined(separator: ","))) do not match "*/*".
"""
case let .unacceptableContentType(acceptableTypes, responseType):
return """
Response Content-Type "\(responseType)" does not match any acceptable types: \
\(acceptableTypes.joined(separator: ",")).
"""
case let .unacceptableStatusCode(code):
return "Response status code was unacceptable: \(code)."
case let .customValidationFailed(error):
return "Custom response validation failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.ServerTrustFailureReason {
var localizedDescription: String {
switch self {
case let .noRequiredEvaluator(host):
return "A ServerTrustEvaluating value is required for host \(host) but none was found."
case .noCertificatesFound:
return "No certificates were found or provided for evaluation."
case .noPublicKeysFound:
return "No public keys were found or provided for evaluation."
case .policyApplicationFailed:
return "Attempting to set a SecPolicy failed."
case .settingAnchorCertificatesFailed:
return "Attempting to set the provided certificates as anchor certificates failed."
case .revocationPolicyCreationFailed:
return "Attempting to create a revocation policy failed."
case let .trustEvaluationFailed(error):
return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")"
case let .defaultEvaluationFailed(output):
return "Default evaluation failed for host \(output.host)."
case let .hostValidationFailed(output):
return "Host validation failed for host \(output.host)."
case let .revocationCheckFailed(output, _):
return "Revocation check failed for host \(output.host)."
case let .certificatePinningFailed(host, _, _, _):
return "Certificate pinning failed for host \(host)."
case let .publicKeyPinningFailed(host, _, _, _):
return "Public key pinning failed for host \(host)."
case let .customEvaluationFailed(error):
return "Custom trust evaluation failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.URLRequestValidationFailureReason {
var localizedDescription: String {
switch self {
case let .bodyDataInGETRequest(data):
return """
Invalid URLRequest: Requests with GET method cannot have body data:
\(String(decoding: data, as: UTF8.self))
"""
}
}
}
| mit |
Fluci/CPU-Spy | CPU Spy/glue/GlobalDecl.swift | 1 | 208 | //
// GlobalDecl.swift
// CPU Spy
//
// Created by Felice Serena on 09.02.16.
// Copyright © 2016 Serena. All rights reserved.
//
import Foundation
let settings = Settings()
let appState = AppState() | mit |
modnovolyk/MAVLinkSwift | Sources/SimstateArdupilotmegaMsg.swift | 1 | 2630 | //
// SimstateArdupilotmegaMsg.swift
// MAVLink Protocol Swift Library
//
// Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py
// https://github.com/modnovolyk/MAVLinkSwift
//
import Foundation
/// Status of simulation environment, if used
public struct Simstate {
/// Roll angle (rad)
public let roll: Float
/// Pitch angle (rad)
public let pitch: Float
/// Yaw angle (rad)
public let yaw: Float
/// X acceleration m/s/s
public let xacc: Float
/// Y acceleration m/s/s
public let yacc: Float
/// Z acceleration m/s/s
public let zacc: Float
/// Angular speed around X axis rad/s
public let xgyro: Float
/// Angular speed around Y axis rad/s
public let ygyro: Float
/// Angular speed around Z axis rad/s
public let zgyro: Float
/// Latitude in degrees * 1E7
public let lat: Int32
/// Longitude in degrees * 1E7
public let lng: Int32
}
extension Simstate: Message {
public static let id = UInt8(164)
public static var typeName = "SIMSTATE"
public static var typeDescription = "Status of simulation environment, if used"
public static var fieldDefinitions: [FieldDefinition] = [("roll", 0, "Float", 0, "Roll angle (rad)"), ("pitch", 4, "Float", 0, "Pitch angle (rad)"), ("yaw", 8, "Float", 0, "Yaw angle (rad)"), ("xacc", 12, "Float", 0, "X acceleration m/s/s"), ("yacc", 16, "Float", 0, "Y acceleration m/s/s"), ("zacc", 20, "Float", 0, "Z acceleration m/s/s"), ("xgyro", 24, "Float", 0, "Angular speed around X axis rad/s"), ("ygyro", 28, "Float", 0, "Angular speed around Y axis rad/s"), ("zgyro", 32, "Float", 0, "Angular speed around Z axis rad/s"), ("lat", 36, "Int32", 0, "Latitude in degrees * 1E7"), ("lng", 40, "Int32", 0, "Longitude in degrees * 1E7")]
public init(data: Data) throws {
roll = try data.number(at: 0)
pitch = try data.number(at: 4)
yaw = try data.number(at: 8)
xacc = try data.number(at: 12)
yacc = try data.number(at: 16)
zacc = try data.number(at: 20)
xgyro = try data.number(at: 24)
ygyro = try data.number(at: 28)
zgyro = try data.number(at: 32)
lat = try data.number(at: 36)
lng = try data.number(at: 40)
}
public func pack() throws -> Data {
var payload = Data(count: 44)
try payload.set(roll, at: 0)
try payload.set(pitch, at: 4)
try payload.set(yaw, at: 8)
try payload.set(xacc, at: 12)
try payload.set(yacc, at: 16)
try payload.set(zacc, at: 20)
try payload.set(xgyro, at: 24)
try payload.set(ygyro, at: 28)
try payload.set(zgyro, at: 32)
try payload.set(lat, at: 36)
try payload.set(lng, at: 40)
return payload
}
}
| mit |
cnoon/swift-compiler-crashes | fixed/25947-llvm-tinyptrvector-swift-valuedecl-push-back.swift | 7 | 223 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import a func a}struct B<T where H.B:A{struct c}var a
| mit |
1457792186/JWSwift | 熊猫TV2/XMTV/Classes/Tools/Network/NetworkTool.swift | 2 | 829 | //
// NetworkTool.swift
// XMTV
//
// Created by Mac on 2017/1/4.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class NetworkTool {
class func request(type: MethodType, urlString: String, paramters: [String: Any]? = nil, finishedCallback: @escaping (_ result: Any) -> ()) {
// 获取类型
let method = type == .GET ? HTTPMethod.get : HTTPMethod.post
// 发送网络请求
Alamofire.request(urlString, method: method, parameters: paramters).responseJSON { (response) in
guard let result = response.result.value else {
print(response.result.error)
return
}
// 回调
finishedCallback(result as AnyObject)
}
}
}
| apache-2.0 |
jgainfort/FRPlayer | FRPlayer/AppReducer.swift | 1 | 529 | //
// AppReducer.swift
// FRPlayer
//
// Created by John Gainfort Jr on 3/31/17.
// Copyright © 2017 John Gainfort Jr. All rights reserved.
//
import ReSwift
struct AppReducer: Reducer {
typealias ReducerStateType = State
func handleAction(action: Action, state: State?) -> State {
return State(
playerState: playerReducer(state: state?.playerState, action: action),
controlbarState: controlbarReducer(state: state?.controlbarState, action: action)
)
}
}
| mit |
Ceroce/SwiftRay | SwiftRay/SwiftRay/Camera.swift | 1 | 1924 | //
// Camera.swift
// SwiftRay
//
// Created by Renaud Pradenc on 23/11/2016.
// Copyright © 2016 Céroce. All rights reserved.
//
import Darwin // Maths
struct Camera {
let lookFrom: Vec3
let lowerLeft: Vec3
let horizontal: Vec3
let vertical: Vec3
let u: Vec3
let v: Vec3
let aperture: Float
let startTime: Float
let endTime: Float
// yFov in degres. aspectRatio = width/height
init(lookFrom: Vec3, lookAt: Vec3, up: Vec3, yFov: Float, aspectRatio: Float, aperture: Float, focusDistance: Float, startTime: Float, endTime: Float) {
self.lookFrom = lookFrom
self.aperture = aperture
let theta = rad(yFov)
let halfHeight = tanf(theta/2)
let halfWidth = aspectRatio * halfHeight
let w = normalize(lookFrom - lookAt) // Direction of the camera
u = normalize(cross(up, w))
v = cross(w, u)
lowerLeft = lookFrom - halfWidth*focusDistance*u - halfHeight*focusDistance*v - focusDistance*w
horizontal = 2 * halfWidth * focusDistance * u
vertical = 2 * halfHeight * focusDistance * v
self.startTime = startTime
self.endTime = endTime
}
func ray(s: Float, t: Float) -> Ray {
// Depth of field is simulated by offsetting the origin of the ray randomly
let defocus = (aperture/2.0) * randPointOnUnitDisc()
let offset: Vec3 = u * defocus.x + v * defocus.y
let time = self.startTime + random01()*(endTime-startTime)
return Ray(origin: lookFrom+offset, direction: lowerLeft + s*horizontal + t*vertical - lookFrom - offset, time: time)
}
// Uses a rejection method
func randPointOnUnitDisc() -> Vec3 {
var p: Vec3
repeat {
p = 2 * Vec3(random01(), random01(), 0) - Vec3(1, 1, 0)
} while dot(p, p) >= 1.0
return p
}
}
| mit |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/MapTab/StopMap.swift | 1 | 2724 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* 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 GoogleMaps
import SwiftUI
import UIKit
/// This view that the user sees when tapping on the map tab.
struct StopMap: View {
@EnvironmentObject var modelData: ModelData
@State var selectedMarker: GMSMarker?
@State var markers: [GMSMarker] = []
@State private var zoom: Float = 15
@State var currentPage: Int = 0
var body: some View {
NavigationView {
ZStack(alignment: .bottom) {
MapViewControllerBridge(
markers: $markers,
selectedMarker: $selectedMarker,
zoom: $zoom
)
.frame(maxWidth: .infinity, alignment: .leading)
.onAppear {
markers = StopMap.buildMarkers(modelData: modelData)
}
PageViewController(
pages: modelData.stops.map({
StopPage(stop: $0).environmentObject(modelData)
}),
currentPage: $currentPage
)
.frame(height: 120)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 20, trailing: 0))
}
.navigationTitle(Text("Your itinerary"))
.onChange(of: selectedMarker) { newSelectedMarker in
if let stopId = newSelectedMarker?.userData as? String {
if let stopIndex = modelData.stops.firstIndex(where: { $0.stopInfo.stopId == stopId }) {
currentPage = stopIndex
}
}
}
}
}
func mapViewControllerBridge(
_ bridge: MapViewControllerBridge,
didTapOnMarker marker: GMSMarker
) {
if let stopId = marker.userData as? String,
let stopIndex = modelData.stops.firstIndex(where: { $0.stopInfo.stopId == stopId })
{
currentPage = stopIndex
}
}
private static func buildMarkers(modelData: ModelData) -> [GMSMarker] {
return modelData.stops.map({ CustomMarker.makeMarker(stop: $0) })
}
init() {
// Ensure Google Maps SDK is initialized.
let _ = LMFSDriverSampleApp.googleMapsInited
}
}
struct StopMap_Previews: PreviewProvider {
static var previews: some View {
let _ = LMFSDriverSampleApp.googleMapsInited
StopMap()
.environmentObject(ModelData(filename: "test_manifest"))
}
}
| apache-2.0 |
asalom/Cocoa-Design-Patterns-in-Swift | DesignPatterns/DesignPatternsTests/Hide Complexity/Facade/FacadeTests.swift | 1 | 427 | //
// FacadeTests.swift
// DesignPatterns
//
// Created by Alex Salom on 12/11/15.
// Copyright © 2015 Alex Salom © alexsalom.es. All rights reserved.
//
import XCTest
@testable import DesignPatterns
class FacadeTests: XCTestCase {
func testAComputerCanBeStarted() {
let computer = Computer()
XCTAssertFalse(computer.started)
computer.start()
XCTAssertTrue(computer.started)
}
} | mit |
Floater-ping/DYDemo | DYDemo/DYDemo/Classes/Tools/Extension/NSDate-Extension.swift | 1 | 343 | //
// NSDate-Extension.swift
// DYDemo
//
// Created by ZYP-MAC on 2017/8/7.
// Copyright © 2017年 ZYP-MAC. All rights reserved.
//
import Foundation
extension NSDate {
class func getCurrentTime() -> String {
let nowDate = NSDate()
let interval = nowDate.timeIntervalSince1970
return "\(interval)"
}
}
| mit |
RxSwiftCommunity/Action | Sources/Action/Action+Internal.swift | 1 | 1188 | import Foundation
import RxSwift
internal struct AssociatedKeys {
static var Action = "rx_action"
static var DisposeBag = "rx_disposeBag"
}
// Note: Actions performed in this extension are _not_ locked
// So be careful!
internal extension NSObject {
// A dispose bag to be used exclusively for the instance's rx.action.
var actionDisposeBag: DisposeBag {
var disposeBag: DisposeBag
if let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag {
disposeBag = lookup
} else {
disposeBag = DisposeBag()
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, disposeBag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return disposeBag
}
// Resets the actionDisposeBag to nil, disposeing of any subscriptions within it.
func resetActionDisposeBag() {
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
// Uses objc_sync on self to perform a locked operation.
func doLocked(_ closure: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
closure()
}
}
| mit |
xusader/firefox-ios | Client/Frontend/Home/TopSitesPanel.swift | 2 | 10666 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
private let ThumbnailIdentifier = "Thumbnail"
private let RowIdentifier = "Row"
private let SeparatorKind = "separator"
private let SeparatorIdentifier = "separator"
private let ThumbnailSectionPadding: CGFloat = 8
private let SeparatorColor = UIColor(rgb: 0xcccccc)
private let DefaultImage = "defaultFavicon"
class TopSitesPanel: UIViewController, UICollectionViewDelegate, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
private var collection: TopSitesCollectionView!
private var dataSource: TopSitesDataSource!
private let layout = TopSitesLayout()
var profile: Profile! {
didSet {
let options = QueryOptions(filter: nil, filterType: .None, sort: .Frecency)
profile.history.get(options, complete: { (data) -> Void in
self.dataSource.data = data
self.dataSource.profile = self.profile
self.collection.reloadData()
})
}
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
layout.setupForOrientation(toInterfaceOrientation)
collection.setNeedsLayout()
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = TopSitesDataSource(profile: profile, data: Cursor(status: .Failure, msg: "Nothing loaded yet"))
layout.registerClass(TopSitesSeparator.self, forDecorationViewOfKind: SeparatorKind)
collection = TopSitesCollectionView(frame: self.view.frame, collectionViewLayout: layout)
collection.backgroundColor = UIColor.whiteColor()
collection.delegate = self
collection.dataSource = dataSource
collection.registerClass(ThumbnailCell.self, forCellWithReuseIdentifier: ThumbnailIdentifier)
collection.registerClass(TwoLineCollectionViewCell.self, forCellWithReuseIdentifier: RowIdentifier)
collection.keyboardDismissMode = .OnDrag
view.addSubview(collection)
collection.snp_makeConstraints { make in
make.edges.equalTo(self.view)
return
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let site = dataSource?.data[indexPath.item] as? Site {
homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: site.url)!)
}
}
}
private class TopSitesCollectionView: UICollectionView {
private override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// Hide the keyboard if this view is touched.
window?.rootViewController?.view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
}
private class TopSitesLayout: UICollectionViewLayout {
private let AspectRatio: CGFloat = 1.25 // Ratio of width:height.
private var thumbnailRows = 3
private var thumbnailCols = 2
private var thumbnailCount: Int { return thumbnailRows * thumbnailCols }
private var width: CGFloat { return self.collectionView?.frame.width ?? 0 }
private var thumbnailWidth: CGFloat { return width / CGFloat(thumbnailCols) - (ThumbnailSectionPadding * 2) / CGFloat(thumbnailCols) }
private var thumbnailHeight: CGFloat { return thumbnailWidth / AspectRatio }
private var count: Int {
if let dataSource = self.collectionView?.dataSource as? TopSitesDataSource {
return dataSource.data.count
}
return 0
}
private var topSectionHeight: CGFloat {
let maxRows = ceil(Float(count) / Float(thumbnailCols))
let rows = min(Int(maxRows), thumbnailRows)
return thumbnailHeight * CGFloat(rows) + ThumbnailSectionPadding * 2
}
override init() {
super.init()
setupForOrientation(UIApplication.sharedApplication().statusBarOrientation)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupForOrientation(orientation: UIInterfaceOrientation) {
if orientation.isLandscape {
thumbnailRows = 2
thumbnailCols = 3
} else {
thumbnailRows = 3
thumbnailCols = 2
}
}
private func getIndexAtPosition(#y: CGFloat) -> Int {
if y < topSectionHeight {
let row = Int(y / thumbnailHeight)
return min(count - 1, max(0, row * thumbnailCols))
}
return min(count - 1, max(0, Int((y - topSectionHeight) / AppConstants.DefaultRowHeight + CGFloat(thumbnailCount))))
}
override func collectionViewContentSize() -> CGSize {
if count <= thumbnailCount {
let row = floor(Double(count / thumbnailCols))
return CGSize(width: width, height: topSectionHeight)
}
let bottomSectionHeight = CGFloat(count - thumbnailCount) * AppConstants.DefaultRowHeight
return CGSize(width: width, height: topSectionHeight + bottomSectionHeight)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
let start = getIndexAtPosition(y: rect.origin.y)
let end = getIndexAtPosition(y: rect.origin.y + rect.height)
var attrs = [UICollectionViewLayoutAttributes]()
if start == -1 || end == -1 {
return attrs
}
for i in start...end {
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let attr = layoutAttributesForItemAtIndexPath(indexPath)
attrs.append(attr)
if i >= thumbnailCount - 1 {
let decoration = layoutAttributesForDecorationViewOfKind(SeparatorKind, atIndexPath: indexPath)
attrs.append(decoration)
}
}
return attrs
}
// Set the frames for the row separators.
override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let decoration = UICollectionViewLayoutAttributes(forDecorationViewOfKind: elementKind, withIndexPath: indexPath)
let rowIndex = indexPath.item - thumbnailCount + 1
let rowYOffset = CGFloat(rowIndex) * AppConstants.DefaultRowHeight
let y = topSectionHeight + rowYOffset
decoration.frame = CGRectMake(0, y, width, 0.5)
return decoration
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let attr = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
let i = indexPath.item
if i < thumbnailCount {
// Set the top thumbnail frames.
let row = floor(Double(i / thumbnailCols))
let col = i % thumbnailCols
let x = CGFloat(thumbnailWidth * CGFloat(col)) + ThumbnailSectionPadding
let y = CGFloat(row) * thumbnailHeight + ThumbnailSectionPadding
attr.frame = CGRectMake(x, y, thumbnailWidth, thumbnailHeight)
} else {
// Set the bottom row frames.
let rowYOffset = CGFloat(i - thumbnailCount) * AppConstants.DefaultRowHeight
let y = CGFloat(topSectionHeight + rowYOffset)
attr.frame = CGRectMake(0, y, width, AppConstants.DefaultRowHeight)
}
return attr
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
class TopSitesDataSource: NSObject, UICollectionViewDataSource {
var data: Cursor
var profile: Profile
init(profile: Profile, data: Cursor) {
self.data = data
self.profile = profile
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
private func setDefaultThumbnailBackground(cell: ThumbnailCell) {
cell.imageView.image = UIImage(named: "defaultFavicon")!
cell.imageView.contentMode = UIViewContentMode.Center
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let site = data[indexPath.item] as! Site
// Cells for the top site thumbnails.
if indexPath.item < 6 {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ThumbnailIdentifier, forIndexPath: indexPath) as! ThumbnailCell
cell.textLabel.text = site.title.isEmpty ? site.url : site.title
if let thumbs = profile.thumbnails as? SDWebThumbnails {
cell.imageView.moz_getImageFromCache(site.url, cache: thumbs.cache, completed: { (img, err, type, url) -> Void in
if img != nil {
return
}
self.setDefaultThumbnailBackground(cell)
})
} else {
setDefaultThumbnailBackground(cell)
}
cell.isAccessibilityElement = true
cell.accessibilityLabel = cell.textLabel.text
return cell
}
// Cells for the remainder of the top sites list.
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(RowIdentifier, forIndexPath: indexPath) as! TwoLineCollectionViewCell
cell.textLabel.text = site.title.isEmpty ? site.url : site.title
cell.detailTextLabel.text = site.url
cell.isAccessibilityElement = true
cell.accessibilityLabel = "\(cell.textLabel.text!), \(cell.detailTextLabel.text!)"
if let icon = site.icon {
cell.imageView.sd_setImageWithURL(NSURL(string: icon.url)!)
} else {
cell.imageView.image = UIImage(named: DefaultImage)
}
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: SeparatorIdentifier, forIndexPath: indexPath) as! UICollectionReusableView
}
}
private class TopSitesSeparator: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = SeparatorColor
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 |
kylef/JSONSchema.swift | Sources/Applicators/if.swift | 1 | 458 | func `if`(context: Context, `if`: Any, instance: Any, schema: [String: Any]) throws -> AnySequence<ValidationError> {
if try context.validate(instance: instance, schema: `if`).isValid {
if let then = schema["then"] {
return try context.descend(instance: instance, subschema: then)
}
} else if let `else` = schema["else"] {
return try context.descend(instance: instance, subschema: `else`)
}
return AnySequence(EmptyCollection())
}
| bsd-3-clause |
darthpelo/SurviveAmsterdam | mobile/Pods/R.swift.Library/Library/UIKit/UIViewController+NibResource.swift | 4 | 592 | //
// UIViewController+NibResource.swift
// R.swift Library
//
// Created by Mathijs Kadijk on 06-12-15.
// Copyright © 2015 Mathijs Kadijk. All rights reserved.
//
import Foundation
import UIKit
public extension UIViewController {
/**
Returns a newly initialized view controller with the nib resource (R.nib.*).
- parameter nib: The nib resource (R.nib.*) to associate with the view controller.
- returns: A newly initialized UIViewController object.
*/
public convenience init(nib: NibResourceType) {
self.init(nibName: nib.name, bundle: nib.bundle)
}
}
| mit |
OscarSwanros/swift | test/SILGen/same_type_across_generic_depths.swift | 5 | 523 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s > %t/out.sil
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %t/out.sil | %FileCheck %s
class X<A> {}
struct Foo<T> {
// CHECK-LABEL: sil hidden @{{.*}}Foo{{.*}}bar{{.*}} : $@convention(method) <T><U where T == X<U>>
func bar<U>(_: U) where T == X<U> {}
// CHECK-LABEL: sil hidden @{{.*}}Foo{{.*}}bar{{.*}} : $@convention(method) <T><U where T : X<U>>
func bar<U>(_: U) where T: X<U> {}
}
| apache-2.0 |
imf/Stella | StellaTests/StellaTests.swift | 1 | 887 | //
// StellaTests.swift
// StellaTests
//
// Created by Ian McFarland on 6/5/14.
// Copyright (c) 2014 Ian McFarland. All rights reserved.
//
import XCTest
class StellaTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
cottonBuddha/Qsic | Qsic/config.swift | 1 | 3287 | //
// config.swift
// Qsic
//
// Created by cottonBuddha on 2017/8/27.
// Copyright © 2017年 cottonBuddha. All rights reserved.
//
import Foundation
import Darwin.ncurses
public let KEY_A_LOW: Int32 = 97
public let KEY_B_LOW: Int32 = 98
public let KEY_C_LOW: Int32 = 99
public let KEY_D_LOW: Int32 = 100
public let KEY_E_LOW: Int32 = 101
public let KEY_F_LOW: Int32 = 102
public let KEY_G_LOW: Int32 = 103
public let KEY_H_LOW: Int32 = 104
public let KEY_I_LOW: Int32 = 105
public let KEY_J_LOW: Int32 = 106
public let KEY_K_LOW: Int32 = 107
public let KEY_L_LOW: Int32 = 108
public let KEY_M_LOW: Int32 = 109
public let KEY_N_LOW: Int32 = 110
public let KEY_O_LOW: Int32 = 111
public let KEY_P_LOW: Int32 = 112
public let KEY_Q_LOW: Int32 = 113
public let KEY_R_LOW: Int32 = 114
public let KEY_S_LOW: Int32 = 115
public let KEY_T_LOW: Int32 = 116
public let KEY_U_LOW: Int32 = 117
public let KEY_V_LOW: Int32 = 118
public let KEY_W_LOW: Int32 = 119
public let KEY_X_LOW: Int32 = 120
public let KEY_Y_LOW: Int32 = 121
public let KEY_Z_LOW: Int32 = 122
public let KEY_L_ANGLE_EN: Int32 = 44
public let KEY_R_ANGLE_EN: Int32 = 46
public let KEY_L_ANGLE_ZH: Int32 = 140
public let KEY_R_ANGLE_ZH: Int32 = 130
public let EN_L_C_BRACE: Int32 = 91
public let EN_R_C_BRACE: Int32 = 93
public let ZH_L_C_BRACE: Int32 = 144
public let ZH_R_C_BRACE: Int32 = 145
public let KEY_SLASH_EN: Int32 = 47
public let KEY_SLASH_ZH: Int32 = 129
public let KEY_NUMBER_ONE: Int32 = 49
public let KEY_NUMBER_TWO: Int32 = 50
public let KEY_NUMBER_THREE: Int32 = 51
public let KEY_ENTER: Int32 = 10
public let KEY_SPACE: Int32 = 32
public let KEY_COMMA: Int32 = 39
public let KEY_DOT: Int32 = 46
/**
向上移动
*/public let CMD_UP = KEY_UP
/**
向下移动
*/public let CMD_DOWN = KEY_DOWN
/**
上一页
*/public let CMD_LEFT = KEY_LEFT
/**
下一页
*/public let CMD_RIGHT = KEY_RIGHT
/**
选中
*/public let CMD_ENTER = KEY_ENTER
/**
退出
*/public let CMD_QUIT = KEY_Q_LOW
/**
退出且退出登录
*/public let CMD_QUIT_LOGOUT = KEY_W_LOW
/**
返回上一级菜单
*/public let CMD_BACK = (KEY_SLASH_ZH,KEY_SLASH_EN)
/**
播放/暂停
*/public let CMD_PLAY_PAUSE = KEY_SPACE
/**
下一首
*/public let CMD_PLAY_NEXT = (KEY_R_ANGLE_EN,KEY_R_ANGLE_ZH)
/**
上一首
*/public let CMD_PLAY_PREVIOUS = (KEY_L_ANGLE_EN,KEY_L_ANGLE_ZH)
/**
音量+
*/public let CMD_VOLUME_ADD = (EN_R_C_BRACE,ZH_R_C_BRACE)
/**
音量-
*/public let CMD_VOLUME_MINUS = (EN_L_C_BRACE,ZH_L_C_BRACE)
/**
添加到收藏
*/public let CMD_ADD_LIKE = KEY_A_LOW
/**
搜索
*/public let CMD_SEARCH = KEY_S_LOW
/**
登录
*/public let CMD_LOGIN = KEY_D_LOW
/**
当前播放列表
*/public let CMD_PLAY_LIST = KEY_F_LOW
/**
打开GitHub
*/public let CMD_GITHUB = KEY_G_LOW
/**
隐藏╭( ̄3 ̄)╯播放指示
*/public let CMD_HIDE_DANCER = KEY_H_LOW
/**
单曲循环
*/public let CMD_PLAYMODE_SINGLE = KEY_NUMBER_ONE
/**
顺序播放
*/public let CMD_PLAYMODE_ORDER = KEY_NUMBER_TWO
/**
随机播放
*/public let CMD_PLAYMODE_SHUFFLE = KEY_NUMBER_THREE
/**
相关设置的key
*/
//public let UD_POP_HINT = "UD_POP_HINT"
//public let UD_HIDE_DANCER = "UD_HIDE_DANCER"
public let UD_USER_NICKNAME = "UD_USER_NICKNAME"
public let UD_USER_ID = "UD_USER_ID"
| mit |
carambalabs/Paparajote | Example/Tests/Providers/GitLabProviderSpec.swift | 1 | 3607 | import Foundation
import Quick
import Nimble
import NSURL_QueryDictionary
@testable import Paparajote
class GitLabProviderSpec: QuickSpec {
override func spec() {
var subject: GitLabProvider!
var clientId: String!
var clientSecret: String!
var redirectUri: String!
var state: String!
var url: URL!
beforeEach {
clientId = "client_id"
clientSecret = "client_secret"
redirectUri = "redirect://works"
state = "asdg135125"
url = URL(string: "https://gitlab.com")!
subject = GitLabProvider(url: url, clientId: clientId, clientSecret: clientSecret, redirectUri: redirectUri, state: state)
}
describe("-authorization") {
it("should return the correct url") {
let expected = "https://gitlab.com/oauth/authorize?client_id=client_id&redirect_uri=redirect://works&response_type=code&state=asdg135125"
expect(subject.authorization().absoluteString) == expected
}
}
describe("-authentication") {
context("when there's no code in the url") {
it("should return nil") {
let url = URL(string: "\(redirectUri!)?state=abc")!
expect(subject.authentication(url)).to(beNil())
}
}
context("when there's no state in the url") {
it("should return nil") {
let url = URL(string: "\(redirectUri!)?code=abc")!
expect(subject.authentication(url)).to(beNil())
}
}
context("when it has code and state") {
var request: URLRequest!
beforeEach {
let url = URL(string: "\(redirectUri!)?code=abc&state=\(state!)")!
request = subject.authentication(url)
}
it("should return a request with the correct URL") {
let expected = "https://gitlab.com/oauth/token?client_id=client_id&client_secret=client_secret&code=abc&redirect_uri=redirect://works&grant_type=authorization_code"
expect(request.url?.absoluteString) == expected
}
it("should return a request with the a JSON Accept header") {
expect(request.value(forHTTPHeaderField: "Accept")) == "application/json"
}
it("should return a request with the POST method") {
expect(request.httpMethod) == "POST"
}
}
}
describe("-sessionAdapter") {
context("when the data has not the correct format") {
it("should return nil") {
let dictionary: [String: Any] = [:]
let data = try! JSONSerialization.data(withJSONObject: dictionary, options: [])
expect(subject.sessionAdapter(data, URLResponse())).to(beNil())
}
}
context("when the data has the correct format") {
it("should return the session") {
let dictionary = ["access_token": "tooooken"]
let data = try! JSONSerialization.data(withJSONObject: dictionary, options: [])
expect(subject.sessionAdapter(data, URLResponse())?.accessToken) == "tooooken"
}
}
}
}
}
| mit |
AliSoftware/SwiftGen | Sources/SwiftGen/Version.swift | 1 | 219 | //
// SwiftGen
// Copyright © 2020 SwiftGen
// MIT Licence
//
enum Version {
static let swiftgen = "6.5.1"
static let swiftGenKit = "6.5.1"
static let stencil = "0.14.1"
static let stencilSwiftKit = "2.8.0"
}
| mit |
monisun/yowl | Yelp/RecentSearchesViewController.swift | 1 | 1527 | //
// RecentSearchesViewController.swift
// Yelp
//
// Created by Monica Sun on 5/16/15.
// Copyright (c) 2015 Monica Sun. All rights reserved.
//
import UIKit
class RecentSearchesViewController: UIViewController {
var recentSearches = [String]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recentSearches.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("searchTermCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel!.text = recentSearches[indexPath.row]
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
Candyroot/DesignPattern | command/command/SimpleRemoteControl.swift | 1 | 417 | //
// SimpleRemoteControl.swift
// command
//
// Created by Bing Liu on 11/12/14.
// Copyright (c) 2014 UnixOSS. All rights reserved.
//
import Foundation
public class SimpleRemoteControl {
public var slot: Command?
public init() {}
public func setCommand(command: Command) {
slot = command
}
public func buttonWasPressed() {
slot!.execute()
}
}
| apache-2.0 |
zkhCreator/ASImagePicker | ASImagePicker/Classes/ASPreviewUtilsManager.swift | 1 | 306 | //
// ASPreviewUtilsManager.h
// Pods
//
// Created by zkhCreator on 12/06/2017.
//
//
import UIKit
public class ASPreviewUtilsManager: NSObject {
// public static let shared = ASPreviewUtilsManager()
//
// public var previewController:ASPreviewViewController
//
//
}
| mit |
craftsmanship-toledo/katangapp-ios | Katanga/Cells/NearBusStopCell.swift | 1 | 3714 | /**
* Copyright 2016-today Software Craftmanship Toledo
*
* 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.
*/
/*!
@author Víctor Galán
*/
import RxCocoa
import RxSwift
import UIKit
class NearBusStopCell: UITableViewCell {
public var busStopName: String {
set {
busStopNameLabel.text = newValue
}
get {
return busStopNameLabel.text ?? ""
}
}
public var distance: String {
set {
distanceLabel.text = newValue
}
get {
return distanceLabel.text ?? ""
}
}
public var bustStopTimes: [BusStopTime] {
set {
busStopsTimeDataSource.value.append(contentsOf: newValue)
}
get {
return busStopsTimeDataSource.value
}
}
public var routeItemClick: ((String) -> Void)?
public var busStopClick: (() -> Void)?
@IBOutlet private weak var busStopNameLabel: UILabel!
@IBOutlet weak var busStopIcon: UIImageView!
@IBOutlet private weak var containerView: UIView! {
didSet {
containerView.layer.cornerRadius = Constants.cornerRadius
containerView.layer.masksToBounds = true
}
}
@IBOutlet private weak var distanceLabel: UILabel!
@IBOutlet private weak var heightConstraint: NSLayoutConstraint!
@IBOutlet private weak var headerHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var tableView: UITableView! {
didSet {
tableView.register(BusComingCell.self)
tableView.rowHeight = Constants.rowHeight
}
}
private var disposeBag = DisposeBag()
private var busStopsTimeDataSource = Variable<[BusStopTime]>([])
private struct Constants {
static let cornerRadius: CGFloat = 10
static let rowHeight: CGFloat = 40
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
tableView.customizeTableView(withColor: .clear)
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(busStopIconClick))
busStopIcon.addGestureRecognizer(gestureRecognizer)
busStopIcon.isUserInteractionEnabled = true
setupRx()
}
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
busStopsTimeDataSource.value = []
setupRx()
}
private func setupRx() {
busStopsTimeDataSource
.asObservable()
.bindTo(tableView.rx.items(cellType: BusComingCell.self)) { [weak self] _, element, cell in
cell.routeId = element.id
cell.time = element.minutes
cell.routeItemClick = self?.routeItemClick
}.addDisposableTo(disposeBag)
busStopsTimeDataSource
.asObservable()
.map { CGFloat($0.count) }
.filter { $0 > 0 }
.map { $0 * Constants.rowHeight + self.headerHeightConstraint.constant }
.bindTo(heightConstraint.rx.constant)
.addDisposableTo(disposeBag)
}
@objc private func busStopIconClick() {
busStopClick?()
}
}
| apache-2.0 |
raphaelhanneken/apple-juice | AppleJuiceToday/PercentageInfoType.swift | 1 | 395 | //
// PercentageInfoType.swift
// Apple Juice Widget
// https://github.com/raphaelhanneken/apple-juice
//
import Foundation
class PercentageInfoType: NSObject, BatteryInfoTypeProtocol {
var title: String
var value: String
init(_ battery: BatteryService?) {
title = NSLocalizedString("Percentage", comment: "")
value = battery?.percentage.formatted ?? "--"
}
}
| mit |
tannernelson/hamburger-menu | Pod/Classes/MenuControllerView.swift | 1 | 693 | /*
Replaces the native UIView inside of the UITabBarController subclass.
This is necessary to ensure proper capture of touch events for the
hamburger menu added outside of the UIView's bounds.
*/
import Foundation
class MenuControllerView: UIView {
//MARK: Properties
var menu: MenuView!
//MARK: Touch
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
if CGRectContainsPoint(self.bounds, point) {
return true
}
//allow touches to pass to the Menu
if CGRectContainsPoint(self.menu.frame, point) {
return true
}
return false
}
} | mit |
babarqb/HackingWithSwift | project36/Project36/AppDelegate.swift | 25 | 2051 | //
// AppDelegate.swift
// Project36
//
// Created by Hudzilla on 19/09/2015.
// Copyright © 2015 Paul Hudson. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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:.
}
}
| unlicense |
lucaslt89/PopupContainer | Example/PopupContainerExample/AppDelegate.swift | 1 | 2191 | //
// AppDelegate.swift
// PopupContainerExample
//
// Created by Lucas Diez de Medina on 3/12/15.
// Copyright (c) 2015 Technopix. 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:.
}
}
| mit |
benlangmuir/swift | validation-test/Sema/type_checker_crashers_fixed/issue59031.swift | 6 | 486 | // RUN: not %target-swift-frontend %s -typecheck
struct Data {
// Type `Q` not declared yet.
typealias ReturnType = Q
mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: () -> R
// If you put "R" instead of "ReturnType", it doesn't crash.
) -> ReturnType {
fatalError()
}
}
func withUnsafeMutableBufferPointer<R>() -> R {
var data = Data()
return data.withContiguousMutableStorageIfAvailable {
_ = Int.init
return 2 as Any as R
}
}
| apache-2.0 |
kgaidis/KGViewSeparators | Example/Swift/KGViewSeparatorsExample/UITableViewCell+Separators.swift | 1 | 626 | //
// UITableViewCell+Separators.swift
// KGViewSeparatorsExample
//
// Created by Krisjanis Gaidis on 12/28/15.
// Copyright © 2015 KG. All rights reserved.
//
import Foundation
extension UITableViewCell {
func showTopSeparator(show: Bool) {
self.contentView.kg_show(show, separator: .Top, color: UIColor.blackColor(), lineWidth: KGViewSeparatorLineWidth(1.0), insets: UIEdgeInsetsZero)
}
func showBottomSeparator(show: Bool) {
self.contentView.kg_show(show, separator: .Bottom, color: UIColor.blackColor(), lineWidth: KGViewSeparatorLineWidth(1.0), insets: UIEdgeInsetsZero)
}
} | mit |
Jerry21/JYDouYuZB | JYDouYuZB/JYDouYuZB/AppDelegate.swift | 1 | 2267 | //
// AppDelegate.swift
// JYDouYuZB
//
// Created by yejunyou on 2017/2/13.
// Copyright © 2017年 yejunyou. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// 修改tabbar icon 选中时候的颜色
UITabBar.appearance().tintColor = UIColor.orangeColor()
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:.
}
}
| mit |
Octadero/TensorFlow | Sources/Proto/core/protobuf/tensor_bundle.pb.swift | 1 | 12963 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: tensorflow/core/protobuf/tensor_bundle.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// Special header that is associated with a bundle.
///
/// TODO(zongheng,zhifengc): maybe in the future, we can add information about
/// which binary produced this checkpoint, timestamp, etc. Sometime, these can be
/// valuable debugging information. And if needed, these can be used as defensive
/// information ensuring reader (binary version) of the checkpoint and the writer
/// (binary version) must match within certain range, etc.
public struct Tensorflow_BundleHeaderProto {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// Number of data files in the bundle.
public var numShards: Int32 {
get {return _storage._numShards}
set {_uniqueStorage()._numShards = newValue}
}
public var endianness: Tensorflow_BundleHeaderProto.Endianness {
get {return _storage._endianness}
set {_uniqueStorage()._endianness = newValue}
}
/// Versioning of the tensor bundle format.
public var version: Tensorflow_VersionDef {
get {return _storage._version ?? Tensorflow_VersionDef()}
set {_uniqueStorage()._version = newValue}
}
/// Returns true if `version` has been explicitly set.
public var hasVersion: Bool {return _storage._version != nil}
/// Clears the value of `version`. Subsequent reads from it will return its default value.
public mutating func clearVersion() {_storage._version = nil}
public var unknownFields = SwiftProtobuf.UnknownStorage()
/// An enum indicating the endianness of the platform that produced this
/// bundle. A bundle can only be read by a platform with matching endianness.
/// Defaults to LITTLE, as most modern platforms are little-endian.
///
/// Affects the binary tensor data bytes only, not the metadata in protobufs.
public enum Endianness: SwiftProtobuf.Enum {
public typealias RawValue = Int
case little // = 0
case big // = 1
case UNRECOGNIZED(Int)
public init() {
self = .little
}
public init?(rawValue: Int) {
switch rawValue {
case 0: self = .little
case 1: self = .big
default: self = .UNRECOGNIZED(rawValue)
}
}
public var rawValue: Int {
switch self {
case .little: return 0
case .big: return 1
case .UNRECOGNIZED(let i): return i
}
}
}
public init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
/// Describes the metadata related to a checkpointed tensor.
public struct Tensorflow_BundleEntryProto {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
/// The tensor dtype and shape.
public var dtype: Tensorflow_DataType {
get {return _storage._dtype}
set {_uniqueStorage()._dtype = newValue}
}
public var shape: Tensorflow_TensorShapeProto {
get {return _storage._shape ?? Tensorflow_TensorShapeProto()}
set {_uniqueStorage()._shape = newValue}
}
/// Returns true if `shape` has been explicitly set.
public var hasShape: Bool {return _storage._shape != nil}
/// Clears the value of `shape`. Subsequent reads from it will return its default value.
public mutating func clearShape() {_storage._shape = nil}
/// The binary content of the tensor lies in:
/// File "shard_id": bytes [offset, offset + size).
public var shardID: Int32 {
get {return _storage._shardID}
set {_uniqueStorage()._shardID = newValue}
}
public var offset: Int64 {
get {return _storage._offset}
set {_uniqueStorage()._offset = newValue}
}
public var size: Int64 {
get {return _storage._size}
set {_uniqueStorage()._size = newValue}
}
/// The CRC32C checksum of the tensor bytes.
public var crc32C: UInt32 {
get {return _storage._crc32C}
set {_uniqueStorage()._crc32C = newValue}
}
/// Iff present, this entry represents a partitioned tensor. The previous
/// fields are interpreted as follows:
///
/// "dtype", "shape": describe the full tensor.
/// "shard_id", "offset", "size", "crc32c": all IGNORED.
/// These information for each slice can be looked up in their own
/// BundleEntryProto, keyed by each "slice_name".
public var slices: [Tensorflow_TensorSliceProto] {
get {return _storage._slices}
set {_uniqueStorage()._slices = newValue}
}
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _storage = _StorageClass.defaultInstance
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "tensorflow"
extension Tensorflow_BundleHeaderProto: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".BundleHeaderProto"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "num_shards"),
2: .same(proto: "endianness"),
3: .same(proto: "version"),
]
fileprivate class _StorageClass {
var _numShards: Int32 = 0
var _endianness: Tensorflow_BundleHeaderProto.Endianness = .little
var _version: Tensorflow_VersionDef? = nil
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_numShards = source._numShards
_endianness = source._endianness
_version = source._version
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularInt32Field(value: &_storage._numShards)
case 2: try decoder.decodeSingularEnumField(value: &_storage._endianness)
case 3: try decoder.decodeSingularMessageField(value: &_storage._version)
default: break
}
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if _storage._numShards != 0 {
try visitor.visitSingularInt32Field(value: _storage._numShards, fieldNumber: 1)
}
if _storage._endianness != .little {
try visitor.visitSingularEnumField(value: _storage._endianness, fieldNumber: 2)
}
if let v = _storage._version {
try visitor.visitSingularMessageField(value: v, fieldNumber: 3)
}
}
try unknownFields.traverse(visitor: &visitor)
}
public func _protobuf_generated_isEqualTo(other: Tensorflow_BundleHeaderProto) -> Bool {
if _storage !== other._storage {
let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let other_storage = _args.1
if _storage._numShards != other_storage._numShards {return false}
if _storage._endianness != other_storage._endianness {return false}
if _storage._version != other_storage._version {return false}
return true
}
if !storagesAreEqual {return false}
}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension Tensorflow_BundleHeaderProto.Endianness: SwiftProtobuf._ProtoNameProviding {
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
0: .same(proto: "LITTLE"),
1: .same(proto: "BIG"),
]
}
extension Tensorflow_BundleEntryProto: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".BundleEntryProto"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "dtype"),
2: .same(proto: "shape"),
3: .standard(proto: "shard_id"),
4: .same(proto: "offset"),
5: .same(proto: "size"),
6: .same(proto: "crc32c"),
7: .same(proto: "slices"),
]
fileprivate class _StorageClass {
var _dtype: Tensorflow_DataType = .dtInvalid
var _shape: Tensorflow_TensorShapeProto? = nil
var _shardID: Int32 = 0
var _offset: Int64 = 0
var _size: Int64 = 0
var _crc32C: UInt32 = 0
var _slices: [Tensorflow_TensorSliceProto] = []
static let defaultInstance = _StorageClass()
private init() {}
init(copying source: _StorageClass) {
_dtype = source._dtype
_shape = source._shape
_shardID = source._shardID
_offset = source._offset
_size = source._size
_crc32C = source._crc32C
_slices = source._slices
}
}
fileprivate mutating func _uniqueStorage() -> _StorageClass {
if !isKnownUniquelyReferenced(&_storage) {
_storage = _StorageClass(copying: _storage)
}
return _storage
}
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
_ = _uniqueStorage()
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularEnumField(value: &_storage._dtype)
case 2: try decoder.decodeSingularMessageField(value: &_storage._shape)
case 3: try decoder.decodeSingularInt32Field(value: &_storage._shardID)
case 4: try decoder.decodeSingularInt64Field(value: &_storage._offset)
case 5: try decoder.decodeSingularInt64Field(value: &_storage._size)
case 6: try decoder.decodeSingularFixed32Field(value: &_storage._crc32C)
case 7: try decoder.decodeRepeatedMessageField(value: &_storage._slices)
default: break
}
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try withExtendedLifetime(_storage) { (_storage: _StorageClass) in
if _storage._dtype != .dtInvalid {
try visitor.visitSingularEnumField(value: _storage._dtype, fieldNumber: 1)
}
if let v = _storage._shape {
try visitor.visitSingularMessageField(value: v, fieldNumber: 2)
}
if _storage._shardID != 0 {
try visitor.visitSingularInt32Field(value: _storage._shardID, fieldNumber: 3)
}
if _storage._offset != 0 {
try visitor.visitSingularInt64Field(value: _storage._offset, fieldNumber: 4)
}
if _storage._size != 0 {
try visitor.visitSingularInt64Field(value: _storage._size, fieldNumber: 5)
}
if _storage._crc32C != 0 {
try visitor.visitSingularFixed32Field(value: _storage._crc32C, fieldNumber: 6)
}
if !_storage._slices.isEmpty {
try visitor.visitRepeatedMessageField(value: _storage._slices, fieldNumber: 7)
}
}
try unknownFields.traverse(visitor: &visitor)
}
public func _protobuf_generated_isEqualTo(other: Tensorflow_BundleEntryProto) -> Bool {
if _storage !== other._storage {
let storagesAreEqual: Bool = withExtendedLifetime((_storage, other._storage)) { (_args: (_StorageClass, _StorageClass)) in
let _storage = _args.0
let other_storage = _args.1
if _storage._dtype != other_storage._dtype {return false}
if _storage._shape != other_storage._shape {return false}
if _storage._shardID != other_storage._shardID {return false}
if _storage._offset != other_storage._offset {return false}
if _storage._size != other_storage._size {return false}
if _storage._crc32C != other_storage._crc32C {return false}
if _storage._slices != other_storage._slices {return false}
return true
}
if !storagesAreEqual {return false}
}
if unknownFields != other.unknownFields {return false}
return true
}
}
| gpl-3.0 |
radazzouz/firefox-ios | StorageTests/TestSQLiteHistory.swift | 1 | 62031 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@testable import Storage
import Deferred
import XCTest
let threeMonthsInMillis: UInt64 = 3 * 30 * 24 * 60 * 60 * 1000
let threeMonthsInMicros: UInt64 = UInt64(threeMonthsInMillis) * UInt64(1000)
// Start everything three months ago.
let baseInstantInMillis = Date.now() - threeMonthsInMillis
let baseInstantInMicros = Date.nowMicroseconds() - threeMonthsInMicros
func advanceTimestamp(_ timestamp: Timestamp, by: Int) -> Timestamp {
return timestamp + UInt64(by)
}
func advanceMicrosecondTimestamp(_ timestamp: MicrosecondTimestamp, by: Int) -> MicrosecondTimestamp {
return timestamp + UInt64(by)
}
extension Site {
func asPlace() -> Place {
return Place(guid: self.guid!, url: self.url, title: self.title)
}
}
class BaseHistoricalBrowserTable {
func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool {
assert(false, "Should never be called.")
}
func exists(_ db: SQLiteDBConnection) -> Bool {
return false
}
func drop(_ db: SQLiteDBConnection) -> Bool {
return false
}
var supportsPartialIndices: Bool {
let v = sqlite3_libversion_number()
return v >= 3008000 // 3.8.0.
}
let oldFaviconsSQL =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
func run(_ db: SQLiteDBConnection, sql: String?, args: Args? = nil) -> Bool {
if let sql = sql {
let err = db.executeChange(sql, withArgs: args)
return err == nil
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String?]) -> Bool {
for sql in queries {
if let sql = sql {
if !run(db, sql: sql) {
return false
}
}
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql) {
return false
}
}
return true
}
}
// Versions of BrowserTable that we care about:
// v6, prior to 001c73ea1903c238be1340950770879b40c41732, July 2015.
// This is when we first started caring about database versions.
//
// v7, 81e22fa6f7446e27526a5a9e8f4623df159936c3. History tiles.
//
// v8, 02c08ddc6d805d853bbe053884725dc971ef37d7. Favicons.
//
// v10, 4428c7d181ff4779ab1efb39e857e41bdbf4de67. Mirroring. We skipped v9.
//
// These tests snapshot the table creation code at each of these points.
class BrowserTableV6: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 6 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func CreateHistoryTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func CreateDomainsTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func CreateQueueTable() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
}
extension BrowserTableV6: Table {
func create(_ db: SQLiteDBConnection) -> Bool {
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"\(TableFavicons).id AS iconID, " +
"\(TableFavicons).url AS iconURL, " +
"\(TableFavicons).date AS iconDate, " +
"\(TableFavicons).type AS iconType, " +
"MAX(\(TableFavicons).width) AS iconWidth " +
"FROM \(TableFaviconSites), \(TableFavicons) WHERE " +
"\(TableFaviconSites).faviconID = \(TableFavicons).id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT \(TableHistory).id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM \(TableHistory) " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
CreateDomainsTable(),
CreateHistoryTable(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
CreateQueueTable(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserTableV7: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 7 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS history (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
}
extension BrowserTableV7: SectionCreator, TableInfo {
func create(_ db: SQLiteDBConnection) -> Bool {
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
getDomainsTableCreationString(),
getHistoryTableCreationString(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserTableV8: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 8 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
}
extension BrowserTableV8: SectionCreator, TableInfo {
func create(_ db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS visits (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"history, \(ViewWidestFaviconsForSites) AS icons WHERE " +
"history.id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserTableV10: BaseHistoricalBrowserTable {
var name: String { return "BROWSER" }
var version: Int { return 10 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql =
"INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " +
"(?, ?, ?, NULL, ?, ?), " + // Root
"(?, ?, ?, NULL, ?, ?), " + // Mobile
"(?, ?, ?, NULL, ?, ?), " + // Menu
"(?, ?, ?, NULL, ?, ?), " + // Toolbar
"(?, ?, ?, NULL, ?, ?) " // Unsorted
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String {
return "CREATE TABLE IF NOT EXISTS history (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
}
func getDomainsTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
}
func getQueueTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
}
func getBookmarksMirrorTableCreationString() -> String {
// The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry.
// For now we have the simplest possible schema: everything in one.
let sql =
"CREATE TABLE IF NOT EXISTS \(TableBookmarksMirror) " +
// Shared fields.
"( id INTEGER PRIMARY KEY AUTOINCREMENT" +
", guid TEXT NOT NULL UNIQUE" +
", type TINYINT NOT NULL" + // Type enum. TODO: BookmarkNodeType needs to be extended.
// Record/envelope metadata that'll allow us to do merges.
", server_modified INTEGER NOT NULL" + // Milliseconds.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean
", hasDupe TINYINT NOT NULL DEFAULT 0" + // Boolean, 0 (false) if deleted.
", parentid TEXT" + // GUID
", parentName TEXT" +
// Type-specific fields. These should be NOT NULL in many cases, but we're going
// for a sparse schema, so this'll do for now. Enforce these in the application code.
", feedUri TEXT, siteUri TEXT" + // LIVEMARKS
", pos INT" + // SEPARATORS
", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES
", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES
", folderName TEXT, queryId TEXT" + // QUERIES
", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" +
", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" +
")"
return sql
}
/**
* We need to explicitly store what's provided by the server, because we can't rely on
* referenced child nodes to exist yet!
*/
func getBookmarksMirrorStructureTableCreationString() -> String {
return "CREATE TABLE IF NOT EXISTS \(TableBookmarksMirrorStructure) " +
"( parent TEXT NOT NULL REFERENCES \(TableBookmarksMirror)(guid) ON DELETE CASCADE" +
", child TEXT NOT NULL" + // Should be the GUID of a child.
", idx INTEGER NOT NULL" + // Should advance from 0.
")"
}
}
extension BrowserTableV10: SectionCreator, TableInfo {
func create(_ db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS favicons (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS visits (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON visits (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"favicons.id AS iconID, " +
"favicons.url AS iconURL, " +
"favicons.date AS iconDate, " +
"favicons.type AS iconType, " +
"MAX(favicons.width) AS iconWidth " +
"FROM \(TableFaviconSites), favicons WHERE " +
"\(TableFaviconSites).faviconID = favicons.id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT history.id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM history " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"history, \(ViewWidestFaviconsForSites) AS icons WHERE " +
"history.id = icons.siteID "
let bookmarks =
"CREATE TABLE IF NOT EXISTS bookmarks (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"type TINYINT NOT NULL, " +
"url TEXT, " +
"parent INTEGER REFERENCES bookmarks(id) NOT NULL, " +
"faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL, " +
"title TEXT" +
") "
let bookmarksMirror = getBookmarksMirrorTableCreationString()
let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString()
let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
bookmarksMirror,
bookmarksMirrorStructure,
indexStructureParentIdx,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class TestSQLiteHistory: XCTestCase {
let files = MockFiles()
fileprivate func deleteDatabases() {
for v in ["6", "7", "8", "10", "6-data"] {
do {
try files.remove("browser-v\(v).db")
} catch {}
}
do {
try files.remove("browser.db")
try files.remove("historysynced.db")
} catch {}
}
override func tearDown() {
super.tearDown()
self.deleteDatabases()
}
override func setUp() {
super.setUp()
// Just in case tearDown didn't run or succeed last time!
self.deleteDatabases()
}
// Test that our visit partitioning for frecency is correct.
func testHistoryLocalAndRemoteVisits() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let siteL = Site(url: "http://url1/", title: "title local only")
let siteR = Site(url: "http://url2/", title: "title remote only")
let siteB = Site(url: "http://url3/", title: "title local and remote")
siteL.guid = "locallocal12"
siteR.guid = "remoteremote"
siteB.guid = "bothbothboth"
let siteVisitL1 = SiteVisit(site: siteL, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitL2 = SiteVisit(site: siteL, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR1 = SiteVisit(site: siteR, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitR2 = SiteVisit(site: siteR, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR3 = SiteVisit(site: siteR, date: baseInstantInMicros + 3000, type: VisitType.link)
let siteVisitBL1 = SiteVisit(site: siteB, date: baseInstantInMicros + 4000, type: VisitType.link)
let siteVisitBR1 = SiteVisit(site: siteB, date: baseInstantInMicros + 5000, type: VisitType.link)
let deferred =
history.clearHistory()
>>> { history.addLocalVisit(siteVisitL1) }
>>> { history.addLocalVisit(siteVisitL2) }
>>> { history.addLocalVisit(siteVisitBL1) }
>>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) }
>>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) }
>>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) }
// Do this step twice, so we exercise the dupe-visit handling.
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) }
>>> { history.getSitesByFrecencyWithHistoryLimit(3)
>>== { (sites: Cursor) -> Success in
XCTAssertEqual(3, sites.count)
// Two local visits beat a single later remote visit and one later local visit.
// Two local visits beat three remote visits.
XCTAssertEqual(siteL.guid!, sites[0]!.guid!)
XCTAssertEqual(siteB.guid!, sites[1]!.guid!)
XCTAssertEqual(siteR.guid!, sites[2]!.guid!)
return succeed()
}
// This marks everything as modified so we can fetch it.
>>> history.onRemovedAccount
// Now check that we have no duplicate visits.
>>> { history.getModifiedHistoryToUpload()
>>== { (places) -> Success in
if let (_, visits) = places.find({$0.0.guid == siteR.guid!}) {
XCTAssertEqual(3, visits.count)
} else {
XCTFail("Couldn't find site R.")
}
return succeed()
}
}
}
XCTAssertTrue(deferred.value.isSuccess)
}
func testUpgrades() {
let sources: [(Int, SectionCreator)] = [
(6, BrowserTableV6()),
(7, BrowserTableV7()),
(8, BrowserTableV8()),
(10, BrowserTableV10()),
]
let destination = BrowserTable()
for (version, table) in sources {
let db = BrowserDB(filename: "browser-v\(version).db", files: files)
XCTAssertTrue(
db.runWithConnection { (conn, err) in
XCTAssertTrue(table.create(conn), "Creating browser table version \(version)")
// And we can upgrade to the current version.
XCTAssertTrue(destination.updateTable(conn, from: table.version), "Upgrading browser table from version \(version)")
}.value.isSuccess
)
db.forceClose()
}
}
func testUpgradesWithData() {
let db = BrowserDB(filename: "browser-v6-data.db", files: files)
XCTAssertTrue(db.createOrUpdate(BrowserTableV6()) == .success, "Creating browser table version 6")
// Insert some data.
let queries = [
"INSERT INTO domains (id, domain) VALUES (1, 'example.com')",
"INSERT INTO history (id, guid, url, title, server_modified, local_modified, is_deleted, should_upload, domain_id) VALUES (5, 'guid', 'http://www.example.com', 'title', 5, 10, 0, 1, 1)",
"INSERT INTO visits (siteID, date, type, is_local) VALUES (5, 15, 1, 1)",
"INSERT INTO favicons (url, width, height, type, date) VALUES ('http://www.example.com/favicon.ico', 10, 10, 1, 20)",
"INSERT INTO favicon_sites (siteID, faviconID) VALUES (5, 1)",
"INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES ('guid', 1, 'http://www.example.com', 0, 1, 'title')"
]
XCTAssertTrue(db.run(queries).value.isSuccess)
// And we can upgrade to the current version.
XCTAssertTrue(db.createOrUpdate(BrowserTable()) == .success, "Upgrading browser table from version 6")
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let results = history.getSitesByLastVisit(10).value.successValue
XCTAssertNotNil(results)
XCTAssertEqual(results![0]?.url, "http://www.example.com")
db.forceClose()
}
func testDomainUpgrade() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let site = Site(url: "http://www.example.com/test1.1", title: "title one")
var err: NSError? = nil
// Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden.
db.withWritableConnection(&err, callback: { (connection, err) -> Int in
let insert = "INSERT INTO \(TableHistory) (guid, url, title, local_modified, is_deleted, should_upload, domain_id) " +
"?, ?, ?, ?, ?, ?, ?"
let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1]
err = connection.executeChange(insert, withArgs: args)
return 0
})
// Now insert it again. This should update the domain
history.addLocalVisit(SiteVisit(site: site, date: Date.nowMicroseconds(), type: VisitType.link))
// DomainID isn't normally exposed, so we manually query to get it
let results = db.withReadableConnection(&err, callback: { (connection, err) -> Cursor<Int> in
let sql = "SELECT domain_id FROM \(TableHistory) WHERE url = ?"
let args: Args = [site.url]
return connection.executeQuery(sql, factory: IntFactory, withArgs: args)
})
XCTAssertNotEqual(results[0]!, -1, "Domain id was updated")
}
func testDomains() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGuid = Bytes.generateGUID()
let site11 = Site(url: "http://www.example.com/test1.1", title: "title one")
let site12 = Site(url: "http://www.example.com/test1.2", title: "title two")
let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three")
let site3 = Site(url: "http://www.example2.com/test1", title: "title three")
let expectation = self.expectation(description: "First.")
history.clearHistory().bind({ success in
return all([history.addLocalVisit(SiteVisit(site: site11, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site12, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site3, date: Date.nowMicroseconds(), type: VisitType.link))])
}).bind({ (results: [Maybe<()>]) in
return history.insertOrUpdatePlace(site13, modified: Date.nowMicroseconds())
}).bind({ guid in
XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct")
return history.getSitesByFrecencyWithHistoryLimit(10)
}).bind({ (sites: Maybe<Cursor<Site>>) -> Success in
XCTAssert(sites.successValue!.count == 2, "2 sites returned")
return history.removeSiteFromTopSites(site11)
}).bind({ success in
XCTAssertTrue(success.isSuccess, "Remove was successful")
return history.getSitesByFrecencyWithHistoryLimit(10)
}).upon({ (sites: Maybe<Cursor<Site>>) in
XCTAssert(sites.successValue!.count == 1, "1 site returned")
expectation.fulfill()
})
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testHistoryIsSynced() {
let db = BrowserDB(filename: "historysynced.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGUID = Bytes.generateGUID()
let site = Place(guid: initialGUID, url: "http://www.example.com/test1.3", title: "title")
XCTAssertFalse(history.hasSyncedHistory().value.successValue ?? true)
XCTAssertTrue(history.insertOrUpdatePlace(site, modified: Date.now()).value.isSuccess)
XCTAssertTrue(history.hasSyncedHistory().value.successValue ?? false)
}
// This is a very basic test. Adds an entry, retrieves it, updates it,
// and then clears the database.
func testHistoryTable() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let site1 = Site(url: "http://url1/", title: "title one")
let site1Changed = Site(url: "http://url1/", title: "title one alt")
let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link)
let siteVisit2 = SiteVisit(site: site1Changed, date: Date.nowMicroseconds() + 1000, type: VisitType.bookmark)
let site2 = Site(url: "http://url2/", title: "title two")
let siteVisit3 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func checkSitesByFrecency(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithHistoryLimit(10)
>>== f
}
}
func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByLastVisit(10)
>>== f
}
}
func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByFrecencyWithHistoryLimit(10, whereURLContains: filter)
>>== f
}
}
func checkDeletedCount(_ expected: Int) -> () -> Success {
return {
history.getDeletedHistoryToUpload()
>>== { guids in
XCTAssertEqual(expected, guids.count)
return succeed()
}
}
}
history.clearHistory()
>>> { history.addLocalVisit(siteVisit1) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1.title, sites[0]!.title)
XCTAssertEqual(site1.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit2) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site1Changed.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit3) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site2.title, sites[1]!.title)
return succeed()
}
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of date last visited.
let first = sites[0]!
let second = sites[1]!
XCTAssertEqual(site2.title, first.title)
XCTAssertEqual(site1Changed.title, second.title)
XCTAssertTrue(siteVisit3.date == first.latestVisit!.date)
return succeed()
}
>>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(1, sites.count)
let first = sites[0]!
XCTAssertEqual(site2.title, first.title)
return succeed()
}
>>>
checkDeletedCount(0)
>>> { history.removeHistoryForURL("http://url2/") }
>>>
checkDeletedCount(1)
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
return succeed()
}
>>> { history.clearHistory() }
>>>
checkDeletedCount(0)
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testFaviconTable() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func updateFavicon() -> Success {
let fav = Favicon(url: "http://url2/", date: Date(), type: .icon)
fav.id = 1
let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark")
return history.addFavicon(fav, forSite: site) >>> succeed
}
func checkFaviconForBookmarkIsNil() -> Success {
return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in
XCTAssertEqual(1, results.count)
XCTAssertNil(results[0]?.favicon)
return succeed()
}
}
func checkFaviconWasSetForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(1, results.count)
if let actualFaviconURL = results[0]??.url {
XCTAssertEqual("http://url2/", actualFaviconURL)
}
return succeed()
}
}
func removeBookmark() -> Success {
return bookmarks.testFactory.removeByURL("http://bookmarkedurl/")
}
func checkFaviconWasRemovedForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(0, results.count)
return succeed()
}
}
history.clearAllFavicons()
>>> bookmarks.clearBookmarks
>>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) }
>>> checkFaviconForBookmarkIsNil
>>> updateFavicon
>>> checkFaviconWasSetForBookmark
>>> removeBookmark
>>> checkFaviconWasRemovedForBookmark
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesCache() {
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().value
history.clearHistory().value
// Make sure that we get back the top sites
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Add extra visits to the 5th site to bubble it to the top of the top sites cache
let site = Site(url: "http://s\(5)ite\(5)/foo", title: "A \(5)")
site.guid = "abc\(5)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
func invalidateIfNeededDoesntChangeResults() -> Success {
return history.updateTopSitesCacheIfInvalidated() >>> {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
}
func addVisitsToZerothSite() -> Success {
let site = Site(url: "http://s\(0)ite\(0)/foo", title: "A \(0)")
site.guid = "abc\(0)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
return succeed()
}
func markInvalidation() -> Success {
history.setTopSitesNeedsInvalidation()
return succeed()
}
func checkSitesInvalidate() -> Success {
history.updateTopSitesCacheIfInvalidated().value
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(0)def")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> invalidateIfNeededDoesntChangeResults
>>> markInvalidation
>>> addVisitsToZerothSite
>>> checkSitesInvalidate
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
}
class TestSQLiteHistoryTransactionUpdate: XCTestCase {
func testUpdateInTransaction() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.clearHistory().value
let site = Site(url: "http://site/foo", title: "AA")
site.guid = "abcdefghiabc"
history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).value
let ts: MicrosecondTimestamp = baseInstantInMicros
let local = SiteVisit(site: site, date: ts, type: VisitType.link)
XCTAssertTrue(history.addLocalVisit(local).value.isSuccess)
}
}
class TestSQLiteHistoryFilterSplitting: XCTestCase {
let history: SQLiteHistory = {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
let prefs = MockProfilePrefs()
return SQLiteHistory(db: db, prefs: prefs)
}()
func testWithSingleWord() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithIdenticalWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo fo foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithDistinctWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithDistinctWordsAndWhitespace() {
let (fragment, args) = history.computeWhereFragmentWithFilter(" foo bar ", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithSubstrings() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
func testWithSubstringsAndIdenticalWords() {
let (fragment, args) = history.computeWhereFragmentWithFilter("foo bar foobar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
fileprivate func stringArgsEqual(_ one: Args, _ other: Args) -> Bool {
return one.elementsEqual(other, by: { (oneElement: Any?, otherElement: Any?) -> Bool in
return (oneElement as! String) == (otherElement as! String)
})
}
}
// MARK - Private Test Helper Methods
enum VisitOrigin {
case local
case remote
}
private func populateHistoryForFrecencyCalculations(_ history: SQLiteHistory, siteCount count: Int) {
for i in 0...count {
let site = Site(url: "http://s\(i)ite\(i)/foo", title: "A \(i)")
site.guid = "abc\(i)def"
let baseMillis: UInt64 = baseInstantInMillis - 20000
history.insertOrUpdatePlace(site.asPlace(), modified: baseMillis).value
for j in 0...20 {
let visitTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i) + (1000 * j))
addVisitForSite(site, intoHistory: history, from: .local, atTime: visitTime)
addVisitForSite(site, intoHistory: history, from: .remote, atTime: visitTime)
}
}
}
func addVisitForSite(_ site: Site, intoHistory history: SQLiteHistory, from: VisitOrigin, atTime: MicrosecondTimestamp) {
let visit = SiteVisit(site: site, date: atTime, type: VisitType.link)
switch from {
case .local:
history.addLocalVisit(visit).value
case .remote:
history.storeRemoteVisits([visit], forGUID: site.guid!).value
}
}
| mpl-2.0 |
PDF417/pdf417-ios | Samples/pdf417-sample-Swift/pdf417-sample-Swift/CustomOverlay.swift | 1 | 2459 | //
// CustomOverlay.swift
// pdf417-sample-Swift
//
// Created by Dino Gustin on 06/03/2018.
// Copyright © 2018 Dino. All rights reserved.
//
import Pdf417Mobi
class CustomOverlay: MBBCustomOverlayViewController, MBBScanningRecognizerRunnerViewControllerDelegate {
static func initFromStoryboardWith() -> CustomOverlay {
let customOverlay: CustomOverlay = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CustomOverlay") as! CustomOverlay
return customOverlay
}
override func viewDidLoad() {
super.viewDidLoad()
super.scanningRecognizerRunnerViewControllerDelegate = self;
}
func recognizerRunnerViewControllerDidFinishScanning(_ recognizerRunnerViewController: UIViewController & MBBRecognizerRunnerViewController, state: MBBRecognizerResultState) {
/** This is done on background thread */
if state == .valid {
recognizerRunnerViewController.pauseScanning();
DispatchQueue.main.async {
var message: String = ""
var title: String = ""
for recognizer in self.recognizerCollection.recognizerList {
if ( recognizer.baseResult?.resultState == .valid ) {
let barcodeRecognizer = recognizer as? MBBBarcodeRecognizer
title = "QR Code"
message = (barcodeRecognizer?.result.stringData!)!
}
}
let alertController: UIAlertController = UIAlertController.init(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
let okAction: UIAlertAction = UIAlertAction.init(title: "OK", style: UIAlertAction.Style.default,
handler: { (action) -> Void in
self.dismiss(animated: true, completion: nil)
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
@IBAction func didTapClose(_ sender: Any) {
self.recognizerRunnerViewController?.overlayViewControllerWillCloseCamera(self);
self.dismiss(animated: true, completion: nil);
}
}
| apache-2.0 |
halawata13/Golf | GolfUITests/GolfUITests.swift | 1 | 1137 | //
// GolfUITests.swift
// GolfUITests
//
import XCTest
class GolfUITests: 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.
}
}
| mit |
slavapestov/swift | validation-test/compiler_crashers_fixed/28151-swift-constraints-constraintsystem-simplifymemberconstraint.swift | 3 | 361 | // 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 k:CollectionType
let a{
enum B{struct d{
struct S{let a=0.g
let a{class d<T where f:A{
enum E{struct B{{}struct B<g{class B{class d{var _=B
| apache-2.0 |
isgustavo/AnimatedMoviesMakeMeCry | iOS/Animated Movies Make Me Cry/Pods/Firebase/Samples/database/DatabaseExampleSwift/PostDataSource.swift | 9 | 1775 | //
// Copyright (c) 2015 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 FirebaseUI
class PostDataSource: FirebaseTableViewDataSource {
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
refForIndex(UInt(indexPath.row)).removeValue()
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.count() != 0 {
tableView.separatorStyle = .SingleLine
tableView.backgroundView = nil
}
return Int(self.count())
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let noDataLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No posts yet - why not add one?"
noDataLabel.textColor = UIColor.blackColor()
noDataLabel.textAlignment = .Center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .None
return 1
}
} | apache-2.0 |
ioscreator/ioscreator | SwiftUIDragGestureTutorial/SwiftUIDragGestureTutorial/AppDelegate.swift | 1 | 1442 | //
// AppDelegate.swift
// SwiftUIDragGestureTutorial
//
// Created by Arthur Knopper on 24/09/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| mit |
jemartti/Hymnal | Hymnal/ScheduleViewController.swift | 1 | 11474 | //
// ScheduleViewController.swift
// Hymnal
//
// Created by Jacob Marttinen on 5/6/17.
// Copyright © 2017 Jacob Marttinen. All rights reserved.
//
import UIKit
import CoreData
// MARK: - ScheduleViewController: UITableViewController
class ScheduleViewController: UITableViewController {
// MARK: Properties
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var indicator: UIActivityIndicatorView!
var schedule: [ScheduleLineEntity]!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
initialiseUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Check if it's time to update the schedule
var forceFetch = false
if !UserDefaults.standard.bool(forKey: "hasFetchedSchedule") {
forceFetch = true
} else {
let lastScheduleFetch = UserDefaults.standard.double(forKey: "lastScheduleFetch")
if (lastScheduleFetch + 60*60*24 < NSDate().timeIntervalSince1970) {
forceFetch = true
}
}
// Check for existing Schedule in Model
let scheduleFR = NSFetchRequest<NSManagedObject>(entityName: "ScheduleLineEntity")
scheduleFR.sortDescriptors = [NSSortDescriptor(key: "sortKey", ascending: true)]
do {
let scheduleLineEntities = try appDelegate.stack.context.fetch(scheduleFR) as! [ScheduleLineEntity]
if scheduleLineEntities.count <= 0 || forceFetch {
schedule = [ScheduleLineEntity]()
fetchSchedule()
} else {
schedule = scheduleLineEntities
tableView.reloadData()
}
} catch _ as NSError {
alertUserOfFailure(message: "Data load failed.")
}
}
// UI+UX Functionality
private func initialiseUI() {
view.backgroundColor = .white
indicator = createIndicator()
// Set up the Navigation bar
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: UIBarButtonItem.SystemItem.stop,
target: self,
action: #selector(ScheduleViewController.returnToRoot)
)
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: UIBarButtonItem.SystemItem.refresh,
target: self,
action: #selector(ScheduleViewController.fetchSchedule)
)
navigationItem.title = "Schedule"
navigationController?.navigationBar.barTintColor = .white
navigationController?.navigationBar.tintColor = Constants.UI.Armadillo
navigationController?.navigationBar.titleTextAttributes = [
NSAttributedString.Key.foregroundColor: Constants.UI.Armadillo
]
}
private func createIndicator() -> UIActivityIndicatorView {
let indicator = UIActivityIndicatorView(
style: UIActivityIndicatorView.Style.gray
)
indicator.frame = CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0);
indicator.center = view.center
view.addSubview(indicator)
indicator.bringSubviewToFront(view)
return indicator
}
private func alertUserOfFailure( message: String) {
DispatchQueue.main.async {
let alertController = UIAlertController(
title: "Action Failed",
message: message,
preferredStyle: UIAlertController.Style.alert
)
alertController.addAction(UIAlertAction(
title: "Dismiss",
style: UIAlertAction.Style.default,
handler: nil
))
self.present(alertController, animated: true, completion: nil)
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.indicator.stopAnimating()
}
}
@objc func returnToRoot() {
dismiss(animated: true, completion: nil)
}
// MARK: Data Management Functions
@objc func fetchSchedule() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
indicator.startAnimating()
MarttinenClient.sharedInstance().getSchedule() { (scheduleRaw, error) in
if error != nil {
self.alertUserOfFailure(message: "Data download failed.")
} else {
self.appDelegate.stack.performBackgroundBatchOperation { (workerContext) in
// Cleanup any existing data
let DelAllScheduleLineEntities = NSBatchDeleteRequest(
fetchRequest: NSFetchRequest<NSFetchRequestResult>(entityName: "ScheduleLineEntity")
)
do {
try workerContext.execute(DelAllScheduleLineEntities)
}
catch {
self.alertUserOfFailure(message: "Data load failed.")
}
// Clear local properties
self.schedule = [ScheduleLineEntity]()
// We have to clear data in active contexts after performing batch operations
self.appDelegate.stack.reset()
DispatchQueue.main.async {
self.parseAndSaveSchedule(scheduleRaw)
self.tableView.reloadData()
UserDefaults.standard.set(true, forKey: "hasFetchedSchedule")
UserDefaults.standard.set(NSDate().timeIntervalSince1970, forKey: "lastScheduleFetch")
UserDefaults.standard.synchronize()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.indicator.stopAnimating()
}
}
}
}
}
private func parseAndSaveSchedule(_ scheduleRaw: [ScheduleLine]) {
for i in 0 ..< scheduleRaw.count {
let scheduleLineRaw = scheduleRaw[i]
let scheduleLineEntity = ScheduleLineEntity(context: self.appDelegate.stack.context)
scheduleLineEntity.sortKey = Int32(i)
scheduleLineEntity.isSunday = scheduleLineRaw.isSunday
scheduleLineEntity.locality = scheduleLineRaw.locality
var titleString = scheduleLineRaw.dateString + ": "
if let status = scheduleLineRaw.status {
titleString = titleString + status
} else if let localityPretty = scheduleLineRaw.localityPretty {
titleString = titleString + localityPretty
}
scheduleLineEntity.title = titleString
var subtitleString = ""
if let missionaries = scheduleLineRaw.missionaries {
subtitleString = subtitleString + missionaries
}
if scheduleLineRaw.with.count > 0 {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
subtitleString = subtitleString + "(with "
for i in 0 ..< scheduleLineRaw.with.count {
if i != 0 {
subtitleString = subtitleString + " and "
}
subtitleString = subtitleString + scheduleLineRaw.with[i]
}
subtitleString = subtitleString + ")"
}
if let isAM = scheduleLineRaw.am, let isPM = scheduleLineRaw.pm {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
if isAM && isPM {
subtitleString = subtitleString + "(AM & PM)"
} else if isAM {
subtitleString = subtitleString + "(AM Only)"
} else if isPM {
subtitleString = subtitleString + "(PM Only)"
}
}
if let comment = scheduleLineRaw.comment {
if subtitleString != "" {
subtitleString = subtitleString + " "
}
subtitleString = subtitleString + "(" + comment + ")"
}
scheduleLineEntity.subtitle = subtitleString
self.schedule.append(scheduleLineEntity)
}
self.appDelegate.stack.save()
}
// MARK: Table View Data Source
override func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
return schedule.count
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: "ScheduleLineTableViewCell"
)!
let scheduleLine = schedule[(indexPath as NSIndexPath).row]
cell.textLabel?.text = scheduleLine.title!
cell.detailTextLabel?.text = scheduleLine.subtitle!
cell.backgroundColor = .white
cell.textLabel?.textColor = Constants.UI.Armadillo
cell.detailTextLabel?.textColor = Constants.UI.Armadillo
if scheduleLine.isSunday {
cell.textLabel?.textColor = .red
cell.detailTextLabel?.textColor = .red
}
return cell
}
override func tableView(
_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath
) {
let scheduleLine = schedule[(indexPath as NSIndexPath).row]
// Only load information if the ScheduleLine refers to a specific locality
guard let key = scheduleLine.locality else {
tableView.deselectRow(at: indexPath, animated: true)
return
}
// Protect against missing locality
guard let locality = Directory.directory!.localities[key] else {
tableView.deselectRow(at: indexPath, animated: true)
return
}
// If we have location details, load the LocalityView
// Otherwise, jump straight to ContactView
if locality.hasLocationDetails {
let localityViewController = storyboard!.instantiateViewController(
withIdentifier: "LocalityViewController"
) as! LocalityViewController
localityViewController.locality = locality
navigationController!.pushViewController(localityViewController, animated: true)
} else {
let contactViewController = storyboard!.instantiateViewController(
withIdentifier: "ContactViewController"
) as! ContactViewController
contactViewController.locality = locality
navigationController!.pushViewController(contactViewController, animated: true)
}
}
}
| mit |
chicio/RangeUISlider | RangeUISliderTests/StepCalculatorTest.swift | 1 | 788 | //
// StepCalculator.swift
// RangeUISliderTests
//
// Created by Fabrizio Duroni on 29.12.20.
// 2020 Fabrizio Duroni.
//
import XCTest
@testable import RangeUISlider
class StepCalculatorTest: XCTestCase {
func testCalculateStepWidthInvalidIncrement() throws {
let stepWidth = StepCalculator().calculateStepWidth(
stepIncrement: 0,
scale: Scale(scaleMinValue: 10, scaleMaxValue: 20),
barWidth: 100
)
XCTAssertEqual(stepWidth, 1)
}
func testCalculateStepWidth() throws {
let stepWidth = StepCalculator().calculateStepWidth(
stepIncrement: 5,
scale: Scale(scaleMinValue: 0, scaleMaxValue: 100),
barWidth: 100
)
XCTAssertEqual(stepWidth, 5)
}
}
| mit |
ZamzamInc/ZamzamKitData | ZamzamKitData Example Watch Extension/ComplicationController.swift | 1 | 2400 | //
// ComplicationController.swift
// ZamzamKitData Example Watch Extension
//
// Created by Basem Emara on 3/19/16.
//
//
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) {
handler([.Forward, .Backward])
}
func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(nil)
}
func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) {
handler(nil)
}
func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) {
handler(.ShowOnLockScreen)
}
// MARK: - Timeline Population
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) {
// Call the handler with the current timeline entry
handler(nil)
}
func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries prior to the given date
handler(nil)
}
func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) {
// Call the handler with the timeline entries after to the given date
handler(nil)
}
// MARK: - Update Scheduling
func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) {
// Call the handler with the date when you would next like to be given the opportunity to update your complication content
handler(nil);
}
// MARK: - Placeholder Templates
func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) {
// This method will be called once per supported complication, and the results will be cached
handler(nil)
}
}
| mit |
JGiola/swift | test/attr/attr_inlinable_available.swift | 3 | 64030 | // A module with library evolution enabled has two different "minimum versions".
// One, the minimum deployment target, is the lowest version that non-ABI
// declarations and bodies of non-inlinable functions will ever see. The other,
// the minimum inlining target, is the lowest version that ABI declarations and
// inlinable bodies will ever see.
//
// Test that we use the right version floor in the right places.
// REQUIRES: OS=macosx
// Primary execution of this test. Uses the default minimum inlining version,
// which is the version when Swift was introduced.
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -module-name Test -target %target-next-stable-abi-triple -target-min-inlining-version min
// Check that `-library-level api` implies `-target-min-inlining-version min`
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -module-name Test -target %target-next-stable-abi-triple -library-level api
// Check that these rules are only applied when requested and that at least some
// diagnostics are not present without it.
// RUN: not %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -module-name Test -target %target-next-stable-abi-triple 2>&1 | %FileCheck --check-prefix NON_MIN %s
// Check that -target-min-inlining-version overrides -library-level, allowing
// library owners to disable this behavior for API libraries if needed.
// RUN: not %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -module-name Test -target %target-next-stable-abi-triple -target-min-inlining-version target -library-level api 2>&1 | %FileCheck --check-prefix NON_MIN %s
// Check that we respect -target-min-inlining-version by cranking it up high
// enough to suppress any possible errors.
// RUN: %target-swift-frontend -typecheck -disable-objc-attr-requires-foundation-module %s -swift-version 5 -enable-library-evolution -module-name Test -target %target-next-stable-abi-triple -target-min-inlining-version 42.0
// NON_MIN: error: expected error not produced
// NON_MIN: {'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}
// MARK: - Struct definitions
/// Declaration with no availability annotation. Should be inferred as minimum
/// inlining target.
public struct NoAvailable {
@usableFromInline internal init() {}
}
@available(macOS 10.9, *)
public struct BeforeInliningTarget {
@usableFromInline internal init() {}
}
@available(macOS 10.10, *)
public struct AtInliningTarget {
@usableFromInline internal init() {}
}
@available(macOS 10.14.5, *)
public struct BetweenTargets {
@usableFromInline internal init() {}
}
@available(macOS 10.15, *)
public struct AtDeploymentTarget {
@usableFromInline internal init() {}
}
@available(macOS 11, *)
public struct AfterDeploymentTarget {
@usableFromInline internal init() {}
}
@available(macOS, unavailable)
public struct Unavailable {
@usableFromInline internal init() {}
}
// MARK: - Protocol definitions
public protocol NoAvailableProto {}
@available(macOS 10.9, *)
public protocol BeforeInliningTargetProto {}
@available(macOS 10.10, *)
public protocol AtInliningTargetProto {}
@available(macOS 10.14.5, *)
public protocol BetweenTargetsProto {}
@available(macOS 10.15, *)
public protocol AtDeploymentTargetProto {}
@available(macOS 11, *)
public protocol AfterDeploymentTargetProto {}
@available(macOS, unavailable)
public protocol UnavailableProto {}
// MARK: - Class definitions
public class NoAvailableClass {}
@available(macOS 10.9, *)
public class BeforeInliningTargetClass {}
@available(macOS 10.10, *)
public class AtInliningTargetClass {}
@available(macOS 10.14.5, *)
public class BetweenTargetsClass {}
@available(macOS 10.15, *)
public class AtDeploymentTargetClass {}
@available(macOS 11, *)
public class AfterDeploymentTargetClass {}
@available(macOS, unavailable)
public class UnavailableClass {}
// MARK: - Internal functions
//
// Both the signature and the body of internal functions should be typechecked
// using the minimum deployment target.
//
internal func internalFn( // expected-note 3 {{add @available attribute to enclosing global function}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
// MARK: - Resilient functions
//
// The body of a resilient function is typechecked using the minimum deployment
// but the function's signature should be checked with the inlining target.
//
public func deployedUseNoAvailable( // expected-note 5 {{add @available attribute}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 10.9, *)
public func deployedUseBeforeInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 10.10, *)
public func deployedUseAtInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 10.14.5, *)
public func deployedUseBetweenTargets(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 10.15, *)
public func deployedUseAtDeploymentTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 11, *)
public func deployedUseAfterDeploymentTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget()
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget()
}
@available(macOS, unavailable)
public func alwaysUnavailable(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget,
_: Unavailable
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
_ = Unavailable()
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@_spi(Private)
public func spiDeployedUseNoAvailable( // expected-note 3 {{add @available attribute}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
// MARK: - @inlinable functions
//
// Both the bodies and signatures of inlinable functions need to be typechecked
// using the minimum inlining target.
//
@inlinable public func inlinedUseNoAvailable( // expected-note 8 {{add @available attribute}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 10.14.5, *) {
_ = BetweenTargets()
}
if #available(macOS 10.15, *) {
_ = AtDeploymentTarget()
}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 10.9, *)
@inlinable public func inlinedUseBeforeInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 10.14.5, *) {
_ = BetweenTargets()
}
if #available(macOS 10.15, *) {
_ = AtDeploymentTarget()
}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 10.10, *)
@inlinable public func inlinedUseAtInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 10.14.5, *) {
_ = BetweenTargets()
}
if #available(macOS 10.15, *) {
_ = AtDeploymentTarget()
}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 10.14.5, *)
@inlinable public func inlinedUseBetweenTargets(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 10.15, *) {
_ = AtDeploymentTarget()
}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 10.15, *)
@inlinable public func inlinedUseAtDeploymentTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@available(macOS 11, *)
@inlinable public func inlinedUseAfterDeploymentTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget()
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget()
}
@available(macOS, unavailable)
@inlinable public func inlinedAlwaysUnavailable(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget,
_: Unavailable
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
_ = Unavailable()
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
@_spi(Private)
@inlinable public func spiInlinedUseNoAvailable( // expected-note 3 {{add @available attribute}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
// MARK: - @_alwaysEmitIntoClient functions
// @_alwaysEmitIntoClient acts like @inlinable.
@_alwaysEmitIntoClient public func aEICUseNoAvailable( // expected-note 8 {{add @available attribute}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 10.14.5, *) {
_ = BetweenTargets()
}
if #available(macOS 10.15, *) {
_ = AtDeploymentTarget()
}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
// MARK: - @_backDeploy functions
// @_backDeploy acts like @inlinable.
@available(macOS 10.10, *)
@_backDeploy(before: macOS 999.0)
public func backDeployedToInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 10.14.5, *) {
_ = BetweenTargets()
}
if #available(macOS 10.15, *) {
_ = AtDeploymentTarget()
}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
// MARK: - Default arguments
// Default arguments act like @inlinable when in a public function.
public func defaultArgsUseNoAvailable( // expected-note 3 {{add @available attribute}}
_: Any = NoAvailable.self,
_: Any = BeforeInliningTarget.self,
_: Any = AtInliningTarget.self,
_: Any = BetweenTargets.self, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: Any = AtDeploymentTarget.self, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: Any = AfterDeploymentTarget.self // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
func defaultArgsUseInternal( // expected-note {{add @available attribute}}
_: Any = NoAvailable.self,
_: Any = BeforeInliningTarget.self,
_: Any = AtInliningTarget.self,
_: Any = BetweenTargets.self,
_: Any = AtDeploymentTarget.self,
_: Any = AfterDeploymentTarget.self // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
@available(macOS, unavailable)
public func defaultArgsUseUnavailable(
_: Any = NoAvailable.self,
_: Any = BeforeInliningTarget.self,
_: Any = AtInliningTarget.self,
_: Any = BetweenTargets.self,
_: Any = AtDeploymentTarget.self,
_: Any = AfterDeploymentTarget.self, // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
_: Any = Unavailable.self
) {}
@_spi(Private)
public func spiDefaultArgsUseNoAvailable( // expected-note 1 {{add @available attribute}}
_: Any = NoAvailable.self,
_: Any = BeforeInliningTarget.self,
_: Any = AtInliningTarget.self,
_: Any = BetweenTargets.self,
_: Any = AtDeploymentTarget.self,
_: Any = AfterDeploymentTarget.self // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
// Verify that complex default argument expressions are checked appropriately.
public func defaultArgsClosureExprNoAvailable( // expected-note 3 {{add @available attribute}}
_: Int = {
_ = NoAvailable.self
_ = BeforeInliningTarget.self
_ = AtInliningTarget.self
_ = BetweenTargets.self // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available' version check}}
_ = AtDeploymentTarget.self // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available' version check}}
_ = AfterDeploymentTarget.self // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available' version check}}
if #available(macOS 10.14.5, *) {
_ = BetweenTargets.self
}
if #available(macOS 10.15, *) {
_ = AtDeploymentTarget.self
}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget.self
}
return 42
}()
) {}
func defaultArgsClosureExprInternal( // expected-note {{add @available attribute}}
_: Int = {
_ = NoAvailable.self
_ = BeforeInliningTarget.self
_ = AtInliningTarget.self
_ = BetweenTargets.self
_ = AtDeploymentTarget.self
_ = AfterDeploymentTarget.self // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available' version check}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget.self
}
return 42
}()
) {}
// MARK: - Properties
@propertyWrapper
public struct PropertyWrapper<T> {
public var wrappedValue: T
public init(wrappedValue value: T) { self.wrappedValue = value }
public init(_ value: T) { self.wrappedValue = value }
}
public struct PublicStruct { // expected-note 13 {{add @available attribute}}
// Public property declarations are exposed.
public var aPublic: NoAvailable,
bPublic: BeforeInliningTarget,
cPublic: AtInliningTarget,
dPublic: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
ePublic: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
fPublic: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
@available(macOS 10.14.5, *)
public var aPublicAvailBetween: NoAvailable,
bPublicAvailBetween: BeforeInliningTarget,
cPublicAvailBetween: AtInliningTarget,
dPublicAvailBetween: BetweenTargets,
ePublicAvailBetween: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
fPublicAvailBetween: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
// The inferred types of public properties are exposed.
public var aPublicInferred = NoAvailable(),
bPublicInferred = BeforeInliningTarget(),
cPublicInferred = AtInliningTarget(),
dPublicInferred = BetweenTargets(), // FIXME: Inferred type should be diagnosed
ePublicInferred = AtDeploymentTarget(), // FIXME: Inferred type should be diagnosed
fPublicInferred = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
@available(macOS 10.14.5, *)
public var aPublicInferredAvailBetween = NoAvailable(),
bPublicInferredAvailBetween = BeforeInliningTarget(),
cPublicInferredAvailBetween = AtInliningTarget(),
dPublicInferredAvailBetween = BetweenTargets(),
ePublicInferredAvailBetween = AtDeploymentTarget(), // FIXME: Inferred type should be diagnosed
fPublicInferredAvailBetween = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
// Property initializers are not exposed.
public var aPublicInit: Any = NoAvailable(),
bPublicInit: Any = BeforeInliningTarget(),
cPublicInit: Any = AtInliningTarget(),
dPublicInit: Any = BetweenTargets(),
ePublicInit: Any = AtDeploymentTarget(),
fPublicInit: Any = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
// Internal declarations are not exposed.
var aInternal: NoAvailable = .init(),
bInternal: BeforeInliningTarget = .init(),
cInternal: AtInliningTarget = .init(),
dInternal: BetweenTargets = .init(),
eInternal: AtDeploymentTarget = .init(),
fInternal: AfterDeploymentTarget = .init() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
@available(macOS 10.14.5, *)
public internal(set) var internalSetter: Void {
@inlinable get {
// Public inlinable getter acts like @inlinable
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 10.15, *) {
_ = AtDeploymentTarget()
}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
set {
// Private setter acts like non-inlinable
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
}
public var block: () -> () = {
// The body of a block assigned to a public property acts like non-@inlinable
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
}
}
public struct PublicStructWithWrappers { // expected-note 4 {{add @available attribute}}
// The property type is inferred from the initializer expression. The
// expressions themselves will not be exposed.
@PropertyWrapper public var aExplicitInit = NoAvailable()
@PropertyWrapper public var bExplicitInit = BeforeInliningTarget()
@PropertyWrapper public var cExplicitInit = AtInliningTarget()
@PropertyWrapper public var dExplicitInit = BetweenTargets() // FIXME: Inferred type should be diagnosed
@PropertyWrapper public var eExplicitInit = AtDeploymentTarget() // FIXME: Inferred type should be diagnosed
@PropertyWrapper public var fExplicitInit = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
// The property type is inferred from the initializer expression. The
// expressions themselves will not be exposed.
@PropertyWrapper(NoAvailable()) public var aExplicitInitAlt
@PropertyWrapper(BeforeInliningTarget()) public var bExplicitInitAlt
@PropertyWrapper(AtInliningTarget()) public var cExplicitInitAlt
@PropertyWrapper(BetweenTargets()) public var dExplicitInitAlt // FIXME: Inferred type should be diagnosed
@PropertyWrapper(AtDeploymentTarget()) public var ePExplicitInitAlt // FIXME: Inferred type should be diagnosed
@PropertyWrapper(AfterDeploymentTarget()) public var fExplicitInitAlt // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
// The property type is explicitly `Any` and the initializer expressions are
// not exposed.
@PropertyWrapper public var aAny: Any = NoAvailable()
@PropertyWrapper public var bAny: Any = BeforeInliningTarget()
@PropertyWrapper public var cAny: Any = AtInliningTarget()
@PropertyWrapper public var dAny: Any = BetweenTargets()
@PropertyWrapper public var eAny: Any = AtDeploymentTarget()
@PropertyWrapper public var fAny: Any = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
// The property type is explicitly `Any` and the initializer expressions are
// not exposed.
@PropertyWrapper(NoAvailable()) public var aAnyAlt: Any
@PropertyWrapper(BeforeInliningTarget()) public var bAnyAlt: Any
@PropertyWrapper(AtInliningTarget()) public var cAnyAlt: Any
@PropertyWrapper(BetweenTargets()) public var dAnyAlt: Any
@PropertyWrapper(AtDeploymentTarget()) public var eAnyAlt: Any
@PropertyWrapper(AfterDeploymentTarget()) public var fAnyAlt: Any // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
}
@frozen public struct FrozenPublicStruct { // expected-note 9 {{add @available attribute}}
// Public declarations are exposed.
public var aPublic: NoAvailable,
bPublic: BeforeInliningTarget,
cPublic: AtInliningTarget,
dPublic: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
ePublic: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
fPublic: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
// Property initializers are exposed in frozen structs.
public var aPublicInit: Any = NoAvailable(),
bPublicInit: Any = BeforeInliningTarget(),
cPublicInit: Any = AtInliningTarget(),
dPublicInit: Any = BetweenTargets(), // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
ePublicInit: Any = AtDeploymentTarget(), // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
fPublicInit: Any = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
// Internal declarations are also exposed in frozen structs.
var aInternal: NoAvailable = .init(),
bInternal: BeforeInliningTarget = .init(),
cInternal: AtInliningTarget = .init(),
dInternal: BetweenTargets = .init(), // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
eInternal: AtDeploymentTarget = .init(), // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
fInternal: AfterDeploymentTarget = .init() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
}
@available(macOS, unavailable)
public struct UnavailablePublicStruct {
public var aPublic: NoAvailable,
bPublic: BeforeInliningTarget,
cPublic: AtInliningTarget,
dPublic: BetweenTargets,
ePublic: AtDeploymentTarget,
fPublic: AfterDeploymentTarget, // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
gPublic: Unavailable
public var aPublicInit: Any = NoAvailable(),
bPublicInit: Any = BeforeInliningTarget(),
cPublicInit: Any = AtInliningTarget(),
dPublicInit: Any = BetweenTargets(),
ePublicInit: Any = AtDeploymentTarget(),
fPublicInit: Any = AfterDeploymentTarget(), // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
gPublicInit: Any = Unavailable()
var aInternal: NoAvailable = .init(),
bInternal: BeforeInliningTarget = .init(),
cInternal: AtInliningTarget = .init(),
dInternal: BetweenTargets = .init(),
eInternal: AtDeploymentTarget = .init(),
fInternal: AfterDeploymentTarget = .init(), // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
gInternal: Unavailable = .init()
}
@_spi(Private)
public struct SPIStruct { // expected-note 3 {{add @available attribute}}
public var aPublic: NoAvailable,
bPublic: BeforeInliningTarget,
cPublic: AtInliningTarget,
dPublic: BetweenTargets,
ePublic: AtDeploymentTarget,
fPublic: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
public var aPublicInit: Any = NoAvailable(),
bPublicInit: Any = BeforeInliningTarget(),
cPublicInit: Any = AtInliningTarget(),
dPublicInit: Any = BetweenTargets(),
ePublicInit: Any = AtDeploymentTarget(),
fPublicInit: Any = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
var aInternal: NoAvailable = .init(),
bInternal: BeforeInliningTarget = .init(),
cInternal: AtInliningTarget = .init(),
dInternal: BetweenTargets = .init(),
eInternal: AtDeploymentTarget = .init(),
fInternal: AfterDeploymentTarget = .init() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
}
internal struct InternalStruct { // expected-note 2 {{add @available attribute}}
// Internal declarations act like non-inlinable.
var aInternal: NoAvailable = .init(),
bInternal: BeforeInliningTarget = .init(),
cInternal: AtInliningTarget = .init(),
dInternal: BetweenTargets = .init(),
eInternal: AtDeploymentTarget = .init(),
fInternal: AfterDeploymentTarget = .init() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
@PropertyWrapper(NoAvailable()) var aWrapped: Any
@PropertyWrapper(BeforeInliningTarget()) var bWrapped: Any
@PropertyWrapper(AtInliningTarget()) var cWrapped: Any
@PropertyWrapper(BetweenTargets()) var dWrapped: Any
@PropertyWrapper(AtDeploymentTarget()) var eWrapped: Any
@PropertyWrapper(AfterDeploymentTarget()) var fWrapped: Any // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
}
// MARK: - Extensions
//
// Extensions are externally visible if they extend a public type and (1) have
// public members or (2) declare a conformance to a public protocol.
//
// Extensions without explicit availability that are externally visible use an
// implied floor of either the availability of the extended type or the
// deployment target, whichever is more available. This is a special rule
// designed as a convenience to library authors who have written quite a bit of
// code without annotating availability on their extensions and getting away
// with it because previously the deployment target was always used as the
// floor.
//
// Extensions without explicit availability that are not visible externally are
// checked using an implied floor of the deployment target.
//
// MARK: Extensions on NoAvailable
extension NoAvailable {}
extension NoAvailable { // expected-note {{add @available attribute to enclosing extension}}
func internalFuncInExtension( // expected-note {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
extension NoAvailable { // expected-note 3 {{add @available attribute to enclosing extension}}
public func publicFuncInExtension( // expected-note 3 {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
// MARK: Extensions on BetweenTargets
extension BetweenTargets {}
extension BetweenTargets { // expected-note {{add @available attribute to enclosing extension}}
func internalFuncInExtension( // expected-note {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
extension BetweenTargets { // expected-note 2 {{add @available attribute to enclosing extension}}
public func publicFuncInExtension( // expected-note 2 {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
@available(macOS 10.15, *)
extension BetweenTargets {
public func publicFuncInExtensionWithExplicitAvailability( // expected-note {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
extension BetweenTargets { // expected-note {{add @available attribute to enclosing extension}}
@available(macOS 10.15, *)
public func publicFuncWithExplicitAvailabilityInExtension(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
@_spi(Private)
extension BetweenTargets { // expected-note {{add @available attribute to enclosing extension}}
public func inheritedSPIFuncInExtension( // expected-note {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
@available(macOS, unavailable)
extension BetweenTargets {
public func inheritsUnavailableFuncInExtension(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget,
_: Unavailable
) {}
}
// This extension is explicitly more available than BetweenTargets but because
// it only contains internal members, the availability floor is still the
// deployment target.
@available(macOS 10.10, *)
extension BetweenTargets {
func internalFuncInExcessivelyAvailableExtension() {}
}
extension BetweenTargets {
@available(macOS 10.10, *)
func excessivelyAvailableInternalFuncInExtension() {}
}
@available(macOS 10.10, *)
extension BetweenTargets { // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
public func publicFuncInExcessivelyAvailableExtension() {}
}
// MARK: Extensions on BetweenTargetsInternal
// Same availability as BetweenTargets but internal instead of public.
@available(macOS 10.14.5, *)
internal struct BetweenTargetsInternal {}
extension BetweenTargetsInternal {}
extension BetweenTargetsInternal { // expected-note {{add @available attribute to enclosing extension}}
func internalFuncInExtension( // expected-note {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
extension BetweenTargetsInternal { // expected-note {{add @available attribute to enclosing extension}}
public func publicFuncInExtension( // expected-note {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
// MARK: Extensions on AfterDeploymentTarget
// expected-error@+1 {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note@+1 {{add @available attribute to enclosing extension}}
extension AfterDeploymentTarget {}
// expected-error@+1 {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
extension AfterDeploymentTarget { // expected-note 2 {{add @available attribute to enclosing extension}}
func internalFuncInExtension( // expected-note {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
// expected-error@+1 {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
extension AfterDeploymentTarget { // expected-note 2 {{add @available attribute to enclosing extension}}
public func publicFuncInExtension( // expected-note {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
@available(macOS 11, *)
extension AfterDeploymentTarget {
public func publicFuncInExtensionWithExplicitAvailability(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget
) {}
}
// MARK: Extensions on nested types
@available(macOS 10.14.5, *)
public enum BetweenTargetsEnum {
public struct Nested {}
}
extension BetweenTargetsEnum.Nested {}
extension BetweenTargetsEnum.Nested { // expected-note {{add @available attribute to enclosing extension}}
func internalFuncInExtension( // expected-note {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
extension BetweenTargetsEnum.Nested { // expected-note 2 {{add @available attribute to enclosing extension}}
public func publicFuncInExtension( // expected-note 2 {{add @available attribute to enclosing instance method}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}}
) {}
}
// MARK: Protocol conformances
internal protocol InternalProto {}
extension NoAvailable: InternalProto {}
extension BeforeInliningTarget: InternalProto {}
extension AtInliningTarget: InternalProto {}
extension BetweenTargets: InternalProto {}
extension AtDeploymentTarget: InternalProto {}
extension AfterDeploymentTarget: InternalProto {} // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add @available attribute to enclosing extension}}
public protocol PublicProto {}
extension NoAvailable: PublicProto {}
extension BeforeInliningTarget: PublicProto {}
extension AtInliningTarget: PublicProto {}
extension BetweenTargets: PublicProto {}
extension AtDeploymentTarget: PublicProto {}
extension AfterDeploymentTarget: PublicProto {} // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add @available attribute to enclosing extension}}
// MARK: - Associated types
public protocol NoAvailableProtoWithAssoc { // expected-note 3 {{add @available attribute to enclosing protocol}}
associatedtype A: NoAvailableProto
associatedtype B: BeforeInliningTargetProto
associatedtype C: AtInliningTargetProto
associatedtype D: BetweenTargetsProto // expected-error {{'BetweenTargetsProto' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
associatedtype E: AtDeploymentTargetProto // expected-error {{'AtDeploymentTargetProto' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
associatedtype F: AfterDeploymentTargetProto // expected-error {{'AfterDeploymentTargetProto' is only available in}}
}
@available(macOS 10.9, *)
public protocol BeforeInliningTargetProtoWithAssoc {
associatedtype A: NoAvailableProto
associatedtype B: BeforeInliningTargetProto
associatedtype C: AtInliningTargetProto
associatedtype D: BetweenTargetsProto // expected-error {{'BetweenTargetsProto' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
associatedtype E: AtDeploymentTargetProto // expected-error {{'AtDeploymentTargetProto' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
associatedtype F: AfterDeploymentTargetProto // expected-error {{'AfterDeploymentTargetProto' is only available in}}
}
@available(macOS 10.10, *)
public protocol AtInliningTargetProtoWithAssoc {
associatedtype A: NoAvailableProto
associatedtype B: BeforeInliningTargetProto
associatedtype C: AtInliningTargetProto
associatedtype D: BetweenTargetsProto // expected-error {{'BetweenTargetsProto' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}}
associatedtype E: AtDeploymentTargetProto // expected-error {{'AtDeploymentTargetProto' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
associatedtype F: AfterDeploymentTargetProto // expected-error {{'AfterDeploymentTargetProto' is only available in}}
}
@available(macOS 10.14.5, *)
public protocol BetweenTargetsProtoWithAssoc {
associatedtype A: NoAvailableProto
associatedtype B: BeforeInliningTargetProto
associatedtype C: AtInliningTargetProto
associatedtype D: BetweenTargetsProto
associatedtype E: AtDeploymentTargetProto // expected-error {{'AtDeploymentTargetProto' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}}
associatedtype F: AfterDeploymentTargetProto // expected-error {{'AfterDeploymentTargetProto' is only available in}}
}
@available(macOS 10.15, *)
public protocol AtDeploymentTargetProtoWithAssoc {
associatedtype A: NoAvailableProto
associatedtype B: BeforeInliningTargetProto
associatedtype C: AtInliningTargetProto
associatedtype D: BetweenTargetsProto
associatedtype E: AtDeploymentTargetProto
associatedtype F: AfterDeploymentTargetProto // expected-error {{'AfterDeploymentTargetProto' is only available in}}
}
@available(macOS 11, *)
public protocol AfterDeploymentTargetProtoWithAssoc {
associatedtype A: NoAvailableProto
associatedtype B: BeforeInliningTargetProto
associatedtype C: AtInliningTargetProto
associatedtype D: BetweenTargetsProto
associatedtype E: AtDeploymentTargetProto
associatedtype F: AfterDeploymentTargetProto
}
@available(macOS, unavailable)
public protocol UnavailableProtoWithAssoc {
associatedtype A: NoAvailableProto
associatedtype B: BeforeInliningTargetProto
associatedtype C: AtInliningTargetProto
associatedtype D: BetweenTargetsProto
associatedtype E: AtDeploymentTargetProto
associatedtype F: AfterDeploymentTargetProto // expected-error {{'AfterDeploymentTargetProto' is only available in}}
associatedtype G: UnavailableProto
}
@_spi(Private)
public protocol SPINoAvailableProtoWithAssoc { // expected-note 1 {{add @available attribute to enclosing protocol}}
associatedtype A: NoAvailableProto
associatedtype B: BeforeInliningTargetProto
associatedtype C: AtInliningTargetProto
associatedtype D: BetweenTargetsProto
associatedtype E: AtDeploymentTargetProto
associatedtype F: AfterDeploymentTargetProto // expected-error {{'AfterDeploymentTargetProto' is only available in}}
}
// MARK: - Type aliases
public enum PublicNoAvailableEnumWithTypeAliases { // expected-note 3 {{add @available attribute to enclosing enum}}
public typealias A = NoAvailable
public typealias B = BeforeInliningTarget
public typealias C = AtInliningTarget
public typealias D = BetweenTargets // expected-error {{'BetweenTargets' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add @available attribute to enclosing type alias}}
public typealias E = AtDeploymentTarget // expected-error {{'AtDeploymentTarget' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note {{add @available attribute to enclosing type alias}}
public typealias F = AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add @available attribute to enclosing type alias}}
}
@available(macOS, unavailable)
public enum UnavailableEnumWithTypeAliases {
public typealias A = NoAvailable
public typealias B = BeforeInliningTarget
public typealias C = AtInliningTarget
public typealias D = BetweenTargets
public typealias E = AtDeploymentTarget
public typealias F = AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add @available attribute to enclosing type alias}}
public typealias G = Unavailable
}
@_spi(Private)
public enum SPIEnumWithTypeAliases { // expected-note 1 {{add @available attribute to enclosing enum}}
public typealias A = NoAvailable
public typealias B = BeforeInliningTarget
public typealias C = AtInliningTarget
public typealias D = BetweenTargets
public typealias E = AtDeploymentTarget
public typealias F = AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add @available attribute to enclosing type alias}}
}
enum InternalNoAvailableEnumWithTypeAliases { // expected-note {{add @available attribute to enclosing enum}}
public typealias A = NoAvailable
public typealias B = BeforeInliningTarget
public typealias C = AtInliningTarget
public typealias D = BetweenTargets
public typealias E = AtDeploymentTarget
public typealias F = AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add @available attribute to enclosing type alias}}
}
// MARK: - Class inheritance
// FIXME: Duplicate 'add @available' emitted when classes are nested in a decl
public enum NoAvailableEnumWithClasses {
public class InheritsNoAvailable: NoAvailableClass {}
public class InheritsBeforeInliningTarget: BeforeInliningTargetClass {}
public class InheritsAtInliningTarget: AtInliningTargetClass {}
public class InheritsBetweenTargets: BetweenTargetsClass {} // expected-error {{'BetweenTargetsClass' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}} expected-note 2 {{add @available attribute to enclosing class}}
public class InheritsAtDeploymentTarget: AtDeploymentTargetClass {} // expected-error {{'AtDeploymentTargetClass' is only available in macOS 10.15 or newer; clients of 'Test' may have a lower deployment target}} expected-note 2 {{add @available attribute to enclosing class}}
public class InheritsAfterDeploymentTarget: AfterDeploymentTargetClass {} // expected-error {{'AfterDeploymentTargetClass' is only available in macOS 11 or newer}} expected-note 2 {{add @available attribute to enclosing class}}
// As a special case, downgrade the less available superclasses diagnostic for
// `@usableFromInline` classes.
@usableFromInline
class UFIInheritsBetweenTargets: BetweenTargetsClass {} // expected-warning {{'BetweenTargetsClass' is only available in macOS 10.14.5 or newer; clients of 'Test' may have a lower deployment target}} expected-note 2 {{add @available attribute to enclosing class}}
}
@_spi(Private)
public enum SPIEnumWithClasses {
public class InheritsNoAvailable: NoAvailableClass {}
public class InheritsBeforeInliningTarget: BeforeInliningTargetClass {}
public class InheritsAtInliningTarget: AtInliningTargetClass {}
public class InheritsBetweenTargets: BetweenTargetsClass {}
public class InheritsAtDeploymentTarget: AtDeploymentTargetClass {}
// FIXME: Duplicate 'add @available' note is emitted
public class InheritsAfterDeploymentTarget: AfterDeploymentTargetClass {} // expected-error {{'AfterDeploymentTargetClass' is only available in}} expected-note 2 {{add @available attribute to enclosing class}}
}
@available(macOS, unavailable)
public enum UnavailableEnumWithClasses {
public class InheritsNoAvailable: NoAvailableClass {}
public class InheritsBeforeInliningTarget: BeforeInliningTargetClass {}
public class InheritsAtInliningTarget: AtInliningTargetClass {}
public class InheritsBetweenTargets: BetweenTargetsClass {}
public class InheritsAtDeploymentTarget: AtDeploymentTargetClass {}
public class InheritsAfterDeploymentTarget: AfterDeploymentTargetClass {} // expected-error {{'AfterDeploymentTargetClass' is only available in}} expected-note 2 {{add @available attribute to enclosing class}}
public class InheritsUnavailable: UnavailableClass {}
}
// MARK: - Top-level code
// Top-level code, if somehow present in a resilient module, is treated like
// a non-inlinable function.
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in macOS 11 or newer}} expected-note {{add 'if #available'}}
if #available(macOS 11, *) {
_ = AfterDeploymentTarget()
}
| apache-2.0 |
nearspeak/iOS-SDK | NearspeakDemo/AppDelegate.swift | 1 | 6562 | //
// AppDelegate.swift
// NearspeakDemo
//
// Created by Patrick Steiner on 23.04.15.
// Copyright (c) 2015 Mopius. All rights reserved.
//
import UIKit
import CoreLocation
import NearspeakKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let api = NSKApi(devMode: false)
var pushedTags = Set<String>()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))
setupNotifications()
if NSKManager.sharedInstance.checkForBeaconSupport() {
Log.debug("iBeacons supported")
NSKManager.sharedInstance.addCustomUUID("CEFCC021-E45F-4520-A3AB-9D1EA22873AD") // Nearspeak UUID
NSKManager.sharedInstance.startBeaconMonitoring()
} else {
Log.error("iBeacons not supported")
}
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:.
}
// MARK: - Notifications
private func setupNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onEnterRegionNotification(_:)),
name: NSKConstants.managerNotificationRegionEnterKey,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onExitRegionNotification(_:)),
name: NSKConstants.managerNotificationRegionExitKey,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onNearbyTagsUpdatedNotification(_:)),
name: NSKConstants.managerNotificationNearbyTagsUpdatedKey,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onBluetoothOkNotification(_:)),
name: NSKConstants.managerNotificationBluetoothOkKey,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(AppDelegate.onBluetoothErrorNotification(_:)),
name: NSKConstants.managerNotificationBluetoothErrorKey,
object: nil)
}
func onBluetoothOkNotification(notification: NSNotification) {
Log.debug("Bluetooth OK")
}
func onBluetoothErrorNotification(notification: NSNotification) {
Log.debug("Bluetooth ERROR")
}
func onNearbyTagsUpdatedNotification(notification: NSNotification) {
// copy the nearbyTags from the shared instance
let nearbyTags = NSKManager.sharedInstance.nearbyTags
for tag in nearbyTags {
if let identifier = tag.tagIdentifier {
api.getTagById(tagIdentifier: identifier, requestCompleted: { (succeeded, tag) -> () in
if succeeded {
if let tag = tag {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if !self.pushedTags.contains(identifier) {
self.pushedTags.insert(identifier)
if let bodyText = tag.translation {
self.showLocalPushNotification(title: tag.titleString(), body: bodyText)
} else {
self.showLocalPushNotification(title: tag.titleString(), body: "Default Body")
}
}
})
}
}
})
}
}
}
func onEnterRegionNotification(notification: NSNotification) {
// start discovery to get more infos about the beacon
NSKManager.sharedInstance.startBeaconDiscovery(false)
}
func onExitRegionNotification(notification: NSNotification) {
// stop discovery
NSKManager.sharedInstance.stopBeaconDiscovery()
// reset already pushed tags
pushedTags.removeAll()
}
private func showLocalPushNotification(title notificationTitle: String, body notificationText: String) {
let notification = UILocalNotification()
notification.alertTitle = notificationTitle
if notificationText.isEmpty {
notification.alertBody = "Default Body Text"
} else {
notification.alertBody = notificationText
}
UIApplication.sharedApplication().presentLocalNotificationNow(notification)
}
}
| lgpl-3.0 |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Other/GameKit Support/GKHelper.swift | 2 | 2946 | //
// GKHelper.swift
// WikiRaces
//
// Created by Andrew Finke on 6/24/20.
// Copyright © 2020 Andrew Finke. All rights reserved.
//
import Foundation
import GameKit
import WKRUIKit
#if !MULTIWINDOWDEBUG && !targetEnvironment(macCatalyst)
import FirebaseAnalytics
import FirebaseCrashlytics
#endif
class GKHelper {
enum AuthResult {
case controller(UIViewController)
case error(Error)
case isAuthenticated
}
static let shared = GKHelper()
private var pendingInvite: String?
var inviteHandler: ((String) -> Void)? {
didSet {
pushInviteToHandler()
}
}
private var pendingResult: AuthResult?
var authHandler: ((AuthResult) -> Void)? {
didSet {
pushResultToHandler()
}
}
public var isAuthenticated = false
// MARK: - Initalization -
private init() {}
// MARK: - Handlers -
private func pushResultToHandler() {
guard let result = pendingResult, let handler = authHandler else { return }
DispatchQueue.main.async {
handler(result)
}
pendingResult = nil
}
private func pushInviteToHandler() {
guard let invite = pendingInvite, let handler = inviteHandler else { return }
DispatchQueue.main.async {
handler(invite)
}
pendingInvite = nil
}
// MARK: - Helpers -
func start() {
guard !Defaults.isFastlaneSnapshotInstance else {
return
}
DispatchQueue.global().async {
GKLocalPlayer.local.authenticateHandler = { controller, error in
DispatchQueue.main.async {
if let error = error {
self.pendingResult = .error(error)
} else if let controller = controller {
self.pendingResult = .controller(controller)
} else if GKLocalPlayer.local.isAuthenticated {
self.pendingResult = .isAuthenticated
self.isAuthenticated = true
DispatchQueue.global().asyncAfter(deadline: .now() + 0.1) {
WKRUIPlayerImageManager.shared.connected(to: GKLocalPlayer.local, completion: nil)
}
#if !MULTIWINDOWDEBUG && !targetEnvironment(macCatalyst)
let playerName = GKLocalPlayer.local.alias
Crashlytics.crashlytics().setUserID(playerName)
Analytics.setUserProperty(playerName, forName: "playerName")
#endif
} else {
fatalError()
}
self.pushResultToHandler()
}
}
}
}
func acceptedInvite(code: String) {
pendingInvite = code
pushInviteToHandler()
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/17341-no-stacktrace.swift | 11 | 298 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
enum A {
var d = {
{
{
}
{
func a( ) {
{
}
{
}
deinit {
{
}
struct d {
class a {
let end = [ {
case
{
{
{
var a {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/14347-swift-sourcemanager-getmessage.swift | 11 | 2355 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
}
for {
protocol A? {
class
class A {
class
class
case c,
enum b {
n(v: A<T where T where g: A? {
case c,
( {
e( {
var b {
struct A {
let a {
class
class
class
let start = ( )
e( {
var d {
e( )
struct A {
class
class a {
class
class
func i{
class B<T {
var d {
enum b {
let start = ( {
let c = [ {
( )
case ,
class B {
enum b {
class
case c,
if true {
( )
enum S {
if true {
for {
class a<T where g: a = ( {
class
case ,
class
enum S {
( {
class A? {
class
let a {
class
(f: A
}
struct S<T : a = a<T {
class A {
class
let d {
if true {
( )
enum A {
class A? {
func D Void>(f: A
case ,
for {
enum A {
struct A {
let d {
var d {
func a( {
struct A {
if true {
case ,
if true {
(
class B {
class a {
for {
func b {
enum b {
let a {
class a = [ {
func b { func g {
class B<T where g: A {
var d {
class a {
class B<T where T : A
struct S<T {
case ,
( {
struct B<T where g: A? {
struct d
case ,
func g {
case ,
class
struct A {
class a
if true {
if true {
class A<d
case ,
let d {
class A<T {
enum S {
class
case c,
class
enum S {
var d {
{
var d {
let a {
case c,
class
struct B<T {
class
for {
var d {
let start = a<T : a {
n(v: A
( {
( )
class b {
class
if true {
class B<T {
func g {
class
struct d>(v: A<T where T {
class b {
(f: A {
class a<T {
var d {
}
class
{
class
class
class
class A {
var d {
func D Void>
case c,
struct B<T {
struct S<T : A
if true {
enum S {
(
class a<T {
class
e( {
func i{
B {
class A? {
for
class A {
enum b { func D Void>(f: A<T : A<T {
enum b {
struct B<T where T : a {
case ,
class
e( {
( {
{
class
}
func D Void>
}
if true {
struct A {
}
for {
class
case ,
case c,
case ,
B {
struct A {
class a {
class
case ,
enum b {
{
case c,
func g {
class B<T {
let a {
case c,
class a( {
class A<T : A<T where T : A<T : A<T where g: A? {
let c = [ {
struct A {
let d {
enum S {
struct B<d
case ,
struct d
let a {
class
{
class a {
}
class
n(f: A {
class a<T : A<T : A {
struct A {
func D Void>(
class
{
class
enum S {
class
enum S {
class b {
struct A {
case ,
var b { func g {
enum S {
{
struct A {
e( {
class
func i{
case ,
var b { func i{
class
class
case ,
for
enum b {
func b { func D Void>(
class
class
enum b {
case c,
class B<T {
case ,
class A {
class A {
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/15071-swift-sourcemanager-getmessage.swift | 11 | 292 | // 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 =
var b = ( " " {
struct S {
protocol d {
var d = [ I : {
enum S {
class A {
{
{
dynamicType) "
var d {
class
case ,
| mit |
huangboju/Moots | UICollectionViewLayout/Blueprints-master/Example-iOS/Scenes/LayoutSettingsScenePresenter.swift | 1 | 2648 | protocol LayoutSettingsScenePresentationLogic {
func presentLayoutConfiguration(response: LayoutSettingsScene.GetLayoutConfiguration.Response)
}
class LayoutSettingsScenePresenter: LayoutSettingsScenePresentationLogic {
weak var viewController: LayoutSettingsSceneDisplayLogic?
}
extension LayoutSettingsScenePresenter {
func presentLayoutConfiguration(response: LayoutSettingsScene.GetLayoutConfiguration.Response) {
let noDecimalPlacesFormat = "%.0f"
let oneDecimalPlacesFormat = "%.1f"
let layoutConfiguration = response.layoutConfiguration
let itemsPerRow = String(format: oneDecimalPlacesFormat, (layoutConfiguration.itemsPerRow) ?? (0))
let itemsPerCollumn = String((layoutConfiguration.itemsPerCollumn) ?? (0))
let minimumInteritemSpacing = String(format: noDecimalPlacesFormat, (layoutConfiguration.minimumInteritemSpacing) ?? (0))
let minimumLineSpacing = String(format: noDecimalPlacesFormat, (layoutConfiguration.minimumLineSpacing) ?? (0))
let topSectionInset = String(format: noDecimalPlacesFormat, (layoutConfiguration.sectionInsets?.top) ?? (0))
let leftSectionInset = String(format: noDecimalPlacesFormat, (layoutConfiguration.sectionInsets?.left) ?? (0))
let bottomSectionInset = String(format: noDecimalPlacesFormat, (layoutConfiguration.sectionInsets?.bottom) ?? (0))
let rightSectionInset = String(format: noDecimalPlacesFormat, (layoutConfiguration.sectionInsets?.right) ?? (0))
let viewModel = LayoutSettingsScene.GetLayoutConfiguration.ViewModel(itemsPerRow: itemsPerRow,
itemsPerCollumn: itemsPerCollumn,
minimumInteritemSpacing: minimumInteritemSpacing,
minimumLineSpacing: minimumLineSpacing,
topSectionInset: topSectionInset,
leftSectionInset: leftSectionInset,
bottomSectionInset: bottomSectionInset,
rightSectionInset: rightSectionInset,
dynamicCellHeightEnabled: layoutConfiguration.useDynamicHeight)
viewController?.presentLayoutConfiguration(viewModel: viewModel)
}
}
| mit |
STShenZhaoliang/iOS-GuidesAndSampleCode | 精通Swift设计模式/Chapter 17/SportsStore/SportsStore/NetworkConnection.swift | 1 | 350 | import Foundation
class NetworkConnection {
private let flyweight:NetConnFlyweight;
init() {
self.flyweight = NetConnFlyweightFactory.createFlyweight();
}
func getStockLevel(name:String) -> Int? {
NSThread.sleepForTimeInterval(Double(rand() % 2));
return self.flyweight.getStockLevel(name);
}
}
| mit |
Flinesoft/HandyUIKit | Frameworks/HandyUIKit/IBDesignables/TemplateButton.swift | 1 | 289 | // Copyright © 2019 Flinesoft. All rights reserved.
import UIKit
@IBDesignable
open class TemplateButton: UIButton {
override public func setImage(_ image: UIImage?, for state: UIControl.State) {
super.setImage(image?.withRenderingMode(.alwaysTemplate), for: state)
}
}
| mit |
teads/TeadsSDK-iOS | MediationAdapters/TeadsAppLovinAdapter/Exports.swift | 2 | 189 | //
// Exports.swift
//
//
// Created by Paul NICOLAS on 21/11/2022.
//
/// SPM compatibility: TeadsAdapterCommon sources are exposed as Swift Module
@_exported import TeadsAdapterCommon
| mit |
codefirst/SKK-for-iOS | SKK-Keyboard/ImitationKeyboard/KeyboardConnector.swift | 1 | 10093 | //
// KeyboardConnector.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/19/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
protocol Connectable {
func attachmentPoints(direction: Direction) -> (CGPoint, CGPoint)
func attachmentDirection() -> Direction?
func attach(direction: Direction?) // call with nil to detach
}
// TODO: Xcode crashes
// <ConnectableView: UIView where ConnectableView: Connectable>
class KeyboardConnector: UIView, KeyboardView {
var start: UIView
var end: UIView
var startDir: Direction
var endDir: Direction
// TODO: temporary fix for Swift compiler crash
var startConnectable: Connectable
var endConnectable: Connectable
var convertedStartPoints: (CGPoint, CGPoint)!
var convertedEndPoints: (CGPoint, CGPoint)!
var color: UIColor { didSet { self.setNeedsDisplay() }}
var underColor: UIColor { didSet { self.setNeedsDisplay() }}
var borderColor: UIColor { didSet { self.setNeedsDisplay() }}
var drawUnder: Bool { didSet { self.setNeedsDisplay() }}
var drawBorder: Bool { didSet { self.setNeedsDisplay() }}
var drawShadow: Bool { didSet { self.setNeedsDisplay() }}
var _offset: CGPoint
// TODO: until bug is fixed, make sure start/end and startConnectable/endConnectable are the same object
init(start: UIView, end: UIView, startConnectable: Connectable, endConnectable: Connectable, startDirection: Direction, endDirection: Direction) {
self.start = start
self.end = end
self.startDir = startDirection
self.endDir = endDirection
self.startConnectable = startConnectable
self.endConnectable = endConnectable
self.color = UIColor.whiteColor()
self.underColor = UIColor.grayColor()
self.borderColor = UIColor.blackColor()
self.drawUnder = true
self.drawBorder = true
self.drawShadow = true
self._offset = CGPointZero
super.init(frame: CGRectZero)
self.userInteractionEnabled = false // TODO: why is this even necessary if it's under all the other views?
self.backgroundColor = UIColor.clearColor()
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.resizeFrame()
}
override func layoutSubviews() {
super.layoutSubviews()
self.resizeFrame()
self.setNeedsDisplay()
}
func generateConvertedPoints() {
if self.superview == nil {
return
}
let startPoints = self.startConnectable.attachmentPoints(self.startDir)
let endPoints = self.endConnectable.attachmentPoints(self.endDir)
self.convertedStartPoints = (
self.superview!.convertPoint(startPoints.0, fromView: self.start),
self.superview!.convertPoint(startPoints.1, fromView: self.start))
self.convertedEndPoints = (
self.superview!.convertPoint(endPoints.0, fromView: self.end),
self.superview!.convertPoint(endPoints.1, fromView: self.end))
}
func resizeFrame() {
generateConvertedPoints()
let buffer: CGFloat = 32
self._offset = CGPointMake(buffer/2, buffer/2)
let minX = min(convertedStartPoints.0.x, convertedStartPoints.1.x, convertedEndPoints.0.x, convertedEndPoints.1.x)
let minY = min(convertedStartPoints.0.y, convertedStartPoints.1.y, convertedEndPoints.0.y, convertedEndPoints.1.y)
let maxX = max(convertedStartPoints.0.x, convertedStartPoints.1.x, convertedEndPoints.0.x, convertedEndPoints.1.x)
let maxY = max(convertedStartPoints.0.y, convertedStartPoints.1.y, convertedEndPoints.0.y, convertedEndPoints.1.y)
let width = maxX - minX
let height = maxY - minY
self.frame = CGRectMake(minX - buffer/2, minY - buffer/2, width + buffer, height + buffer)
}
override func drawRect(rect: CGRect) {
// TODO: quick hack
resizeFrame()
let startPoints = self.startConnectable.attachmentPoints(self.startDir)
let endPoints = self.endConnectable.attachmentPoints(self.endDir)
var myConvertedStartPoints = (
self.convertPoint(startPoints.0, fromView: self.start),
self.convertPoint(startPoints.1, fromView: self.start))
let myConvertedEndPoints = (
self.convertPoint(endPoints.0, fromView: self.end),
self.convertPoint(endPoints.1, fromView: self.end))
if self.startDir == self.endDir {
let tempPoint = myConvertedStartPoints.0
myConvertedStartPoints.0 = myConvertedStartPoints.1
myConvertedStartPoints.1 = tempPoint
}
let ctx = UIGraphicsGetCurrentContext()
let csp = CGColorSpaceCreateDeviceRGB()
let path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, myConvertedStartPoints.0.x, myConvertedStartPoints.0.y)
CGPathAddLineToPoint(path, nil, myConvertedEndPoints.1.x, myConvertedEndPoints.1.y)
CGPathAddLineToPoint(path, nil, myConvertedEndPoints.0.x, myConvertedEndPoints.0.y)
CGPathAddLineToPoint(path, nil, myConvertedStartPoints.1.x, myConvertedStartPoints.1.y)
CGPathCloseSubpath(path)
// for now, assuming axis-aligned attachment points
let isVertical = (self.startDir == Direction.Up || self.startDir == Direction.Down) && (self.endDir == Direction.Up || self.endDir == Direction.Down)
var midpoint: CGFloat
if isVertical {
midpoint = myConvertedStartPoints.0.y + (myConvertedEndPoints.1.y - myConvertedStartPoints.0.y) / 2
}
else {
midpoint = myConvertedStartPoints.0.x + (myConvertedEndPoints.1.x - myConvertedStartPoints.0.x) / 2
}
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(myConvertedStartPoints.0)
bezierPath.addCurveToPoint(
myConvertedEndPoints.1,
controlPoint1: (isVertical ?
CGPointMake(myConvertedStartPoints.0.x, midpoint) :
CGPointMake(midpoint, myConvertedStartPoints.0.y)),
controlPoint2: (isVertical ?
CGPointMake(myConvertedEndPoints.1.x, midpoint) :
CGPointMake(midpoint, myConvertedEndPoints.1.y)))
bezierPath.addLineToPoint(myConvertedEndPoints.0)
bezierPath.addCurveToPoint(
myConvertedStartPoints.1,
controlPoint1: (isVertical ?
CGPointMake(myConvertedEndPoints.0.x, midpoint) :
CGPointMake(midpoint, myConvertedEndPoints.0.y)),
controlPoint2: (isVertical ?
CGPointMake(myConvertedStartPoints.1.x, midpoint) :
CGPointMake(midpoint, myConvertedStartPoints.1.y)))
bezierPath.addLineToPoint(myConvertedStartPoints.0)
bezierPath.closePath()
let shadow = UIColor.blackColor().colorWithAlphaComponent(0.35)
let shadowOffset = CGSizeMake(0, 1.5)
let shadowBlurRadius: CGFloat = 12
// shadow is drawn separate from the fill
// http://stackoverflow.com/questions/6709064/coregraphics-quartz-drawing-shadow-on-transparent-alpha-path
// CGContextSaveGState(ctx)
// self.color.setFill()
// CGContextSetShadowWithColor(ctx, shadowOffset, shadowBlurRadius, shadow.CGColor)
// CGContextMoveToPoint(ctx, 0, 0);
// CGContextAddLineToPoint(ctx, self.bounds.width, 0);
// CGContextAddLineToPoint(ctx, self.bounds.width, self.bounds.height);
// CGContextAddLineToPoint(ctx, 0, self.bounds.height);
// CGContextClosePath(ctx);
// CGContextAddPath(ctx, bezierPath.CGPath)
// CGContextClip(ctx)
// CGContextAddPath(ctx, bezierPath.CGPath)
// CGContextDrawPath(ctx, kCGPathFillStroke)
// CGContextRestoreGState(ctx)
// CGContextAddPath(ctx, bezierPath.CGPath)
// CGContextClip(ctx)
CGContextSaveGState(ctx)
UIColor.blackColor().setFill()
CGContextSetShadowWithColor(ctx, shadowOffset, shadowBlurRadius, shadow.CGColor)
bezierPath.fill()
CGContextRestoreGState(ctx)
if self.drawUnder {
CGContextTranslateCTM(ctx, 0, 1)
self.underColor.setFill()
CGContextAddPath(ctx, bezierPath.CGPath)
CGContextFillPath(ctx)
CGContextTranslateCTM(ctx, 0, -1)
}
self.color.setFill()
bezierPath.fill()
if self.drawBorder {
self.borderColor.setStroke()
CGContextSetLineWidth(ctx, 0.5)
CGContextMoveToPoint(ctx, myConvertedStartPoints.0.x, myConvertedStartPoints.0.y)
CGContextAddCurveToPoint(
ctx,
(isVertical ? myConvertedStartPoints.0.x : midpoint),
(isVertical ? midpoint : myConvertedStartPoints.0.y),
(isVertical ? myConvertedEndPoints.1.x : midpoint),
(isVertical ? midpoint : myConvertedEndPoints.1.y),
myConvertedEndPoints.1.x,
myConvertedEndPoints.1.y)
CGContextStrokePath(ctx)
CGContextMoveToPoint(ctx, myConvertedEndPoints.0.x, myConvertedEndPoints.0.y)
CGContextAddCurveToPoint(
ctx,
(isVertical ? myConvertedEndPoints.0.x : midpoint),
(isVertical ? midpoint : myConvertedEndPoints.0.y),
(isVertical ? myConvertedStartPoints.1.x : midpoint),
(isVertical ? midpoint : myConvertedStartPoints.1.y),
myConvertedStartPoints.1.x,
myConvertedStartPoints.1.y)
CGContextStrokePath(ctx)
}
}
}
| gpl-2.0 |
maikotrindade/ios-basics | HelloWorld.playground/Contents.swift | 1 | 1483 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var myVariable = 123 //variable
let myConstant = 123456 //constant
let anExplicit : Int = 2
myVariable+=1000
//myConstant = 2 //Cannot assing a value to a constant
var someVariable : Int
//someVariable + = 4 // error: not initial value
var sampleText = "Welcome!"
print (sampleText)
var anOptionalInt : Int? = nil
anOptionalInt = 55
if anOptionalInt != nil {
print ("It has a value:\(anOptionalInt!)")
} else {
print ("It hasn't a value!")
}
var unwrappedOptionalInteger : Int!
unwrappedOptionalInteger = 4
var anInteger = 40
let aString = String(anInteger)
//Tuples
let aTuple = (1, "YES", 34, "NO")
let firstNumber = aTuple.0
let secondText = aTuple.3
//adding labels
let anotherTuple = (aNumber : 1111, aString : "My String")
let theOtherNumber = anotherTuple.aNumber
//Arrays
let arrayOfIntegers : [Int] = [1,2,3,4,5,6]
let mixedArray = [6,4, "String"]
var testArray = [1,2,3,4,5]
testArray.append(6)
testArray.insert(7, atIndex: 6)
testArray.removeLast()
testArray.removeAtIndex(1)
testArray.count
var arrayOfStrings = ["one","two","three","four"]
//Dictionary
var crew = [
"Captain" : "TPA",
"First Officer" : "TPB",
"Cabin Hostess" : "TPC",
"Cabin Hostes" : "TPD"]
crew["Captain"]
crew["Intern"] = "BBB"
crew.description
var aNumberDic = [1:"value"]
aNumberDic[21]="ok"
aNumberDic.description
| gpl-3.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/25516-swift-diagnosticengine-emitdiagnostic.swift | 7 | 210 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func
i{enum e{class C:Int}struct B<T:T.c
| mit |
huonw/swift | test/NameBinding/import-resolution-2.swift | 31 | 979 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/abcde.swift
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/aeiou.swift
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/asdf.swift
// RUN: %target-swift-frontend -emit-module -o %t -I %t %S/Inputs/letters.swift
// RUN: %target-swift-frontend -typecheck %s -I %t -sdk "" -verify
import letters
import aeiou
import struct asdf.A
import struct abcde.A
var uA : A // expected-error {{'A' is ambiguous for type lookup in this context}}
var uB : B = abcde.B()
var uC : C = letters.C(b: uB)
var uD : D = asdf.D()
var uE : E = aeiou.E()
var uF : F = letters.F()
var qA1 : aeiou.A
var qA2 : asdf.A
var qA3 : abcde.A
var uS : S // expected-error {{use of undeclared type 'S'}}
var qS1 : letters.S // expected-error {{no type named 'S' in module 'letters'}}
var qS2 : asdf.S // expected-error {{no type named 'S' in module 'asdf'}}
// but...!
letters.consumeS(letters.myS)
| apache-2.0 |
mitsuse/la | Sources/La/Matrix_NxN.swift | 1 | 202 | extension Matrix where M == N {
public static func identity() -> Matrix<M, N, Field> { return Field.matrix_identity() }
}
extension Matrix where M == N {
public var order: Int32 { return n }
}
| mit |
CaptainTeemo/Saffron | Saffron/ImageEditor.swift | 1 | 6380 | //
// ImageEditor.swift
// Saffron
//
// Created by CaptainTeemo on 5/3/16.
// Copyright © 2016 Captain Teemo. All rights reserved.
//
import Accelerate
extension UIImage {
func blur(with radius: CGFloat, iterations: Int = 2, ratio: CGFloat = 1.2, blendColor: UIColor? = nil) -> UIImage? {
if floorf(Float(size.width)) * floorf(Float(size.height)) <= 0.0 || radius <= 0 {
return self
}
var imageRef = cgImage
if !isARGB8888(imageRef: imageRef!) {
let context = createARGB8888BitmapContext(from: imageRef!)
let rect = CGRect(x: 0, y: 0, width: imageRef!.width, height: imageRef!.height)
context?.draw(imageRef!, in: rect)
imageRef = context?.makeImage()
}
var boxSize = UInt32(radius * scale * ratio)
if boxSize % 2 == 0 {
boxSize += 1
}
let height = imageRef!.height
let width = imageRef!.width
let rowBytes = imageRef!.bytesPerRow
let bytes = rowBytes * height
let inData = malloc(bytes)
var inBuffer = vImage_Buffer(data: inData, height: UInt(height), width: UInt(width), rowBytes: rowBytes)
let outData = malloc(bytes)
var outBuffer = vImage_Buffer(data: outData, height: UInt(height), width: UInt(width), rowBytes: rowBytes)
let tempFlags = vImage_Flags(kvImageEdgeExtend + kvImageGetTempBufferSize)
let tempSize = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, boxSize, boxSize, nil, tempFlags)
let tempBuffer = malloc(tempSize)
let provider = imageRef!.dataProvider
let copy = provider!.data
let source = CFDataGetBytePtr(copy)
memcpy(inBuffer.data, source, bytes)
let flags = vImage_Flags(kvImageEdgeExtend)
for _ in 0 ..< iterations {
vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, tempBuffer, 0, 0, boxSize, boxSize, nil, flags)
let temp = inBuffer.data
inBuffer.data = outBuffer.data
outBuffer.data = temp
}
let colorSpace = imageRef!.colorSpace
let bitmapInfo = imageRef!.bitmapInfo
let bitmapContext = CGContext(data: inBuffer.data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: rowBytes, space: colorSpace!, bitmapInfo: bitmapInfo.rawValue)
defer {
free(outBuffer.data)
free(tempBuffer)
free(inBuffer.data)
}
if let color = blendColor {
bitmapContext!.setFillColor(color.cgColor)
bitmapContext!.setBlendMode(CGBlendMode.plusLighter)
bitmapContext!.fill(CGRect(x: 0, y: 0, width: width, height: height))
}
if let bitmap = bitmapContext!.makeImage() {
return UIImage(cgImage: bitmap, scale: scale, orientation: imageOrientation)
}
return nil
}
private func isARGB8888(imageRef: CGImage) -> Bool {
let alphaInfo = imageRef.alphaInfo
let isAlphaOnFirstPlace = (CGImageAlphaInfo.first == alphaInfo || CGImageAlphaInfo.first == alphaInfo || CGImageAlphaInfo.noneSkipFirst == alphaInfo || CGImageAlphaInfo.noneSkipLast == alphaInfo)
return imageRef.bitsPerPixel == 32 && imageRef.bitsPerComponent == 8 && (imageRef.bitmapInfo.rawValue & CGBitmapInfo.alphaInfoMask.rawValue) > 0 && isAlphaOnFirstPlace
}
private func createARGB8888BitmapContext(from image: CGImage) -> CGContext? {
let pixelWidth = image.width
let pixelHeight = image.height
let bitmapBytesPerFow = pixelWidth * 4
let bitmapByCount = bitmapBytesPerFow * pixelHeight
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapData = UnsafeMutableRawPointer.allocate(bytes: bitmapByCount, alignedTo: bitmapByCount)
let context = CGContext(data: bitmapData, width: pixelWidth, height: pixelHeight, bitsPerComponent: 8, bytesPerRow: bitmapBytesPerFow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
return context
}
func roundCorner(_ radius: CGFloat) -> UIImage? {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
let path = UIBezierPath(roundedRect: rect, cornerRadius: radius)
context!.addPath(path.cgPath)
context!.clip()
draw(in: rect)
let output = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return output
}
func oval() -> UIImage? {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
let path = UIBezierPath(ovalIn: rect)
context!.addPath(path.cgPath)
context!.clip()
draw(in: rect)
let output = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return output
}
func scaleToFill(_ targetSize: CGSize) -> UIImage {
let targetAspect = targetSize.width / targetSize.height
let aspect = size.width / size.height
var scaledSize = size
if targetAspect < aspect {
scaledSize.width = ceil(size.height * targetAspect)
} else {
scaledSize.height = ceil(size.width * targetAspect)
}
let cropRect = CGRect(origin: CGPoint(x: -abs(size.width - scaledSize.width) / 2, y: -abs(size.height - scaledSize.height) / 2), size: scaledSize)
UIGraphicsBeginImageContextWithOptions(scaledSize, false, UIScreen.main.nativeScale)
let context = UIGraphicsGetCurrentContext()
let path = UIBezierPath(rect: CGRect(origin: CGPoint.zero, size: size)).cgPath
context!.addPath(path)
context!.clip()
draw(in: CGRect(origin: cropRect.origin, size: size))
let output = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return output!
}
}
| mit |
MarcoSantarossa/SwiftyToggler | Source/FeaturesList/Coordinator/FeaturesListCoordinator.swift | 1 | 2952 | //
// FeaturesListCoordinator.swift
//
// Copyright (c) 2017 Marco Santarossa (https://marcosantadev.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
protocol FeaturesListCoordinatorProtocol {
func start(presentingMode: PresentingMode) throws
}
final class FeaturesListCoordinator: FeaturesListCoordinatorProtocol {
fileprivate(set) var window: UIWindowProtocol?
func start(presentingMode: PresentingMode) throws {
switch presentingMode {
case .modal(let parentWindow):
try presentModal(in: parentWindow)
case .inParent(let parentViewController, let parentView):
presentIn(parentViewController, parentView: parentView)
}
}
private func presentModal(in parentWindow: UIWindowProtocol) throws {
guard self.window == nil else {
throw SwiftyTogglerError.modalFeaturesListAlreadyPresented
}
parentWindow.rootViewControllerType = createFeaturestListViewController(presentingMode: .modal(parentWindow))
parentWindow.makeKeyAndVisible()
parentWindow.backgroundColor = .white
self.window = parentWindow
}
private func createFeaturestListViewController(presentingMode: PresentingMode) -> FeaturesListViewController {
let viewModel = FeaturesListViewModel(presentingMode: presentingMode)
viewModel.delegate = self
return FeaturesListViewController(viewModel: viewModel)
}
private func presentIn(_ parentViewController: UIViewControllerProtocol, parentView: UIViewProtocol?) {
let viewController = createFeaturestListViewController(presentingMode: .inParent(parentViewController, parentView))
parentViewController.addFillerChildViewController(viewController, toView: parentView)
}
}
extension FeaturesListCoordinator: FeaturesListViewModelDelegate {
func featuresListViewModelNeedsClose() {
destroyWindow()
}
private func destroyWindow() {
window?.isHidden = true
window?.rootViewControllerType = nil
window = nil
}
}
| mit |
djabo/DataCache | DataCache.swift | 1 | 1911 | //
// DataCache.swift
//
import UIKit
import ImageIO
protocol Datable {
init?(data: NSData)
func toData() -> NSData
}
extension UIImage: Datable {
func toData() -> NSData {
return UIImagePNGRepresentation(self)
}
}
class DataCache<T: Datable> {
private let queue = NSOperationQueue()
private let cache = LRUCache<NSURL, T>(maxSize: 100)
var count: Int { return self.cache.count }
init() {
self.queue.name = "DataCacheQueue"
self.queue.maxConcurrentOperationCount = 10;
}
func clear() {
self.cache.clear()
}
subscript (url: NSURL) -> T? {
get {
if let data = NSData(contentsOfURL: url) {
if let datable = T(data: data) {
self.cache[url] = datable
return datable
}
}
return nil
}
}
func containsKey(key: NSURL) -> Bool {
return self.cache.containsKey(key)
}
func objectForURL(url: NSURL, block: ((url: NSURL, object: T) -> Void)?) -> T? {
if let cachedImage = self.cache[url] {
return cachedImage
} else {
self.queue.addOperationWithBlock() {
if let data = NSData(contentsOfURL: url) {
if data.length > 0 {
if let datable = T(data: data) {
datable.toData()
self.cache[url] = datable
if block != nil {
NSOperationQueue.mainQueue().addOperationWithBlock() {
block!(url: url, object: datable)
}
}
}
}
}
}
return nil
}
}
}
| mit |
Zewo/Core | Tests/LinuxMain.swift | 2 | 314 | import XCTest
@testable import AxisTests
XCTMain([
testCase(ConfigurationTests.allTests),
testCase(JSONTests.allTests),
testCase(LoggerTests.allTests),
testCase(MapConvertibleTests.allTests),
testCase(MapTests.allTests),
testCase(StringTests.allTests),
testCase(URLTests.allTests),
])
| mit |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Personalize/Personalize_API.swift | 1 | 33916 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
@_exported import SotoCore
/*
Client object for interacting with AWS Personalize service.
Amazon Personalize is a machine learning service that makes it easy to add individualized recommendations to customers.
*/
public struct Personalize: AWSService {
// MARK: Member variables
public let client: AWSClient
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the Personalize client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
amzTarget: "AmazonPersonalize",
service: "personalize",
serviceProtocol: .json(version: "1.1"),
apiVersion: "2018-05-22",
endpoint: endpoint,
errorType: PersonalizeErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Creates a batch inference job. The operation can handle up to 50 million records and the input file must be in JSON format. For more information, see recommendations-batch.
public func createBatchInferenceJob(_ input: CreateBatchInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateBatchInferenceJobResponse> {
return self.client.execute(operation: "CreateBatchInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a campaign by deploying a solution version. When a client calls the GetRecommendations and GetPersonalizedRanking APIs, a campaign is specified in the request. Minimum Provisioned TPS and Auto-Scaling A transaction is a single GetRecommendations or GetPersonalizedRanking call. Transactions per second (TPS) is the throughput and unit of billing for Amazon Personalize. The minimum provisioned TPS (minProvisionedTPS) specifies the baseline throughput provisioned by Amazon Personalize, and thus, the minimum billing charge. If your TPS increases beyond minProvisionedTPS, Amazon Personalize auto-scales the provisioned capacity up and down, but never below minProvisionedTPS, to maintain a 70% utilization. There's a short time delay while the capacity is increased that might cause loss of transactions. It's recommended to start with a low minProvisionedTPS, track your usage using Amazon CloudWatch metrics, and then increase the minProvisionedTPS as necessary. Status A campaign can be in one of the following states: CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED DELETE PENDING > DELETE IN_PROGRESS To get the campaign status, call DescribeCampaign. Wait until the status of the campaign is ACTIVE before asking the campaign for recommendations. Related APIs ListCampaigns DescribeCampaign UpdateCampaign DeleteCampaign
public func createCampaign(_ input: CreateCampaignRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateCampaignResponse> {
return self.client.execute(operation: "CreateCampaign", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates an empty dataset and adds it to the specified dataset group. Use CreateDatasetImportJob to import your training data to a dataset. There are three types of datasets: Interactions Items Users Each dataset type has an associated schema with required field types. Only the Interactions dataset is required in order to train a model (also referred to as creating a solution). A dataset can be in one of the following states: CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED DELETE PENDING > DELETE IN_PROGRESS To get the status of the dataset, call DescribeDataset. Related APIs CreateDatasetGroup ListDatasets DescribeDataset DeleteDataset
public func createDataset(_ input: CreateDatasetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDatasetResponse> {
return self.client.execute(operation: "CreateDataset", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates an empty dataset group. A dataset group contains related datasets that supply data for training a model. A dataset group can contain at most three datasets, one for each type of dataset: Interactions Items Users To train a model (create a solution), a dataset group that contains an Interactions dataset is required. Call CreateDataset to add a dataset to the group. A dataset group can be in one of the following states: CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED DELETE PENDING To get the status of the dataset group, call DescribeDatasetGroup. If the status shows as CREATE FAILED, the response includes a failureReason key, which describes why the creation failed. You must wait until the status of the dataset group is ACTIVE before adding a dataset to the group. You can specify an AWS Key Management Service (KMS) key to encrypt the datasets in the group. If you specify a KMS key, you must also include an AWS Identity and Access Management (IAM) role that has permission to access the key. APIs that require a dataset group ARN in the request CreateDataset CreateEventTracker CreateSolution Related APIs ListDatasetGroups DescribeDatasetGroup DeleteDatasetGroup
public func createDatasetGroup(_ input: CreateDatasetGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDatasetGroupResponse> {
return self.client.execute(operation: "CreateDatasetGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a job that imports training data from your data source (an Amazon S3 bucket) to an Amazon Personalize dataset. To allow Amazon Personalize to import the training data, you must specify an AWS Identity and Access Management (IAM) role that has permission to read from the data source, as Amazon Personalize makes a copy of your data and processes it in an internal AWS system. The dataset import job replaces any previous data in the dataset. Status A dataset import job can be in one of the following states: CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED To get the status of the import job, call DescribeDatasetImportJob, providing the Amazon Resource Name (ARN) of the dataset import job. The dataset import is complete when the status shows as ACTIVE. If the status shows as CREATE FAILED, the response includes a failureReason key, which describes why the job failed. Importing takes time. You must wait until the status shows as ACTIVE before training a model using the dataset. Related APIs ListDatasetImportJobs DescribeDatasetImportJob
public func createDatasetImportJob(_ input: CreateDatasetImportJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDatasetImportJobResponse> {
return self.client.execute(operation: "CreateDatasetImportJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates an event tracker that you use when sending event data to the specified dataset group using the PutEvents API. When Amazon Personalize creates an event tracker, it also creates an event-interactions dataset in the dataset group associated with the event tracker. The event-interactions dataset stores the event data from the PutEvents call. The contents of this dataset are not available to the user. Only one event tracker can be associated with a dataset group. You will get an error if you call CreateEventTracker using the same dataset group as an existing event tracker. When you send event data you include your tracking ID. The tracking ID identifies the customer and authorizes the customer to send the data. The event tracker can be in one of the following states: CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED DELETE PENDING > DELETE IN_PROGRESS To get the status of the event tracker, call DescribeEventTracker. The event tracker must be in the ACTIVE state before using the tracking ID. Related APIs ListEventTrackers DescribeEventTracker DeleteEventTracker
public func createEventTracker(_ input: CreateEventTrackerRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateEventTrackerResponse> {
return self.client.execute(operation: "CreateEventTracker", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a recommendation filter. For more information, see Using Filters with Amazon Personalize.
public func createFilter(_ input: CreateFilterRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateFilterResponse> {
return self.client.execute(operation: "CreateFilter", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates an Amazon Personalize schema from the specified schema string. The schema you create must be in Avro JSON format. Amazon Personalize recognizes three schema variants. Each schema is associated with a dataset type and has a set of required field and keywords. You specify a schema when you call CreateDataset. Related APIs ListSchemas DescribeSchema DeleteSchema
public func createSchema(_ input: CreateSchemaRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateSchemaResponse> {
return self.client.execute(operation: "CreateSchema", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates the configuration for training a model. A trained model is known as a solution. After the configuration is created, you train the model (create a solution) by calling the CreateSolutionVersion operation. Every time you call CreateSolutionVersion, a new version of the solution is created. After creating a solution version, you check its accuracy by calling GetSolutionMetrics. When you are satisfied with the version, you deploy it using CreateCampaign. The campaign provides recommendations to a client through the GetRecommendations API. To train a model, Amazon Personalize requires training data and a recipe. The training data comes from the dataset group that you provide in the request. A recipe specifies the training algorithm and a feature transformation. You can specify one of the predefined recipes provided by Amazon Personalize. Alternatively, you can specify performAutoML and Amazon Personalize will analyze your data and select the optimum USER_PERSONALIZATION recipe for you. Status A solution can be in one of the following states: CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED DELETE PENDING > DELETE IN_PROGRESS To get the status of the solution, call DescribeSolution. Wait until the status shows as ACTIVE before calling CreateSolutionVersion. Related APIs ListSolutions CreateSolutionVersion DescribeSolution DeleteSolution ListSolutionVersions DescribeSolutionVersion
public func createSolution(_ input: CreateSolutionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateSolutionResponse> {
return self.client.execute(operation: "CreateSolution", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Trains or retrains an active solution. A solution is created using the CreateSolution operation and must be in the ACTIVE state before calling CreateSolutionVersion. A new version of the solution is created every time you call this operation. Status A solution version can be in one of the following states: CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED To get the status of the version, call DescribeSolutionVersion. Wait until the status shows as ACTIVE before calling CreateCampaign. If the status shows as CREATE FAILED, the response includes a failureReason key, which describes why the job failed. Related APIs ListSolutionVersions DescribeSolutionVersion ListSolutions CreateSolution DescribeSolution DeleteSolution
public func createSolutionVersion(_ input: CreateSolutionVersionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateSolutionVersionResponse> {
return self.client.execute(operation: "CreateSolutionVersion", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Removes a campaign by deleting the solution deployment. The solution that the campaign is based on is not deleted and can be redeployed when needed. A deleted campaign can no longer be specified in a GetRecommendations request. For more information on campaigns, see CreateCampaign.
@discardableResult public func deleteCampaign(_ input: DeleteCampaignRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteCampaign", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a dataset. You can't delete a dataset if an associated DatasetImportJob or SolutionVersion is in the CREATE PENDING or IN PROGRESS state. For more information on datasets, see CreateDataset.
@discardableResult public func deleteDataset(_ input: DeleteDatasetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteDataset", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a dataset group. Before you delete a dataset group, you must delete the following: All associated event trackers. All associated solutions. All datasets in the dataset group.
@discardableResult public func deleteDatasetGroup(_ input: DeleteDatasetGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteDatasetGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the event tracker. Does not delete the event-interactions dataset from the associated dataset group. For more information on event trackers, see CreateEventTracker.
@discardableResult public func deleteEventTracker(_ input: DeleteEventTrackerRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteEventTracker", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a filter.
@discardableResult public func deleteFilter(_ input: DeleteFilterRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteFilter", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a schema. Before deleting a schema, you must delete all datasets referencing the schema. For more information on schemas, see CreateSchema.
@discardableResult public func deleteSchema(_ input: DeleteSchemaRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteSchema", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes all versions of a solution and the Solution object itself. Before deleting a solution, you must delete all campaigns based on the solution. To determine what campaigns are using the solution, call ListCampaigns and supply the Amazon Resource Name (ARN) of the solution. You can't delete a solution if an associated SolutionVersion is in the CREATE PENDING or IN PROGRESS state. For more information on solutions, see CreateSolution.
@discardableResult public func deleteSolution(_ input: DeleteSolutionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteSolution", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the given algorithm.
public func describeAlgorithm(_ input: DescribeAlgorithmRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeAlgorithmResponse> {
return self.client.execute(operation: "DescribeAlgorithm", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets the properties of a batch inference job including name, Amazon Resource Name (ARN), status, input and output configurations, and the ARN of the solution version used to generate the recommendations.
public func describeBatchInferenceJob(_ input: DescribeBatchInferenceJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeBatchInferenceJobResponse> {
return self.client.execute(operation: "DescribeBatchInferenceJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the given campaign, including its status. A campaign can be in one of the following states: CREATE PENDING > CREATE IN_PROGRESS > ACTIVE -or- CREATE FAILED DELETE PENDING > DELETE IN_PROGRESS When the status is CREATE FAILED, the response includes the failureReason key, which describes why. For more information on campaigns, see CreateCampaign.
public func describeCampaign(_ input: DescribeCampaignRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeCampaignResponse> {
return self.client.execute(operation: "DescribeCampaign", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the given dataset. For more information on datasets, see CreateDataset.
public func describeDataset(_ input: DescribeDatasetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDatasetResponse> {
return self.client.execute(operation: "DescribeDataset", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the given dataset group. For more information on dataset groups, see CreateDatasetGroup.
public func describeDatasetGroup(_ input: DescribeDatasetGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDatasetGroupResponse> {
return self.client.execute(operation: "DescribeDatasetGroup", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the dataset import job created by CreateDatasetImportJob, including the import job status.
public func describeDatasetImportJob(_ input: DescribeDatasetImportJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDatasetImportJobResponse> {
return self.client.execute(operation: "DescribeDatasetImportJob", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes an event tracker. The response includes the trackingId and status of the event tracker. For more information on event trackers, see CreateEventTracker.
public func describeEventTracker(_ input: DescribeEventTrackerRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeEventTrackerResponse> {
return self.client.execute(operation: "DescribeEventTracker", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes the given feature transformation.
public func describeFeatureTransformation(_ input: DescribeFeatureTransformationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeFeatureTransformationResponse> {
return self.client.execute(operation: "DescribeFeatureTransformation", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes a filter's properties.
public func describeFilter(_ input: DescribeFilterRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeFilterResponse> {
return self.client.execute(operation: "DescribeFilter", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes a recipe. A recipe contains three items: An algorithm that trains a model. Hyperparameters that govern the training. Feature transformation information for modifying the input data before training. Amazon Personalize provides a set of predefined recipes. You specify a recipe when you create a solution with the CreateSolution API. CreateSolution trains a model by using the algorithm in the specified recipe and a training dataset. The solution, when deployed as a campaign, can provide recommendations using the GetRecommendations API.
public func describeRecipe(_ input: DescribeRecipeRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeRecipeResponse> {
return self.client.execute(operation: "DescribeRecipe", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes a schema. For more information on schemas, see CreateSchema.
public func describeSchema(_ input: DescribeSchemaRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeSchemaResponse> {
return self.client.execute(operation: "DescribeSchema", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes a solution. For more information on solutions, see CreateSolution.
public func describeSolution(_ input: DescribeSolutionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeSolutionResponse> {
return self.client.execute(operation: "DescribeSolution", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes a specific version of a solution. For more information on solutions, see CreateSolution.
public func describeSolutionVersion(_ input: DescribeSolutionVersionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeSolutionVersionResponse> {
return self.client.execute(operation: "DescribeSolutionVersion", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets the metrics for the specified solution version.
public func getSolutionMetrics(_ input: GetSolutionMetricsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetSolutionMetricsResponse> {
return self.client.execute(operation: "GetSolutionMetrics", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets a list of the batch inference jobs that have been performed off of a solution version.
public func listBatchInferenceJobs(_ input: ListBatchInferenceJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListBatchInferenceJobsResponse> {
return self.client.execute(operation: "ListBatchInferenceJobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of campaigns that use the given solution. When a solution is not specified, all the campaigns associated with the account are listed. The response provides the properties for each campaign, including the Amazon Resource Name (ARN). For more information on campaigns, see CreateCampaign.
public func listCampaigns(_ input: ListCampaignsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListCampaignsResponse> {
return self.client.execute(operation: "ListCampaigns", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of dataset groups. The response provides the properties for each dataset group, including the Amazon Resource Name (ARN). For more information on dataset groups, see CreateDatasetGroup.
public func listDatasetGroups(_ input: ListDatasetGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDatasetGroupsResponse> {
return self.client.execute(operation: "ListDatasetGroups", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of dataset import jobs that use the given dataset. When a dataset is not specified, all the dataset import jobs associated with the account are listed. The response provides the properties for each dataset import job, including the Amazon Resource Name (ARN). For more information on dataset import jobs, see CreateDatasetImportJob. For more information on datasets, see CreateDataset.
public func listDatasetImportJobs(_ input: ListDatasetImportJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDatasetImportJobsResponse> {
return self.client.execute(operation: "ListDatasetImportJobs", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the list of datasets contained in the given dataset group. The response provides the properties for each dataset, including the Amazon Resource Name (ARN). For more information on datasets, see CreateDataset.
public func listDatasets(_ input: ListDatasetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDatasetsResponse> {
return self.client.execute(operation: "ListDatasets", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the list of event trackers associated with the account. The response provides the properties for each event tracker, including the Amazon Resource Name (ARN) and tracking ID. For more information on event trackers, see CreateEventTracker.
public func listEventTrackers(_ input: ListEventTrackersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListEventTrackersResponse> {
return self.client.execute(operation: "ListEventTrackers", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all filters that belong to a given dataset group.
public func listFilters(_ input: ListFiltersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListFiltersResponse> {
return self.client.execute(operation: "ListFilters", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of available recipes. The response provides the properties for each recipe, including the recipe's Amazon Resource Name (ARN).
public func listRecipes(_ input: ListRecipesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListRecipesResponse> {
return self.client.execute(operation: "ListRecipes", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the list of schemas associated with the account. The response provides the properties for each schema, including the Amazon Resource Name (ARN). For more information on schemas, see CreateSchema.
public func listSchemas(_ input: ListSchemasRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListSchemasResponse> {
return self.client.execute(operation: "ListSchemas", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of solution versions for the given solution. When a solution is not specified, all the solution versions associated with the account are listed. The response provides the properties for each solution version, including the Amazon Resource Name (ARN). For more information on solutions, see CreateSolution.
public func listSolutionVersions(_ input: ListSolutionVersionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListSolutionVersionsResponse> {
return self.client.execute(operation: "ListSolutionVersions", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of solutions that use the given dataset group. When a dataset group is not specified, all the solutions associated with the account are listed. The response provides the properties for each solution, including the Amazon Resource Name (ARN). For more information on solutions, see CreateSolution.
public func listSolutions(_ input: ListSolutionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListSolutionsResponse> {
return self.client.execute(operation: "ListSolutions", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates a campaign by either deploying a new solution or changing the value of the campaign's minProvisionedTPS parameter. To update a campaign, the campaign status must be ACTIVE or CREATE FAILED. Check the campaign status using the DescribeCampaign API. You must wait until the status of the updated campaign is ACTIVE before asking the campaign for recommendations. For more information on campaigns, see CreateCampaign.
public func updateCampaign(_ input: UpdateCampaignRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateCampaignResponse> {
return self.client.execute(operation: "UpdateCampaign", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension Personalize {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: Personalize, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| apache-2.0 |
VeinGuo/VGPlayer | VGPlayer/Classes/MediaCache/VGPlayerCacheManager.swift | 1 | 7470 | //
// VGPlayerCacheManager.swift
// VGPlayer
//
// Created by Vein on 2017/6/22.
// Copyright © 2017年 Vein. All rights reserved.
//
import Foundation
public extension Notification.Name {
public static var VGPlayerCacheManagerDidUpdateCache = Notification.Name.init("com.vein.VGplayer.CacheManagerDidUpdateCache")
public static var VGPlayerCacheManagerDidFinishCache = Notification.Name.init("com.vein.VGplayer.CacheManagerDidFinishCache")
public static var VGPlayerCacheManagerDidCleanCache = Notification.Name.init("com.vein.VGplayer.CacheManagerDidCleanCache")
}
open class VGPlayerCacheManager: NSObject {
static public let VGPlayerCacheConfigurationKey: String = "VGPlayerCacheConfigurationKey"
static public let VGPlayerCacheErrorKey: String = "VGPlayerCacheErrorKey"
static public let VGPlayerCleanCacheKey: String = "VGPlayerCleanCacheKey"
public static var mediaCacheNotifyInterval = 0.1
fileprivate let ioQueue = DispatchQueue(label: "com.vgplayer.ioQueue")
fileprivate var fileManager: FileManager!
public static let shared = VGPlayerCacheManager()
open private(set) var cacheConfig = VGPlayerCacheConfiguration()
public override init() {
super.init()
ioQueue.sync { fileManager = FileManager() }
}
static public func cacheDirectory() -> String {
return NSTemporaryDirectory().appending("vgplayerCache")
}
static public func cacheFilePath(for url: URL) -> String {
if let cacheFolder = url.lastPathComponent.components(separatedBy: ".").first {
let cacheFilePath = (cacheDirectory().appending("/\(cacheFolder)") as NSString).appendingPathComponent(url.lastPathComponent)
print(cacheFilePath)
return cacheFilePath
}
return (cacheDirectory() as NSString).appendingPathComponent(url.lastPathComponent)
}
static public func cacheConfiguration(forURL url: URL) -> VGPlayerCacheMediaConfiguration {
let filePath = cacheFilePath(for: url)
let configuration = VGPlayerCacheMediaConfiguration.configuration(filePath: filePath)
return configuration
}
open func calculateCacheSize(completion handler: @escaping ((_ size: UInt) -> ())) {
ioQueue.async {
let cacheDirectory = VGPlayerCacheManager.cacheDirectory()
let (_, diskCacheSize, _) = self.cachedFiles(atPath: cacheDirectory, onlyForCacheSize: true)
DispatchQueue.main.async {
handler(diskCacheSize)
}
}
}
open func cleanAllCache() {
ioQueue.sync {
do {
let cacheDirectory = VGPlayerCacheManager.cacheDirectory()
try fileManager.removeItem(atPath: cacheDirectory)
} catch { }
}
}
open func cleanOldFiles(completion handler: (()->())? = nil) {
ioQueue.sync {
let cacheDirectory = VGPlayerCacheManager.cacheDirectory()
var (URLsToDelete, diskCacheSize, cachedFiles) = self.cachedFiles(atPath: cacheDirectory, onlyForCacheSize: false)
for fileURL in URLsToDelete {
do {
try fileManager.removeItem(at: fileURL)
} catch _ { }
}
if cacheConfig.maxCacheSize > 0 && diskCacheSize > cacheConfig.maxCacheSize {
let targetSize = cacheConfig.maxCacheSize / 2
let sortedFiles = cachedFiles.keysSortedByValue {
resourceValue1, resourceValue2 -> Bool in
if let date1 = resourceValue1.contentAccessDate,
let date2 = resourceValue2.contentAccessDate
{
return date1.compare(date2) == .orderedAscending
}
return true
}
for fileURL in sortedFiles {
let (_, cacheSize, _) = self.cachedFiles(atPath: fileURL.path, onlyForCacheSize: true)
diskCacheSize -= cacheSize
do {
try fileManager.removeItem(at: fileURL)
} catch { }
URLsToDelete.append(fileURL)
if diskCacheSize < targetSize {
break
}
}
}
DispatchQueue.main.async {
if URLsToDelete.count != 0 {
let cleanedHashes = URLsToDelete.map { $0.lastPathComponent }
NotificationCenter.default.post(name: .VGPlayerCacheManagerDidCleanCache, object: self, userInfo: [VGPlayerCacheManager.VGPlayerCleanCacheKey: cleanedHashes])
}
handler?()
}
}
}
fileprivate func cachedFiles(atPath path: String, onlyForCacheSize: Bool) -> (urlsToDelete: [URL], diskCacheSize: UInt, cachedFiles: [URL: URLResourceValues]) {
let expiredDate: Date? = (cacheConfig.maxCacheAge < 0) ? nil : Date(timeIntervalSinceNow: -cacheConfig.maxCacheAge)
var cachedFiles = [URL: URLResourceValues]()
var urlsToDelete = [URL]()
var diskCacheSize: UInt = 0
let resourceKeys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey]
let fullPath = (path as NSString).expandingTildeInPath
do {
let url = URL(fileURLWithPath: fullPath)
if let directoryEnumerator = fileManager.enumerator(at:url, includingPropertiesForKeys: Array(resourceKeys), options: [.skipsHiddenFiles], errorHandler: nil) {
for (_ , value) in directoryEnumerator.enumerated() {
do {
if let fileURL = value as? URL{
let resourceValues = try fileURL.resourceValues(forKeys: resourceKeys)
if !onlyForCacheSize,
let expiredDate = expiredDate,
let lastAccessData = resourceValues.contentAccessDate,
(lastAccessData as NSDate).laterDate(expiredDate) == expiredDate
{
urlsToDelete.append(fileURL)
continue
}
if !onlyForCacheSize && resourceValues.isDirectory == true {
cachedFiles[fileURL] = resourceValues
}
if let size = resourceValues.totalFileAllocatedSize {
diskCacheSize += UInt(size)
}
}
} catch { }
}
}
}
return (urlsToDelete, diskCacheSize, cachedFiles)
}
}
extension Dictionary {
func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
}
}
| mit |
RLovelett/langserver-swift | Sources/LanguageServerProtocol/Types/InitializeParams.swift | 1 | 1055 | //
// InitializeParams.swift
// langserver-swift
//
// Created by Ryan Lovelett on 11/21/16.
//
//
import Argo
import Curry
import Runes
/// The initialize request is sent as the first request from the client to the server.
public struct InitializeParams {
/// The process Id of the parent process that started the server. Is null if the process has not
/// been started by another process.
/// If the parent process is not alive then the server should exit (see exit notification) its
/// process.
let processId: Int?
/// The rootPath of the workspace. Is null if no folder is open.
let rootPath: String?
/// User provided initialization options.
let initializationOptions: Any?
}
extension InitializeParams : Argo.Decodable {
public static func decode(_ json: JSON) -> Decoded<InitializeParams> {
let p: Decoded<Int?> = json[optional: "processId"]
let r: Decoded<String?> = json[optional: "rootPath"]
return curry(InitializeParams.init) <^> p <*> r <*> pure(.none)
}
}
| apache-2.0 |
wireapp/wire-ios-sync-engine | Source/Utility/DispatchQueue+SerialAsync.swift | 1 | 1281 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
public typealias AsyncAction = (_ whenDone: @escaping () -> Void) -> Void
extension DispatchQueue {
// Dispatches the @c action on the queue in the serial way, waiting for the completion call (whenDone).
public func serialAsync(do action: @escaping AsyncAction) {
self.async {
let loadingGroup = DispatchGroup()
loadingGroup.enter()
DispatchQueue.main.async {
action {
loadingGroup.leave()
}
}
loadingGroup.wait()
}
}
}
| gpl-3.0 |
thoughtbend/mobile-ps-demo-poc | AboutTownXCode8Beta/AboutTownXCode8Beta/SecondViewController.swift | 1 | 526 | //
// SecondViewController.swift
// AboutTownXCode8Beta
//
// Created by Mike Nolan on 8/6/16.
// Copyright © 2016 Thoughtbend. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
ccrama/Slide-iOS | Slide for Apple Watch Extension/SubmissionRowController.swift | 1 | 12062 | //
// SubmissionRowController.swift
// Slide for Apple Watch Extension
//
// Created by Carlos Crane on 9/23/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import CoreGraphics
import Foundation
import UIKit
import WatchKit
public class SubmissionRowController: NSObject {
var titleText: NSAttributedString?
var thumbnail: UIImage?
var largeimage: UIImage?
var id: String?
var sub: String?
var scoreText: String!
var commentText: String!
var dictionary: NSDictionary!
@IBOutlet weak var imageGroup: WKInterfaceGroup!
@IBOutlet var bannerImage: WKInterfaceImage!
@IBOutlet weak var scoreLabel: WKInterfaceLabel!
@IBOutlet weak var commentsLabel: WKInterfaceLabel!
@IBOutlet weak var infoLabel: WKInterfaceLabel!
@IBOutlet weak var titleLabel: WKInterfaceLabel!
@IBOutlet var bigImage: WKInterfaceImage!
@IBOutlet var thumbGroup: WKInterfaceGroup!
@IBOutlet var upvote: WKInterfaceButton!
@IBOutlet var downvote: WKInterfaceButton!
@IBOutlet var readlater: WKInterfaceButton!
@IBAction func didUpvote() {
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedUp = upvote
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedDown = downvote
(WKExtension.shared().visibleInterfaceController as? Votable)?.doVote(id: id!, upvote: true, downvote: false)
}
@IBAction func didDownvote() {
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedUp = upvote
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedDown = downvote
(WKExtension.shared().visibleInterfaceController as? Votable)?.doVote(id: id!, upvote: false, downvote: true)
}
@IBAction func didSaveLater() {
(WKExtension.shared().visibleInterfaceController as? Votable)?.sharedReadLater = readlater
(WKExtension.shared().visibleInterfaceController as? Votable)?.doReadLater(id: id!, sub: sub!)
}
func setData(dictionary: NSDictionary, color: UIColor) {
largeimage = nil
thumbnail = nil
self.dictionary = dictionary
let titleFont = UIFont.systemFont(ofSize: 14)
let subtitleFont = UIFont.boldSystemFont(ofSize: 10)
let attributedTitle = NSMutableAttributedString(string: dictionary["title"] as! String, attributes: [NSAttributedString.Key.font: titleFont, NSAttributedString.Key.foregroundColor: UIColor.white])
id = dictionary["id"] as? String ?? ""
sub = dictionary["subreddit"] as? String ?? ""
let nsfw = NSMutableAttributedString.init(string: "\u{00A0}NSFW\u{00A0}", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red, NSAttributedString.Key.font: subtitleFont])
let spoiler = NSMutableAttributedString.init(string: "\u{00A0}SPOILER\u{00A0}", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: subtitleFont])
let spacer = NSMutableAttributedString.init(string: " ")
if let flair = dictionary["link_flair_text"] as? String {
attributedTitle.append(spacer)
attributedTitle.append(NSMutableAttributedString.init(string: "\u{00A0}\(flair)\u{00A0}", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: subtitleFont]))
}
if let isNsfw = dictionary["nsfw"] as? Bool, isNsfw == true {
attributedTitle.append(spacer)
attributedTitle.append(nsfw)
}
if let nsfw = dictionary["spoiler"] as? Bool, nsfw == true {
attributedTitle.append(spacer)
attributedTitle.append(spoiler)
}
let attrs = [NSAttributedString.Key.font: subtitleFont, NSAttributedString.Key.foregroundColor: UIColor.white]
let endString = NSMutableAttributedString(string: " • \(dictionary["created"] as! String)", attributes: [NSAttributedString.Key.font: subtitleFont, NSAttributedString.Key.foregroundColor: UIColor.gray])
let authorString = NSMutableAttributedString(string: "\nu/\(dictionary["author"] as? String ?? "")", attributes: [NSAttributedString.Key.font: subtitleFont, NSAttributedString.Key.foregroundColor: UIColor.gray])
endString.append(authorString)
// if SettingValues.domainInInfo && !full {
// endString.append(NSAttributedString.init(string: " • \(submission.domain)", attributes: [NSFontAttributeName: FontGenerator.fontOfSize(size: 12, submission: true), NSForegroundColorAttributeName: colorF]))
// }
//
// let tag = ColorUtil.getTagForUser(name: submission.author)
// if !tag.isEmpty {
// let tagString = NSMutableAttributedString(string: "\u{00A0}\(tag)\u{00A0}", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: colorF])
// tagString.addAttributes([kTTTBackgroundFillColorAttributeName: UIColor(rgb: 0x2196f3), NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: UIColor.white, kTTTBackgroundFillPaddingAttributeName: UIEdgeInsets.init(top: 1, left: 1, bottom: 1, right: 1), kTTTBackgroundCornerRadiusAttributeName: 3], range: NSRange.init(location: 0, length: tagString.length))
// endString.append(spacer)
// endString.append(tagString)
// }
//
let boldString = NSMutableAttributedString(string: "r/\(dictionary["subreddit"] ?? "")", attributes: attrs)
boldString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange.init(location: 0, length: boldString.length))
let infoString = NSMutableAttributedString()
infoString.append(boldString)
infoString.append(endString)
infoString.append(NSAttributedString(string: "\n"))
infoString.append(attributedTitle)
titleLabel.setAttributedText(infoString)
let type = ContentType.getContentType(dict: dictionary)
var big = false
var text = ""
switch type {
case .ALBUM:
text = ("Album")
case .REDDIT_GALLERY:
text = ("Reddit Gallery")
case .EXTERNAL:
text = "External Link"
case .LINK, .EMBEDDED, .NONE:
text = "Link"
case .DEVIANTART:
text = "Deviantart"
case .TUMBLR:
text = "Tumblr"
case .XKCD:
text = ("XKCD")
case .GIF:
if (dictionary["domain"] as? String ?? "") == "v.redd.it" {
text = "Reddit Video"
} else {
text = ("GIF")
}
case .IMGUR, .IMAGE:
big = true && dictionary["bigimage"] != nil
text = ("Image")
case .YOUTUBE:
text = "YouTube"
case .STREAMABLE:
text = "Streamable"
case .VID_ME:
text = ("Vid.me")
case .REDDIT:
text = ("Reddit content")
default:
text = "Link"
}
readlater.setBackgroundColor((dictionary["readLater"] ?? false) as! Bool ? UIColor.init(hexString: "#4CAF50") : UIColor.gray)
upvote.setBackgroundColor((dictionary["upvoted"] ?? false) as! Bool ? UIColor.init(hexString: "#FF5700") : UIColor.gray)
downvote.setBackgroundColor((dictionary["downvoted"] ?? false) as! Bool ? UIColor.init(hexString: "#9494FF") : UIColor.gray)
readlater.setBackgroundColor(UIColor.gray)
if big {
bigImage.setHidden(false)
thumbGroup.setHidden(true)
} else {
bigImage.setHidden(true)
thumbGroup.setHidden(false)
}
let domain = dictionary["domain"] as? String ?? ""
let aboutString = NSMutableAttributedString(string: "\(text)", attributes: [NSAttributedString.Key.font: subtitleFont.withSize(13)])
aboutString.append(NSMutableAttributedString(string: "\n\(domain)", attributes: [NSAttributedString.Key.font: subtitleFont]))
infoLabel.setAttributedText(aboutString)
// infoString.append(NSAttributedString.init(string: "\n"))
// var sColor = UIColor.white
// switch ActionStates.getVoteDirection(s: submission) {
// case .down:
// sColor = ColorUtil.downvoteColor
// case .up:
// sColor = ColorUtil.upvoteColor
// case .none:
// break
// }
//
// let subScore = NSMutableAttributedString(string: (submission.score >= 10000 && SettingValues.abbreviateScores) ? String(format: " %0.1fk points", (Double(submission.score) / Double(1000))) : " \(submission.score) points", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: sColor])
//
// infoString.append(subScore)
//
// if SettingValues.scoreInTitle {
// infoString.append(spacer)
// }
// let scoreString = NSMutableAttributedString(string: "\(submission.commentCount) comments", attributes: [NSFontAttributeName: FontGenerator.boldFontOfSize(size: 12, submission: false), NSForegroundColorAttributeName: colorF])
// infoString.append(scoreString)
titleText = infoString
let scoreNumber = dictionary["score"] as? Int ?? 0
scoreText = scoreNumber > 1000 ?
String(format: "%0.1fk ", (Double(scoreNumber) / Double(1000))) : "\(scoreNumber) "
scoreLabel.setText(scoreText)
commentText = "\(dictionary["num_comments"] as? Int ?? 0)"
commentsLabel.setText(commentText)
if big, let imageurl = (dictionary["bigimage"] as? String), !imageurl.isEmpty(), imageurl.startsWith("http") {
DispatchQueue.global().async {
let imageUrl = URL(string: imageurl)!
URLSession.shared.dataTask(with: imageUrl, completionHandler: { (data, _, _) in
if let image = UIImage(data: data!) {
self.largeimage = image
DispatchQueue.main.async {
self.bigImage.setImage(self.largeimage!)
}
} else {
NSLog("could not load data from image URL: \(imageUrl)")
}
}).resume()
}
} else if let thumburl = (dictionary["thumbnail"] as? String), !thumburl.isEmpty(), thumburl.startsWith("http") {
DispatchQueue.global().async {
let imageUrl = URL(string: thumburl)!
URLSession.shared.dataTask(with: imageUrl, completionHandler: { (data, _, _) in
if let image = UIImage(data: data!) {
self.thumbnail = image
DispatchQueue.main.async {
self.bannerImage.setImage(self.thumbnail!)
}
} else {
NSLog("could not load data from image URL: \(imageUrl)")
}
}).resume()
}
} else if type == .SELF || type == .NONE {
thumbGroup.setHidden(true)
bigImage.setHidden(true)
} else {
if dictionary["spoiler"] as? Bool ?? false {
self.bannerImage.setImage(UIImage(named: "reports")?.getCopy(withSize: CGSize(width: 25, height: 25)))
} else if type == .REDDIT || (dictionary["is_self"] as? Bool ?? false) {
self.bannerImage.setImage(UIImage(named: "reddit")?.getCopy(withSize: CGSize(width: 25, height: 25)))
} else {
self.bannerImage.setImage(UIImage(named: "nav")?.getCopy(withSize: CGSize(width: 25, height: 25)))
}
}
self.imageGroup.setCornerRadius(10)
}
}
| apache-2.0 |
myoungsc/Example-Swift | Example-SwiftUITests/Example_SwiftUITests.swift | 1 | 1263 | //
// Example_SwiftUITests.swift
// Example-SwiftUITests
//
// Created by Myoung.SC on 2016. 4. 27..
// Copyright © 2016년 myoung. All rights reserved.
//
import XCTest
class Example_SwiftUITests: 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.
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.