repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Snowy1803/BreakBaloon-mobile
|
BreakBaloon/GameScene/AbstractGameScene.swift
|
1
|
2213
|
//
// AbstractGameScene.swift
// BreakBaloon
//
// Created by Emil on 29/07/2016.
// Copyright © 2016 Snowy_1803. All rights reserved.
//
import AVFoundation
import SpriteKit
class AbstractGameScene: SKScene {
var gametype: GameType
var points: Int = 0
var beginTime: TimeInterval?
var endTime: TimeInterval?
fileprivate var pauseTime: TimeInterval?
var theme: AbstractTheme
private var normalPumpPlayers: Set<AVAudioPlayer> = []
private var winnerPumpPlayers: Set<AVAudioPlayer> = []
init(view: SKView, gametype: GameType) {
self.gametype = gametype
self.theme = view.gvc.currentTheme
super.init(size: view.bounds.size)
construct(view.gvc)
view.gvc.currentGame = self
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func construct(_ gvc: GameViewController) {
backgroundColor = theme.background
}
func pauseGame() {
pauseTime = Date().timeIntervalSince1970
isPaused = true
}
func quitPause() {
isPaused = false
if beginTime != nil, pauseTime != nil {
let pauseLenght = Date().timeIntervalSince1970 - pauseTime!
beginTime! += pauseLenght
}
pauseTime = nil
}
func isGamePaused() -> Bool {
pauseTime != nil
}
func playPump(winner: Bool) {
let avplayer = (winner ? winnerPumpPlayers : normalPumpPlayers).first(where: { !$0.isPlaying }) ?? preparePlayer(winner: winner)
avplayer?.play()
}
private func preparePlayer(winner: Bool) -> AVAudioPlayer? {
do {
let avplayer = try AVAudioPlayer(data: theme.pumpSound(winner))
avplayer.volume = view!.gvc.audioVolume
avplayer.prepareToPlay()
if winner {
winnerPumpPlayers.insert(avplayer)
} else {
normalPumpPlayers.insert(avplayer)
}
return avplayer
} catch {
print("Error playing sound <winner \(winner)>")
}
return nil
}
}
|
mit
|
709c385e1ef45bb4c1acf9ac0051ed4f
| 25.97561 | 136 | 0.592224 | 4.617954 | false | false | false | false |
apple/swift-nio-http2
|
Sources/NIOHTTP2/ConnectionStateMachine/StateMachineResult.swift
|
1
|
3567
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// The event triggered by this state transition attempt.
///
/// All state transition attempts trigger one of three results. Firstly, they succeed, in which case
/// the frame may be passed on (either outwards, to the serializer, or inwards, to the user).
/// Alternatively, the frame itself may trigger an error.
///
/// Errors triggered by frames come in two types: connection errors, and stream errors. This refers
/// to the scope at which the error occurs. Stream errors occur at stream scope, and therefore should
/// lead to the teardown of only the affected stream (e.g. RST_STREAM frame emission). Connection errors
/// occur at connection scope: either there is no stream available to tear down, or the error is so
/// foundational that the connection can not be recovered. In either case, the mechanism for tolerating
/// that is to tear the entire connection down, via GOAWAY frame.
///
/// In both cases, there is an associated kind of error as represented by a `HTTP2ErrorCode`, that
/// should be reported to the remote peer. Additionally, there is an error fired by the internal state
/// machine that can be reported to the user. This enum ensures that both can be propagated out.
enum StateMachineResult {
/// An error that transitions the stream into a fatal error state. This should cause emission of
/// RST_STREAM frames.
case streamError(streamID: HTTP2StreamID, underlyingError: Error, type: HTTP2ErrorCode)
/// An error that transitions the entire connection into a fatal error state. This should cause
/// emission of GOAWAY frames.
case connectionError(underlyingError: Error, type: HTTP2ErrorCode)
/// The frame itself was not valid, but it is also not an error. Drop the frame.
case ignoreFrame
/// The state transition succeeded, the frame may be passed on.
case succeed
}
/// Operations that may need to be performed after receiving a frame.
enum PostFrameOperation {
/// An appropriate ACK must be sent.
case sendAck
/// No operation is needed.
case nothing
}
/// An encapsulation of a state machine result along with a possible triggered state change.
struct StateMachineResultWithEffect {
var result: StateMachineResult
var effect: NIOHTTP2ConnectionStateChange?
init(result: StateMachineResult, effect: NIOHTTP2ConnectionStateChange?) {
self.result = result
self.effect = effect
}
init(_ streamEffect: StateMachineResultWithStreamEffect,
inboundFlowControlWindow: HTTP2FlowControlWindow,
outboundFlowControlWindow: HTTP2FlowControlWindow) {
self.result = streamEffect.result
self.effect = streamEffect.effect.map {
NIOHTTP2ConnectionStateChange($0, inboundFlowControlWindow: inboundFlowControlWindow, outboundFlowControlWindow: outboundFlowControlWindow)
}
}
}
/// An encapsulation of a state machine result along with a state change on a single stream.
struct StateMachineResultWithStreamEffect {
var result: StateMachineResult
var effect: StreamStateChange?
}
|
apache-2.0
|
aca6183db7e53f21588cdc1adc498b8b
| 41.464286 | 151 | 0.711522 | 4.893004 | false | false | false | false |
KasaLabs/KasaLibs-iOS
|
Classes/Entities/User.swift
|
1
|
2727
|
//
// User.swift
// MobilKasa
//
// Created by Suleyman Calik on 15/05/15.
// Copyright (c) 2015 Kasa. All rights reserved.
//
import ObjectMapper
class User: MKEntity {
/*
email = "[email protected]";
expirationDate = "2015-07-14 07:12:24 +0000";
"first_name" = "S\U00fcleyman";
gender = male;
id = 10152979121993883;
"last_name" = "\U00c7al\U0131k";
link = "https://www.facebook.com/app_scoped_user_id/10152979121993883/";
locale = "tr_TR";
name = "S\U00fcleyman \U00c7al\U0131k";
refreshDate = "2015-05-15 12:26:13 +0000";
timezone = 3;
token = CAAFVJaJafcYBAAiR9yLr7jmZC92Y3ZBYs7ZC0G1GcC4F78J3rKF0yBJGBlq2aHaCgqZCrftlhKrYZCicugJlH0sNira9aLN0tOnsBd3xiiF9VeRiZBTZCs0B0wQqZCwNTmPP9Aql9C1bQnCP5KrGn2hDVZCatzeustswozfDxoi75bZB8VyZBO3KK7qRCTlfi2h1EuueceWZBV9s9jtBdtig003FfXGqXYPxxOU1r5cT6AXeL0mQMllwj0z18Mzh0sTNVJcZAmN8OBvKJ3efz2G4bvxcH;
"updated_time" = "2015-03-01T01:32:27+0000";
permissions = "{(\n email,\n \"contact_email\",\n \"public_profile\"\n)}";
verified = 1;
*/
dynamic var email:String = ""
dynamic var username:String = ""
dynamic var firstName:String = ""
dynamic var lastName:String = ""
dynamic var fullName:String = ""
dynamic var gender:String = ""
dynamic var fbId:String = ""
dynamic var link:String = ""
dynamic var locale:String = ""
dynamic var timezone:Int = 0
dynamic var verified:Bool = false
dynamic var balance:Double = 0
// dynamic var permissions:String = ""
dynamic var updated_time:String = ""
dynamic var fbToken:String = ""
dynamic var tokenRefreshDate:String = ""
dynamic var tokenExpirationDate:String = ""
override class func newInstance() -> Mappable {
return User()
}
override func mapping(map: Map) {
super.mapping(map)
email <- map["email"]
username <- map["username"]
firstName <- map["firstName"]
lastName <- map["lastName"]
fullName <- map["fullName"]
gender <- map["gender"]
fbId <- map["fbId"]
link <- map["link"]
locale <- map["locale"]
timezone <- map["timezone"]
verified <- map["verified"]
balance <- map["balance"]
// permissions <- map["permissions"]
updated_time <- map["updated_time"]
fbToken <- map["fbToken"]
tokenRefreshDate <- map["tokenRefreshDate"]
tokenExpirationDate <- map["tokenExpirationDate"]
}
class func currentUser() -> User! {
return Realm.objects(User).first
}
}
|
mit
|
45820a2786d855f607807374eeb6167f
| 28.641304 | 299 | 0.605427 | 3.178322 | false | false | false | false |
Pluto-Y/SwiftyEcharts
|
SwiftyEcharts/Models/Axis/AxisLine.swift
|
1
|
1226
|
//
// AxisLine.swift
// SwiftyEcharts
//
// Created by Pluto Y on 06/02/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
/// 坐标轴轴线相关设置。
public final class AxisLine: Displayable, Line {
public var show: Bool?
/// X 轴或者 Y 轴的轴线是否在另一个轴的 0 刻度上,只有在另一个轴为数值轴且包含 0 刻度时有效。
public var onZero: Bool?
public var lineStyle: LineStyle?
public init() { }
}
extension AxisLine: Enumable {
public enum Enums {
case show(Bool), onZero(Bool), lineStyle(LineStyle)
}
public typealias ContentEnum = Enums
public convenience init(_ elements: Enums...) {
self.init()
for ele in elements {
switch ele {
case let .show(show):
self.show = show
case let .onZero(onZero):
self.onZero = onZero
case let .lineStyle(lineStyle):
self.lineStyle = lineStyle
}
}
}
}
extension AxisLine: Mappable {
public func mapping(_ map: Mapper) {
map["show"] = show
map["onZero"] = onZero
map["lineStyle"] = lineStyle
}
}
|
mit
|
10c78943fd60aac436f8f19714cbb4b1
| 22.479167 | 59 | 0.565217 | 3.807432 | false | false | false | false |
austinzheng/swift
|
benchmark/single-source/SortStrings.swift
|
3
|
39393
|
//===--- SortStrings.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
// Sort an array of strings using an explicit sort predicate.
public let SortStrings = [
BenchmarkInfo(name: "SortSortedStrings", runFunction: run_SortSortedStrings, tags: [.validation, .api, .algorithm, .String],
setUpFunction: { blackHole(sortedWords) }),
BenchmarkInfo(name: "SortStrings", runFunction: run_SortStrings, tags: [.validation, .api, .algorithm, .String],
setUpFunction: { blackHole(words) }),
BenchmarkInfo(name: "SortStringsUnicode", runFunction: run_SortStringsUnicode, tags: [.validation, .api, .algorithm, .String],
setUpFunction: { blackHole(unicodeWords) }),
]
let sortedWords = words.sorted()
let words: [String] = [
"woodshed",
"lakism",
"gastroperiodynia",
"afetal",
"ramsch",
"Nickieben",
"undutifulness",
"birdglue",
"ungentlemanize",
"menacingly",
"heterophile",
"leoparde",
"Casearia",
"decorticate",
"neognathic",
"mentionable",
"tetraphenol",
"pseudonymal",
"dislegitimate",
"Discoidea",
"intitule",
"ionium",
"Lotuko",
"timbering",
"nonliquidating",
"oarialgia",
"Saccobranchus",
"reconnoiter",
"criminative",
"disintegratory",
"executer",
"Cylindrosporium",
"complimentation",
"Ixiama",
"Araceae",
"silaginoid",
"derencephalus",
"Lamiidae",
"marrowlike",
"ninepin",
"dynastid",
"lampfly",
"feint",
"trihemimer",
"semibarbarous",
"heresy",
"tritanope",
"indifferentist",
"confound",
"hyperbolaeon",
"planirostral",
"philosophunculist",
"existence",
"fretless",
"Leptandra",
"Amiranha",
"handgravure",
"gnash",
"unbelievability",
"orthotropic",
"Susumu",
"teleutospore",
"sleazy",
"shapeliness",
"hepatotomy",
"exclusivism",
"stifler",
"cunning",
"isocyanuric",
"pseudepigraphy",
"carpetbagger",
"respectiveness",
"Jussi",
"vasotomy",
"proctotomy",
"ovatotriangular",
"aesthetic",
"schizogamy",
"disengagement",
"foray",
"haplocaulescent",
"noncoherent",
"astrocyte",
"unreverberated",
"presenile",
"lanson",
"enkraal",
"contemplative",
"Syun",
"sartage",
"unforgot",
"wyde",
"homeotransplant",
"implicational",
"forerunnership",
"calcaneum",
"stomatodeum",
"pharmacopedia",
"preconcessive",
"trypanosomatic",
"intracollegiate",
"rampacious",
"secundipara",
"isomeric",
"treehair",
"pulmonal",
"uvate",
"dugway",
"glucofrangulin",
"unglory",
"Amandus",
"icterogenetic",
"quadrireme",
"Lagostomus",
"brakeroot",
"anthracemia",
"fluted",
"protoelastose",
"thro",
"pined",
"Saxicolinae",
"holidaymaking",
"strigil",
"uncurbed",
"starling",
"redeemeress",
"Liliaceae",
"imparsonee",
"obtusish",
"brushed",
"mesally",
"probosciformed",
"Bourbonesque",
"histological",
"caroba",
"digestion",
"Vindemiatrix",
"triactinal",
"tattling",
"arthrobacterium",
"unended",
"suspectfulness",
"movelessness",
"chartist",
"Corynebacterium",
"tercer",
"oversaturation",
"Congoleum",
"antiskeptical",
"sacral",
"equiradiate",
"whiskerage",
"panidiomorphic",
"unplanned",
"anilopyrine",
"Queres",
"tartronyl",
"Ing",
"notehead",
"finestiller",
"weekender",
"kittenhood",
"competitrix",
"premillenarian",
"convergescence",
"microcoleoptera",
"slirt",
"asteatosis",
"Gruidae",
"metastome",
"ambuscader",
"untugged",
"uneducated",
"redistill",
"rushlight",
"freakish",
"dosology",
"papyrine",
"iconologist",
"Bidpai",
"prophethood",
"pneumotropic",
"chloroformize",
"intemperance",
"spongiform",
"superindignant",
"divider",
"starlit",
"merchantish",
"indexless",
"unidentifiably",
"coumarone",
"nomism",
"diaphanous",
"salve",
"option",
"anallantoic",
"paint",
"thiofurfuran",
"baddeleyite",
"Donne",
"heterogenicity",
"decess",
"eschynite",
"mamma",
"unmonarchical",
"Archiplata",
"widdifow",
"apathic",
"overline",
"chaetophoraceous",
"creaky",
"trichosporange",
"uninterlined",
"cometwise",
"hermeneut",
"unbedraggled",
"tagged",
"Sminthurus",
"somniloquacious",
"aphasiac",
"Inoperculata",
"photoactivity",
"mobship",
"unblightedly",
"lievrite",
"Khoja",
"Falerian",
"milfoil",
"protectingly",
"householder",
"cathedra",
"calmingly",
"tordrillite",
"rearhorse",
"Leonard",
"maracock",
"youngish",
"kammererite",
"metanephric",
"Sageretia",
"diplococcoid",
"accelerative",
"choreal",
"metalogical",
"recombination",
"unimprison",
"invocation",
"syndetic",
"toadback",
"vaned",
"cupholder",
"metropolitanship",
"paramandelic",
"dermolysis",
"Sheriyat",
"rhabdus",
"seducee",
"encrinoid",
"unsuppliable",
"cololite",
"timesaver",
"preambulate",
"sampling",
"roaster",
"springald",
"densher",
"protraditional",
"naturalesque",
"Hydrodamalis",
"cytogenic",
"shortly",
"cryptogrammatical",
"squat",
"genual",
"backspier",
"solubleness",
"macroanalytical",
"overcovetousness",
"Natalie",
"cuprobismutite",
"phratriac",
"Montanize",
"hymnologist",
"karyomiton",
"podger",
"unofficiousness",
"antisplasher",
"supraclavicular",
"calidity",
"disembellish",
"antepredicament",
"recurvirostral",
"pulmonifer",
"coccidial",
"botonee",
"protoglobulose",
"isonym",
"myeloid",
"premiership",
"unmonopolize",
"unsesquipedalian",
"unfelicitously",
"theftbote",
"undauntable",
"lob",
"praenomen",
"underriver",
"gorfly",
"pluckage",
"radiovision",
"tyrantship",
"fraught",
"doppelkummel",
"rowan",
"allosyndetic",
"kinesiology",
"psychopath",
"arrent",
"amusively",
"preincorporation",
"Montargis",
"pentacron",
"neomedievalism",
"sima",
"lichenicolous",
"Ecclesiastes",
"woofed",
"cardinalist",
"sandaracin",
"gymnasial",
"lithoglyptics",
"centimeter",
"quadrupedous",
"phraseology",
"tumuli",
"ankylotomy",
"myrtol",
"cohibitive",
"lepospondylous",
"silvendy",
"inequipotential",
"entangle",
"raveling",
"Zeugobranchiata",
"devastating",
"grainage",
"amphisbaenian",
"blady",
"cirrose",
"proclericalism",
"governmentalist",
"carcinomorphic",
"nurtureship",
"clancular",
"unsteamed",
"discernibly",
"pleurogenic",
"impalpability",
"Azotobacterieae",
"sarcoplasmic",
"alternant",
"fitly",
"acrorrheuma",
"shrapnel",
"pastorize",
"gulflike",
"foreglow",
"unrelated",
"cirriped",
"cerviconasal",
"sexuale",
"pussyfooter",
"gadolinic",
"duplicature",
"codelinquency",
"trypanolysis",
"pathophobia",
"incapsulation",
"nonaerating",
"feldspar",
"diaphonic",
"epiglottic",
"depopulator",
"wisecracker",
"gravitational",
"kuba",
"lactesce",
"Toxotes",
"periomphalic",
"singstress",
"fannier",
"counterformula",
"Acemetae",
"repugnatorial",
"collimator",
"Acinetina",
"unpeace",
"drum",
"tetramorphic",
"descendentalism",
"cementer",
"supraloral",
"intercostal",
"Nipponize",
"negotiator",
"vacationless",
"synthol",
"fissureless",
"resoap",
"pachycarpous",
"reinspiration",
"misappropriation",
"disdiazo",
"unheatable",
"streng",
"Detroiter",
"infandous",
"loganiaceous",
"desugar",
"Matronalia",
"myxocystoma",
"Gandhiism",
"kiddier",
"relodge",
"counterreprisal",
"recentralize",
"foliously",
"reprinter",
"gender",
"edaciousness",
"chondriomite",
"concordant",
"stockrider",
"pedary",
"shikra",
"blameworthiness",
"vaccina",
"Thamnophilinae",
"wrongwise",
"unsuperannuated",
"convalescency",
"intransmutable",
"dropcloth",
"Ceriomyces",
"ponderal",
"unstentorian",
"mem",
"deceleration",
"ethionic",
"untopped",
"wetback",
"bebar",
"undecaying",
"shoreside",
"energize",
"presacral",
"undismay",
"agricolite",
"cowheart",
"hemibathybian",
"postexilian",
"Phacidiaceae",
"offing",
"redesignation",
"skeptically",
"physicianless",
"bronchopathy",
"marabuto",
"proprietory",
"unobtruded",
"funmaker",
"plateresque",
"preadventure",
"beseeching",
"cowpath",
"pachycephalia",
"arthresthesia",
"supari",
"lengthily",
"Nepa",
"liberation",
"nigrify",
"belfry",
"entoolitic",
"bazoo",
"pentachromic",
"distinguishable",
"slideable",
"galvanoscope",
"remanage",
"cetene",
"bocardo",
"consummation",
"boycottism",
"perplexity",
"astay",
"Gaetuli",
"periplastic",
"consolidator",
"sluggarding",
"coracoscapular",
"anangioid",
"oxygenizer",
"Hunanese",
"seminary",
"periplast",
"Corylus",
"unoriginativeness",
"persecutee",
"tweaker",
"silliness",
"Dabitis",
"facetiousness",
"thymy",
"nonimperial",
"mesoblastema",
"turbiniform",
"churchway",
"cooing",
"frithbot",
"concomitantly",
"stalwartize",
"clingfish",
"hardmouthed",
"parallelepipedonal",
"coracoacromial",
"factuality",
"curtilage",
"arachnoidean",
"semiaridity",
"phytobacteriology",
"premastery",
"hyperpurist",
"mobed",
"opportunistic",
"acclimature",
"outdistance",
"sophister",
"condonement",
"oxygenerator",
"acetonic",
"emanatory",
"periphlebitis",
"nonsociety",
"spectroradiometric",
"superaverage",
"cleanness",
"posteroventral",
"unadvised",
"unmistakedly",
"pimgenet",
"auresca",
"overimitate",
"dipnoan",
"chromoxylograph",
"triakistetrahedron",
"Suessiones",
"uncopiable",
"oligomenorrhea",
"fribbling",
"worriable",
"flot",
"ornithotrophy",
"phytoteratology",
"setup",
"lanneret",
"unbraceleted",
"gudemother",
"Spica",
"unconsolatory",
"recorruption",
"premenstrual",
"subretinal",
"millennialist",
"subjectibility",
"rewardproof",
"counterflight",
"pilomotor",
"carpetbaggery",
"macrodiagonal",
"slim",
"indiscernible",
"cuckoo",
"moted",
"controllingly",
"gynecopathy",
"porrectus",
"wanworth",
"lutfisk",
"semiprivate",
"philadelphy",
"abdominothoracic",
"coxcomb",
"dambrod",
"Metanemertini",
"balminess",
"homotypy",
"waremaker",
"absurdity",
"gimcrack",
"asquat",
"suitable",
"perimorphous",
"kitchenwards",
"pielum",
"salloo",
"paleontologic",
"Olson",
"Tellinidae",
"ferryman",
"peptonoid",
"Bopyridae",
"fallacy",
"ictuate",
"aguinaldo",
"rhyodacite",
"Ligydidae",
"galvanometric",
"acquisitor",
"muscology",
"hemikaryon",
"ethnobotanic",
"postganglionic",
"rudimentarily",
"replenish",
"phyllorhine",
"popgunnery",
"summar",
"quodlibetary",
"xanthochromia",
"autosymbolically",
"preloreal",
"extent",
"strawberry",
"immortalness",
"colicwort",
"frisca",
"electiveness",
"heartbroken",
"affrightingly",
"reconfiscation",
"jacchus",
"imponderably",
"semantics",
"beennut",
"paleometeorological",
"becost",
"timberwright",
"resuppose",
"syncategorematical",
"cytolymph",
"steinbok",
"explantation",
"hyperelliptic",
"antescript",
"blowdown",
"antinomical",
"caravanserai",
"unweariedly",
"isonymic",
"keratoplasty",
"vipery",
"parepigastric",
"endolymphatic",
"Londonese",
"necrotomy",
"angelship",
"Schizogregarinida",
"steeplebush",
"sparaxis",
"connectedness",
"tolerance",
"impingent",
"agglutinin",
"reviver",
"hieroglyphical",
"dialogize",
"coestate",
"declamatory",
"ventilation",
"tauromachy",
"cotransubstantiate",
"pome",
"underseas",
"triquadrantal",
"preconfinemnt",
"electroindustrial",
"selachostomous",
"nongolfer",
"mesalike",
"hamartiology",
"ganglioblast",
"unsuccessive",
"yallow",
"bacchanalianly",
"platydactyl",
"Bucephala",
"ultraurgent",
"penalist",
"catamenial",
"lynnhaven",
"unrelevant",
"lunkhead",
"metropolitan",
"hydro",
"outsoar",
"vernant",
"interlanguage",
"catarrhal",
"Ionicize",
"keelless",
"myomantic",
"booker",
"Xanthomonas",
"unimpeded",
"overfeminize",
"speronaro",
"diaconia",
"overholiness",
"liquefacient",
"Spartium",
"haggly",
"albumose",
"nonnecessary",
"sulcalization",
"decapitate",
"cellated",
"unguirostral",
"trichiurid",
"loveproof",
"amakebe",
"screet",
"arsenoferratin",
"unfrizz",
"undiscoverable",
"procollectivistic",
"tractile",
"Winona",
"dermostosis",
"eliminant",
"scomberoid",
"tensile",
"typesetting",
"xylic",
"dermatopathology",
"cycloplegic",
"revocable",
"fissate",
"afterplay",
"screwship",
"microerg",
"bentonite",
"stagecoaching",
"beglerbeglic",
"overcharitably",
"Plotinism",
"Veddoid",
"disequalize",
"cytoproct",
"trophophore",
"antidote",
"allerion",
"famous",
"convey",
"postotic",
"rapillo",
"cilectomy",
"penkeeper",
"patronym",
"bravely",
"ureteropyelitis",
"Hildebrandine",
"missileproof",
"Conularia",
"deadening",
"Conrad",
"pseudochylous",
"typologically",
"strummer",
"luxuriousness",
"resublimation",
"glossiness",
"hydrocauline",
"anaglyph",
"personifiable",
"seniority",
"formulator",
"datiscaceous",
"hydracrylate",
"Tyranni",
"Crawthumper",
"overprove",
"masher",
"dissonance",
"Serpentinian",
"malachite",
"interestless",
"stchi",
"ogum",
"polyspermic",
"archegoniate",
"precogitation",
"Alkaphrah",
"craggily",
"delightfulness",
"bioplast",
"diplocaulescent",
"neverland",
"interspheral",
"chlorhydric",
"forsakenly",
"scandium",
"detubation",
"telega",
"Valeriana",
"centraxonial",
"anabolite",
"neger",
"miscellanea",
"whalebacker",
"stylidiaceous",
"unpropelled",
"Kennedya",
"Jacksonite",
"ghoulish",
"Dendrocalamus",
"paynimhood",
"rappist",
"unluffed",
"falling",
"Lyctus",
"uncrown",
"warmly",
"pneumatism",
"Morisonian",
"notate",
"isoagglutinin",
"Pelidnota",
"previsit",
"contradistinctly",
"utter",
"porometer",
"gie",
"germanization",
"betwixt",
"prenephritic",
"underpier",
"Eleutheria",
"ruthenious",
"convertor",
"antisepsin",
"winterage",
"tetramethylammonium",
"Rockaway",
"Penaea",
"prelatehood",
"brisket",
"unwishful",
"Minahassa",
"Briareus",
"semiaxis",
"disintegrant",
"peastick",
"iatromechanical",
"fastus",
"thymectomy",
"ladyless",
"unpreened",
"overflutter",
"sicker",
"apsidally",
"thiazine",
"guideway",
"pausation",
"tellinoid",
"abrogative",
"foraminulate",
"omphalos",
"Monorhina",
"polymyarian",
"unhelpful",
"newslessness",
"oryctognosy",
"octoradial",
"doxology",
"arrhythmy",
"gugal",
"mesityl",
"hexaplaric",
"Cabirian",
"hordeiform",
"eddyroot",
"internarial",
"deservingness",
"jawbation",
"orographically",
"semiprecious",
"seasick",
"thermically",
"grew",
"tamability",
"egotistically",
"fip",
"preabsorbent",
"leptochroa",
"ethnobotany",
"podolite",
"egoistic",
"semitropical",
"cero",
"spinelessness",
"onshore",
"omlah",
"tintinnabulist",
"machila",
"entomotomy",
"nubile",
"nonscholastic",
"burnt",
"Alea",
"befume",
"doctorless",
"Napoleonic",
"scenting",
"apokreos",
"cresylene",
"paramide",
"rattery",
"disinterested",
"idiopathetic",
"negatory",
"fervid",
"quintato",
"untricked",
"Metrosideros",
"mescaline",
"midverse",
"Musophagidae",
"fictionary",
"branchiostegous",
"yoker",
"residuum",
"culmigenous",
"fleam",
"suffragism",
"Anacreon",
"sarcodous",
"parodistic",
"writmaking",
"conversationism",
"retroposed",
"tornillo",
"presuspect",
"didymous",
"Saumur",
"spicing",
"drawbridge",
"cantor",
"incumbrancer",
"heterospory",
"Turkeydom",
"anteprandial",
"neighborship",
"thatchless",
"drepanoid",
"lusher",
"paling",
"ecthlipsis",
"heredosyphilitic",
"although",
"garetta",
"temporarily",
"Monotropa",
"proglottic",
"calyptro",
"persiflage",
"degradable",
"paraspecific",
"undecorative",
"Pholas",
"myelon",
"resteal",
"quadrantly",
"scrimped",
"airer",
"deviless",
"caliciform",
"Sefekhet",
"shastaite",
"togate",
"macrostructure",
"bipyramid",
"wey",
"didynamy",
"knacker",
"swage",
"supermanism",
"epitheton",
"overpresumptuous"
]
@inline(never)
func benchSortStrings(_ words: [String]) {
// Notice that we _copy_ the array of words before we sort it.
// Pass an explicit '<' predicate to benchmark reabstraction thunks.
var tempwords = words
tempwords.sort(by: <)
}
public func run_SortStrings(_ N: Int) {
for _ in 1...5*N {
benchSortStrings(words)
}
}
public func run_SortSortedStrings(_ N: Int) {
for _ in 1...5*N {
benchSortStrings(sortedWords)
}
}
var unicodeWords: [String] = [
"❄️woodshed",
"❄️lakism",
"❄️gastroperiodynia",
"❄️afetal",
"❄️ramsch",
"❄️Nickieben",
"❄️undutifulness",
"❄️birdglue",
"❄️ungentlemanize",
"❄️menacingly",
"❄️heterophile",
"❄️leoparde",
"❄️Casearia",
"❄️decorticate",
"❄️neognathic",
"❄️mentionable",
"❄️tetraphenol",
"❄️pseudonymal",
"❄️dislegitimate",
"❄️Discoidea",
"❄️intitule",
"❄️ionium",
"❄️Lotuko",
"❄️timbering",
"❄️nonliquidating",
"❄️oarialgia",
"❄️Saccobranchus",
"❄️reconnoiter",
"❄️criminative",
"❄️disintegratory",
"❄️executer",
"❄️Cylindrosporium",
"❄️complimentation",
"❄️Ixiama",
"❄️Araceae",
"❄️silaginoid",
"❄️derencephalus",
"❄️Lamiidae",
"❄️marrowlike",
"❄️ninepin",
"❄️dynastid",
"❄️lampfly",
"❄️feint",
"❄️trihemimer",
"❄️semibarbarous",
"❄️heresy",
"❄️tritanope",
"❄️indifferentist",
"❄️confound",
"❄️hyperbolaeon",
"❄️planirostral",
"❄️philosophunculist",
"❄️existence",
"❄️fretless",
"❄️Leptandra",
"❄️Amiranha",
"❄️handgravure",
"❄️gnash",
"❄️unbelievability",
"❄️orthotropic",
"❄️Susumu",
"❄️teleutospore",
"❄️sleazy",
"❄️shapeliness",
"❄️hepatotomy",
"❄️exclusivism",
"❄️stifler",
"❄️cunning",
"❄️isocyanuric",
"❄️pseudepigraphy",
"❄️carpetbagger",
"❄️respectiveness",
"❄️Jussi",
"❄️vasotomy",
"❄️proctotomy",
"❄️ovatotriangular",
"❄️aesthetic",
"❄️schizogamy",
"❄️disengagement",
"❄️foray",
"❄️haplocaulescent",
"❄️noncoherent",
"❄️astrocyte",
"❄️unreverberated",
"❄️presenile",
"❄️lanson",
"❄️enkraal",
"❄️contemplative",
"❄️Syun",
"❄️sartage",
"❄️unforgot",
"❄️wyde",
"❄️homeotransplant",
"❄️implicational",
"❄️forerunnership",
"❄️calcaneum",
"❄️stomatodeum",
"❄️pharmacopedia",
"❄️preconcessive",
"❄️trypanosomatic",
"❄️intracollegiate",
"❄️rampacious",
"❄️secundipara",
"❄️isomeric",
"❄️treehair",
"❄️pulmonal",
"❄️uvate",
"❄️dugway",
"❄️glucofrangulin",
"❄️unglory",
"❄️Amandus",
"❄️icterogenetic",
"❄️quadrireme",
"❄️Lagostomus",
"❄️brakeroot",
"❄️anthracemia",
"❄️fluted",
"❄️protoelastose",
"❄️thro",
"❄️pined",
"❄️Saxicolinae",
"❄️holidaymaking",
"❄️strigil",
"❄️uncurbed",
"❄️starling",
"❄️redeemeress",
"❄️Liliaceae",
"❄️imparsonee",
"❄️obtusish",
"❄️brushed",
"❄️mesally",
"❄️probosciformed",
"❄️Bourbonesque",
"❄️histological",
"❄️caroba",
"❄️digestion",
"❄️Vindemiatrix",
"❄️triactinal",
"❄️tattling",
"❄️arthrobacterium",
"❄️unended",
"❄️suspectfulness",
"❄️movelessness",
"❄️chartist",
"❄️Corynebacterium",
"❄️tercer",
"❄️oversaturation",
"❄️Congoleum",
"❄️antiskeptical",
"❄️sacral",
"❄️equiradiate",
"❄️whiskerage",
"❄️panidiomorphic",
"❄️unplanned",
"❄️anilopyrine",
"❄️Queres",
"❄️tartronyl",
"❄️Ing",
"❄️notehead",
"❄️finestiller",
"❄️weekender",
"❄️kittenhood",
"❄️competitrix",
"❄️premillenarian",
"❄️convergescence",
"❄️microcoleoptera",
"❄️slirt",
"❄️asteatosis",
"❄️Gruidae",
"❄️metastome",
"❄️ambuscader",
"❄️untugged",
"❄️uneducated",
"❄️redistill",
"❄️rushlight",
"❄️freakish",
"❄️dosology",
"❄️papyrine",
"❄️iconologist",
"❄️Bidpai",
"❄️prophethood",
"❄️pneumotropic",
"❄️chloroformize",
"❄️intemperance",
"❄️spongiform",
"❄️superindignant",
"❄️divider",
"❄️starlit",
"❄️merchantish",
"❄️indexless",
"❄️unidentifiably",
"❄️coumarone",
"❄️nomism",
"❄️diaphanous",
"❄️salve",
"❄️option",
"❄️anallantoic",
"❄️paint",
"❄️thiofurfuran",
"❄️baddeleyite",
"❄️Donne",
"❄️heterogenicity",
"❄️decess",
"❄️eschynite",
"❄️mamma",
"❄️unmonarchical",
"❄️Archiplata",
"❄️widdifow",
"❄️apathic",
"❄️overline",
"❄️chaetophoraceous",
"❄️creaky",
"❄️trichosporange",
"❄️uninterlined",
"❄️cometwise",
"❄️hermeneut",
"❄️unbedraggled",
"❄️tagged",
"❄️Sminthurus",
"❄️somniloquacious",
"❄️aphasiac",
"❄️Inoperculata",
"❄️photoactivity",
"❄️mobship",
"❄️unblightedly",
"❄️lievrite",
"❄️Khoja",
"❄️Falerian",
"❄️milfoil",
"❄️protectingly",
"❄️householder",
"❄️cathedra",
"❄️calmingly",
"❄️tordrillite",
"❄️rearhorse",
"❄️Leonard",
"❄️maracock",
"❄️youngish",
"❄️kammererite",
"❄️metanephric",
"❄️Sageretia",
"❄️diplococcoid",
"❄️accelerative",
"❄️choreal",
"❄️metalogical",
"❄️recombination",
"❄️unimprison",
"❄️invocation",
"❄️syndetic",
"❄️toadback",
"❄️vaned",
"❄️cupholder",
"❄️metropolitanship",
"❄️paramandelic",
"❄️dermolysis",
"❄️Sheriyat",
"❄️rhabdus",
"❄️seducee",
"❄️encrinoid",
"❄️unsuppliable",
"❄️cololite",
"❄️timesaver",
"❄️preambulate",
"❄️sampling",
"❄️roaster",
"❄️springald",
"❄️densher",
"❄️protraditional",
"❄️naturalesque",
"❄️Hydrodamalis",
"❄️cytogenic",
"❄️shortly",
"❄️cryptogrammatical",
"❄️squat",
"❄️genual",
"❄️backspier",
"❄️solubleness",
"❄️macroanalytical",
"❄️overcovetousness",
"❄️Natalie",
"❄️cuprobismutite",
"❄️phratriac",
"❄️Montanize",
"❄️hymnologist",
"❄️karyomiton",
"❄️podger",
"❄️unofficiousness",
"❄️antisplasher",
"❄️supraclavicular",
"❄️calidity",
"❄️disembellish",
"❄️antepredicament",
"❄️recurvirostral",
"❄️pulmonifer",
"❄️coccidial",
"❄️botonee",
"❄️protoglobulose",
"❄️isonym",
"❄️myeloid",
"❄️premiership",
"❄️unmonopolize",
"❄️unsesquipedalian",
"❄️unfelicitously",
"❄️theftbote",
"❄️undauntable",
"❄️lob",
"❄️praenomen",
"❄️underriver",
"❄️gorfly",
"❄️pluckage",
"❄️radiovision",
"❄️tyrantship",
"❄️fraught",
"❄️doppelkummel",
"❄️rowan",
"❄️allosyndetic",
"❄️kinesiology",
"❄️psychopath",
"❄️arrent",
"❄️amusively",
"❄️preincorporation",
"❄️Montargis",
"❄️pentacron",
"❄️neomedievalism",
"❄️sima",
"❄️lichenicolous",
"❄️Ecclesiastes",
"❄️woofed",
"❄️cardinalist",
"❄️sandaracin",
"❄️gymnasial",
"❄️lithoglyptics",
"❄️centimeter",
"❄️quadrupedous",
"❄️phraseology",
"❄️tumuli",
"❄️ankylotomy",
"❄️myrtol",
"❄️cohibitive",
"❄️lepospondylous",
"❄️silvendy",
"❄️inequipotential",
"❄️entangle",
"❄️raveling",
"❄️Zeugobranchiata",
"❄️devastating",
"❄️grainage",
"❄️amphisbaenian",
"❄️blady",
"❄️cirrose",
"❄️proclericalism",
"❄️governmentalist",
"❄️carcinomorphic",
"❄️nurtureship",
"❄️clancular",
"❄️unsteamed",
"❄️discernibly",
"❄️pleurogenic",
"❄️impalpability",
"❄️Azotobacterieae",
"❄️sarcoplasmic",
"❄️alternant",
"❄️fitly",
"❄️acrorrheuma",
"❄️shrapnel",
"❄️pastorize",
"❄️gulflike",
"❄️foreglow",
"❄️unrelated",
"❄️cirriped",
"❄️cerviconasal",
"❄️sexuale",
"❄️pussyfooter",
"❄️gadolinic",
"❄️duplicature",
"❄️codelinquency",
"❄️trypanolysis",
"❄️pathophobia",
"❄️incapsulation",
"❄️nonaerating",
"❄️feldspar",
"❄️diaphonic",
"❄️epiglottic",
"❄️depopulator",
"❄️wisecracker",
"❄️gravitational",
"❄️kuba",
"❄️lactesce",
"❄️Toxotes",
"❄️periomphalic",
"❄️singstress",
"❄️fannier",
"❄️counterformula",
"❄️Acemetae",
"❄️repugnatorial",
"❄️collimator",
"❄️Acinetina",
"❄️unpeace",
"❄️drum",
"❄️tetramorphic",
"❄️descendentalism",
"❄️cementer",
"❄️supraloral",
"❄️intercostal",
"❄️Nipponize",
"❄️negotiator",
"❄️vacationless",
"❄️synthol",
"❄️fissureless",
"❄️resoap",
"❄️pachycarpous",
"❄️reinspiration",
"❄️misappropriation",
"❄️disdiazo",
"❄️unheatable",
"❄️streng",
"❄️Detroiter",
"❄️infandous",
"❄️loganiaceous",
"❄️desugar",
"❄️Matronalia",
"❄️myxocystoma",
"❄️Gandhiism",
"❄️kiddier",
"❄️relodge",
"❄️counterreprisal",
"❄️recentralize",
"❄️foliously",
"❄️reprinter",
"❄️gender",
"❄️edaciousness",
"❄️chondriomite",
"❄️concordant",
"❄️stockrider",
"❄️pedary",
"❄️shikra",
"❄️blameworthiness",
"❄️vaccina",
"❄️Thamnophilinae",
"❄️wrongwise",
"❄️unsuperannuated",
"❄️convalescency",
"❄️intransmutable",
"❄️dropcloth",
"❄️Ceriomyces",
"❄️ponderal",
"❄️unstentorian",
"❄️mem",
"❄️deceleration",
"❄️ethionic",
"❄️untopped",
"❄️wetback",
"❄️bebar",
"❄️undecaying",
"❄️shoreside",
"❄️energize",
"❄️presacral",
"❄️undismay",
"❄️agricolite",
"❄️cowheart",
"❄️hemibathybian",
"❄️postexilian",
"❄️Phacidiaceae",
"❄️offing",
"❄️redesignation",
"❄️skeptically",
"❄️physicianless",
"❄️bronchopathy",
"❄️marabuto",
"❄️proprietory",
"❄️unobtruded",
"❄️funmaker",
"❄️plateresque",
"❄️preadventure",
"❄️beseeching",
"❄️cowpath",
"❄️pachycephalia",
"❄️arthresthesia",
"❄️supari",
"❄️lengthily",
"❄️Nepa",
"❄️liberation",
"❄️nigrify",
"❄️belfry",
"❄️entoolitic",
"❄️bazoo",
"❄️pentachromic",
"❄️distinguishable",
"❄️slideable",
"❄️galvanoscope",
"❄️remanage",
"❄️cetene",
"❄️bocardo",
"❄️consummation",
"❄️boycottism",
"❄️perplexity",
"❄️astay",
"❄️Gaetuli",
"❄️periplastic",
"❄️consolidator",
"❄️sluggarding",
"❄️coracoscapular",
"❄️anangioid",
"❄️oxygenizer",
"❄️Hunanese",
"❄️seminary",
"❄️periplast",
"❄️Corylus",
"❄️unoriginativeness",
"❄️persecutee",
"❄️tweaker",
"❄️silliness",
"❄️Dabitis",
"❄️facetiousness",
"❄️thymy",
"❄️nonimperial",
"❄️mesoblastema",
"❄️turbiniform",
"❄️churchway",
"❄️cooing",
"❄️frithbot",
"❄️concomitantly",
"❄️stalwartize",
"❄️clingfish",
"❄️hardmouthed",
"❄️parallelepipedonal",
"❄️coracoacromial",
"❄️factuality",
"❄️curtilage",
"❄️arachnoidean",
"❄️semiaridity",
"❄️phytobacteriology",
"❄️premastery",
"❄️hyperpurist",
"❄️mobed",
"❄️opportunistic",
"❄️acclimature",
"❄️outdistance",
"❄️sophister",
"❄️condonement",
"❄️oxygenerator",
"❄️acetonic",
"❄️emanatory",
"❄️periphlebitis",
"❄️nonsociety",
"❄️spectroradiometric",
"❄️superaverage",
"❄️cleanness",
"❄️posteroventral",
"❄️unadvised",
"❄️unmistakedly",
"❄️pimgenet",
"❄️auresca",
"❄️overimitate",
"❄️dipnoan",
"❄️chromoxylograph",
"❄️triakistetrahedron",
"❄️Suessiones",
"❄️uncopiable",
"❄️oligomenorrhea",
"❄️fribbling",
"❄️worriable",
"❄️flot",
"❄️ornithotrophy",
"❄️phytoteratology",
"❄️setup",
"❄️lanneret",
"❄️unbraceleted",
"❄️gudemother",
"❄️Spica",
"❄️unconsolatory",
"❄️recorruption",
"❄️premenstrual",
"❄️subretinal",
"❄️millennialist",
"❄️subjectibility",
"❄️rewardproof",
"❄️counterflight",
"❄️pilomotor",
"❄️carpetbaggery",
"❄️macrodiagonal",
"❄️slim",
"❄️indiscernible",
"❄️cuckoo",
"❄️moted",
"❄️controllingly",
"❄️gynecopathy",
"❄️porrectus",
"❄️wanworth",
"❄️lutfisk",
"❄️semiprivate",
"❄️philadelphy",
"❄️abdominothoracic",
"❄️coxcomb",
"❄️dambrod",
"❄️Metanemertini",
"❄️balminess",
"❄️homotypy",
"❄️waremaker",
"❄️absurdity",
"❄️gimcrack",
"❄️asquat",
"❄️suitable",
"❄️perimorphous",
"❄️kitchenwards",
"❄️pielum",
"❄️salloo",
"❄️paleontologic",
"❄️Olson",
"❄️Tellinidae",
"❄️ferryman",
"❄️peptonoid",
"❄️Bopyridae",
"❄️fallacy",
"❄️ictuate",
"❄️aguinaldo",
"❄️rhyodacite",
"❄️Ligydidae",
"❄️galvanometric",
"❄️acquisitor",
"❄️muscology",
"❄️hemikaryon",
"❄️ethnobotanic",
"❄️postganglionic",
"❄️rudimentarily",
"❄️replenish",
"❄️phyllorhine",
"❄️popgunnery",
"❄️summar",
"❄️quodlibetary",
"❄️xanthochromia",
"❄️autosymbolically",
"❄️preloreal",
"❄️extent",
"❄️strawberry",
"❄️immortalness",
"❄️colicwort",
"❄️frisca",
"❄️electiveness",
"❄️heartbroken",
"❄️affrightingly",
"❄️reconfiscation",
"❄️jacchus",
"❄️imponderably",
"❄️semantics",
"❄️beennut",
"❄️paleometeorological",
"❄️becost",
"❄️timberwright",
"❄️resuppose",
"❄️syncategorematical",
"❄️cytolymph",
"❄️steinbok",
"❄️explantation",
"❄️hyperelliptic",
"❄️antescript",
"❄️blowdown",
"❄️antinomical",
"❄️caravanserai",
"❄️unweariedly",
"❄️isonymic",
"❄️keratoplasty",
"❄️vipery",
"❄️parepigastric",
"❄️endolymphatic",
"❄️Londonese",
"❄️necrotomy",
"❄️angelship",
"❄️Schizogregarinida",
"❄️steeplebush",
"❄️sparaxis",
"❄️connectedness",
"❄️tolerance",
"❄️impingent",
"❄️agglutinin",
"❄️reviver",
"❄️hieroglyphical",
"❄️dialogize",
"❄️coestate",
"❄️declamatory",
"❄️ventilation",
"❄️tauromachy",
"❄️cotransubstantiate",
"❄️pome",
"❄️underseas",
"❄️triquadrantal",
"❄️preconfinemnt",
"❄️electroindustrial",
"❄️selachostomous",
"❄️nongolfer",
"❄️mesalike",
"❄️hamartiology",
"❄️ganglioblast",
"❄️unsuccessive",
"❄️yallow",
"❄️bacchanalianly",
"❄️platydactyl",
"❄️Bucephala",
"❄️ultraurgent",
"❄️penalist",
"❄️catamenial",
"❄️lynnhaven",
"❄️unrelevant",
"❄️lunkhead",
"❄️metropolitan",
"❄️hydro",
"❄️outsoar",
"❄️vernant",
"❄️interlanguage",
"❄️catarrhal",
"❄️Ionicize",
"❄️keelless",
"❄️myomantic",
"❄️booker",
"❄️Xanthomonas",
"❄️unimpeded",
"❄️overfeminize",
"❄️speronaro",
"❄️diaconia",
"❄️overholiness",
"❄️liquefacient",
"❄️Spartium",
"❄️haggly",
"❄️albumose",
"❄️nonnecessary",
"❄️sulcalization",
"❄️decapitate",
"❄️cellated",
"❄️unguirostral",
"❄️trichiurid",
"❄️loveproof",
"❄️amakebe",
"❄️screet",
"❄️arsenoferratin",
"❄️unfrizz",
"❄️undiscoverable",
"❄️procollectivistic",
"❄️tractile",
"❄️Winona",
"❄️dermostosis",
"❄️eliminant",
"❄️scomberoid",
"❄️tensile",
"❄️typesetting",
"❄️xylic",
"❄️dermatopathology",
"❄️cycloplegic",
"❄️revocable",
"❄️fissate",
"❄️afterplay",
"❄️screwship",
"❄️microerg",
"❄️bentonite",
"❄️stagecoaching",
"❄️beglerbeglic",
"❄️overcharitably",
"❄️Plotinism",
"❄️Veddoid",
"❄️disequalize",
"❄️cytoproct",
"❄️trophophore",
"❄️antidote",
"❄️allerion",
"❄️famous",
"❄️convey",
"❄️postotic",
"❄️rapillo",
"❄️cilectomy",
"❄️penkeeper",
"❄️patronym",
"❄️bravely",
"❄️ureteropyelitis",
"❄️Hildebrandine",
"❄️missileproof",
"❄️Conularia",
"❄️deadening",
"❄️Conrad",
"❄️pseudochylous",
"❄️typologically",
"❄️strummer",
"❄️luxuriousness",
"❄️resublimation",
"❄️glossiness",
"❄️hydrocauline",
"❄️anaglyph",
"❄️personifiable",
"❄️seniority",
"❄️formulator",
"❄️datiscaceous",
"❄️hydracrylate",
"❄️Tyranni",
"❄️Crawthumper",
"❄️overprove",
"❄️masher",
"❄️dissonance",
"❄️Serpentinian",
"❄️malachite",
"❄️interestless",
"❄️stchi",
"❄️ogum",
"❄️polyspermic",
"❄️archegoniate",
"❄️precogitation",
"❄️Alkaphrah",
"❄️craggily",
"❄️delightfulness",
"❄️bioplast",
"❄️diplocaulescent",
"❄️neverland",
"❄️interspheral",
"❄️chlorhydric",
"❄️forsakenly",
"❄️scandium",
"❄️detubation",
"❄️telega",
"❄️Valeriana",
"❄️centraxonial",
"❄️anabolite",
"❄️neger",
"❄️miscellanea",
"❄️whalebacker",
"❄️stylidiaceous",
"❄️unpropelled",
"❄️Kennedya",
"❄️Jacksonite",
"❄️ghoulish",
"❄️Dendrocalamus",
"❄️paynimhood",
"❄️rappist",
"❄️unluffed",
"❄️falling",
"❄️Lyctus",
"❄️uncrown",
"❄️warmly",
"❄️pneumatism",
"❄️Morisonian",
"❄️notate",
"❄️isoagglutinin",
"❄️Pelidnota",
"❄️previsit",
"❄️contradistinctly",
"❄️utter",
"❄️porometer",
"❄️gie",
"❄️germanization",
"❄️betwixt",
"❄️prenephritic",
"❄️underpier",
"❄️Eleutheria",
"❄️ruthenious",
"❄️convertor",
"❄️antisepsin",
"❄️winterage",
"❄️tetramethylammonium",
"❄️Rockaway",
"❄️Penaea",
"❄️prelatehood",
"❄️brisket",
"❄️unwishful",
"❄️Minahassa",
"❄️Briareus",
"❄️semiaxis",
"❄️disintegrant",
"❄️peastick",
"❄️iatromechanical",
"❄️fastus",
"❄️thymectomy",
"❄️ladyless",
"❄️unpreened",
"❄️overflutter",
"❄️sicker",
"❄️apsidally",
"❄️thiazine",
"❄️guideway",
"❄️pausation",
"❄️tellinoid",
"❄️abrogative",
"❄️foraminulate",
"❄️omphalos",
"❄️Monorhina",
"❄️polymyarian",
"❄️unhelpful",
"❄️newslessness",
"❄️oryctognosy",
"❄️octoradial",
"❄️doxology",
"❄️arrhythmy",
"❄️gugal",
"❄️mesityl",
"❄️hexaplaric",
"❄️Cabirian",
"❄️hordeiform",
"❄️eddyroot",
"❄️internarial",
"❄️deservingness",
"❄️jawbation",
"❄️orographically",
"❄️semiprecious",
"❄️seasick",
"❄️thermically",
"❄️grew",
"❄️tamability",
"❄️egotistically",
"❄️fip",
"❄️preabsorbent",
"❄️leptochroa",
"❄️ethnobotany",
"❄️podolite",
"❄️egoistic",
"❄️semitropical",
"❄️cero",
"❄️spinelessness",
"❄️onshore",
"❄️omlah",
"❄️tintinnabulist",
"❄️machila",
"❄️entomotomy",
"❄️nubile",
"❄️nonscholastic",
"❄️burnt",
"❄️Alea",
"❄️befume",
"❄️doctorless",
"❄️Napoleonic",
"❄️scenting",
"❄️apokreos",
"❄️cresylene",
"❄️paramide",
"❄️rattery",
"❄️disinterested",
"❄️idiopathetic",
"❄️negatory",
"❄️fervid",
"❄️quintato",
"❄️untricked",
"❄️Metrosideros",
"❄️mescaline",
"❄️midverse",
"❄️Musophagidae",
"❄️fictionary",
"❄️branchiostegous",
"❄️yoker",
"❄️residuum",
"❄️culmigenous",
"❄️fleam",
"❄️suffragism",
"❄️Anacreon",
"❄️sarcodous",
"❄️parodistic",
"❄️writmaking",
"❄️conversationism",
"❄️retroposed",
"❄️tornillo",
"❄️presuspect",
"❄️didymous",
"❄️Saumur",
"❄️spicing",
"❄️drawbridge",
"❄️cantor",
"❄️incumbrancer",
"❄️heterospory",
"❄️Turkeydom",
"❄️anteprandial",
"❄️neighborship",
"❄️thatchless",
"❄️drepanoid",
"❄️lusher",
"❄️paling",
"❄️ecthlipsis",
"❄️heredosyphilitic",
"❄️although",
"❄️garetta",
"❄️temporarily",
"❄️Monotropa",
"❄️proglottic",
"❄️calyptro",
"❄️persiflage",
"❄️degradable",
"❄️paraspecific",
"❄️undecorative",
"❄️Pholas",
"❄️myelon",
"❄️resteal",
"❄️quadrantly",
"❄️scrimped",
"❄️airer",
"❄️deviless",
"❄️caliciform",
"❄️Sefekhet",
"❄️shastaite",
"❄️togate",
"❄️macrostructure",
"❄️bipyramid",
"❄️wey",
"❄️didynamy",
"❄️knacker",
"❄️swage",
"❄️supermanism",
"❄️epitheton",
"❄️overpresumptuous"
]
public func run_SortStringsUnicode(_ N: Int) {
for _ in 1...5*N {
benchSortStrings(unicodeWords)
}
}
|
apache-2.0
|
743b452857b24c08354070e4eb877d78
| 16.214494 | 128 | 0.586783 | 2.551031 | false | false | false | false |
vuchau/realm-cocoa
|
RealmSwift-swift1.2/RealmCollectionType.swift
|
18
|
24740
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 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
/**
Encapsulates iteration state and interface for iteration over a
`RealmCollectionType`.
*/
public final class RLMGenerator<T: Object>: GeneratorType {
private let generatorBase: NSFastGenerator
internal init(collection: RLMCollection) {
generatorBase = NSFastGenerator(collection)
}
/// Advance to the next element and return it, or `nil` if no next element
/// exists.
public func next() -> T? {
let accessor = generatorBase.next() as! T?
if let accessor = accessor {
RLMInitializeSwiftListAccessor(accessor)
}
return accessor
}
}
/**
A homogenous collection of `Object`s which can be retrieved, filtered, sorted,
and operated upon.
*/
public protocol RealmCollectionType: CollectionType, Printable {
/// Element type contained in this collection.
typealias Element: Object
// MARK: Properties
/// The Realm the objects in this collection belong to, or `nil` if the
/// collection's owning object does not belong to a realm (the collection is
/// standalone).
var realm: Realm? { get }
/// Returns the number of objects in this collection.
var count: Int { get }
/// Returns a human-readable description of the objects contained in this collection.
var description: String { get }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
:param: object The object whose index is being queried.
:returns: The index of the given object, or `nil` if the object is not in the collection.
*/
func indexOf(object: Element) -> Int?
/**
Returns the index of the first object matching the given predicate,
or `nil` no objects match.
:param: predicate The `NSPredicate` used to filter the objects.
:returns: The index of the given object, or `nil` if no objects match.
*/
func indexOf(predicate: NSPredicate) -> Int?
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
:param: predicateFormat The predicate format string, optionally followed by a variable number
of arguments.
:returns: The index of the given object, or `nil` if no objects match.
*/
func indexOf(predicateFormat: String, _ args: CVarArgType...) -> Int?
// MARK: Object Retrieval
/// Returns the first object in the collection, or `nil` if empty.
var first: Element? { get }
/// Returns the last object in the collection, or `nil` if empty.
var last: Element? { get }
// MARK: Filtering
/**
Returns `Results` containing collection elements that match the given predicate.
:param: predicateFormat The predicate format string which can accept variable arguments.
:returns: `Results` containing collection elements that match the given predicate.
*/
func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<Element>
/**
Returns `Results` containing collection elements that match the given predicate.
:param: predicate The predicate to filter the objects.
:returns: `Results` containing collection elements that match the given predicate.
*/
func filter(predicate: NSPredicate) -> Results<Element>
// MARK: Sorting
/**
Returns `Results` containing collection elements sorted by the given property.
:param: property The property name to sort by.
:param: ascending The direction to sort by.
:returns: `Results` containing collection elements sorted by the given property.
*/
func sorted(property: String, ascending: Bool) -> Results<Element>
/**
Returns `Results` with elements sorted by the given sort descriptors.
:param: sortDescriptors `SortDescriptor`s to sort by.
:returns: `Results` with elements sorted by the given sort descriptors.
*/
func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element>
// MARK: Aggregate Operations
/**
Returns the minimum value of the given property.
:warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
:param: property The name of a property conforming to `MinMaxType` to look for a minimum on.
:returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty.
*/
func min<U: MinMaxType>(property: String) -> U?
/**
Returns the maximum value of the given property.
:warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
:param: property The name of a property conforming to `MinMaxType` to look for a maximum on.
:returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty.
*/
func max<U: MinMaxType>(property: String) -> U?
/**
Returns the sum of the given property for objects in the collection.
:warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
:param: property The name of a property conforming to `AddableType` to calculate sum on.
:returns: The sum of the given property over all objects in the collection.
*/
func sum<U: AddableType>(property: String) -> U
/**
Returns the average of the given property for objects in the collection.
:warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
:param: property The name of a property conforming to `AddableType` to calculate average on.
:returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty.
*/
func average<U: AddableType>(property: String) -> U?
// MARK: Key-Value Coding
/**
Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects.
:param: key The name of the property.
:returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects.
*/
func valueForKey(key: String) -> AnyObject?
/**
Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key.
:warning: This method can only be called during a write transaction.
:param: value The object value.
:param: key The name of the property.
*/
func setValue(value: AnyObject?, forKey key: String)
}
private class _AnyRealmCollectionBase<T: Object>: RealmCollectionType {
typealias Element = T
var realm: Realm? { fatalError() }
var count: Int { fatalError() }
var description: String { fatalError() }
func indexOf(object: Element) -> Int? { fatalError() }
func indexOf(predicate: NSPredicate) -> Int? { fatalError() }
func indexOf(predicateFormat: String, _ args: CVarArgType...) -> Int? { fatalError() }
var first: Element? { fatalError() }
var last: Element? { fatalError() }
func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<Element> { fatalError() }
func filter(predicate: NSPredicate) -> Results<Element> { fatalError() }
func sorted(property: String, ascending: Bool) -> Results<Element> { fatalError() }
func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> { fatalError() }
func min<U: MinMaxType>(property: String) -> U? { fatalError() }
func max<U: MinMaxType>(property: String) -> U? { fatalError() }
func sum<U: AddableType>(property: String) -> U { fatalError() }
func average<U: AddableType>(property: String) -> U? { fatalError() }
subscript(index: Int) -> Element { fatalError() }
func generate() -> RLMGenerator<T> { fatalError() }
var startIndex: Int { fatalError() }
var endIndex: Int { fatalError() }
func valueForKey(key: String) -> AnyObject? { fatalError() }
func setValue(value: AnyObject?, forKey key: String) { fatalError() }
}
private final class _AnyRealmCollection<C: RealmCollectionType>: _AnyRealmCollectionBase<C.Element> {
let base: C
init(base: C) {
self.base = base
}
// MARK: Properties
/// The Realm the objects in this collection belong to, or `nil` if the
/// collection's owning object does not belong to a realm (the collection is
/// standalone).
override var realm: Realm? { return base.realm }
/// Returns the number of objects in this collection.
override var count: Int { return base.count }
/// Returns a human-readable description of the objects contained in this collection.
override var description: String { return base.description }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
:param: object The object whose index is being queried.
:returns: The index of the given object, or `nil` if the object is not in the collection.
*/
override func indexOf(object: C.Element) -> Int? { return base.indexOf(object) }
/**
Returns the index of the first object matching the given predicate,
or `nil` no objects match.
- parameter predicate: The `NSPredicate` used to filter the objects.
- returns: The index of the given object, or `nil` if no objects match.
*/
override func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) }
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
- parameter predicateFormat: The predicate format string, optionally followed by a variable number
of arguments.
- returns: The index of the given object, or `nil` if no objects match.
*/
override func indexOf(predicateFormat: String, _ args: CVarArgType...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, arguments: getVaList(args))) }
// MARK: Object Retrieval
/// Returns the first object in the collection, or `nil` if empty.
override var first: C.Element? { return base.first }
/// Returns the last object in the collection, or `nil` if empty.
override var last: C.Element? { return base.last }
// MARK: Filtering
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicateFormat: The predicate format string which can accept variable arguments.
- returns: `Results` containing collection elements that match the given predicate.
*/
override func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<C.Element> { return base.filter(NSPredicate(format: predicateFormat, arguments: getVaList(args))) }
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicate: The predicate to filter the objects.
- returns: `Results` containing collection elements that match the given predicate.
*/
override func filter(predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) }
// MARK: Sorting
/**
Returns `Results` containing collection elements sorted by the given property.
- parameter property: The property name to sort by.
- parameter ascending: The direction to sort by.
- returns: `Results` containing collection elements sorted by the given property.
*/
override func sorted(property: String, ascending: Bool) -> Results<C.Element> { return base.sorted(property, ascending: ascending) }
/**
Returns `Results` with elements sorted by the given sort descriptors.
- parameter sortDescriptors: `SortDescriptor`s to sort by.
- returns: `Results` with elements sorted by the given sort descriptors.
*/
override func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<C.Element> { return base.sorted(sortDescriptors) }
// MARK: Aggregate Operations
/**
Returns the minimum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on.
- returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty.
*/
override func min<U: MinMaxType>(property: String) -> U? { return base.min(property) }
/**
Returns the maximum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on.
- returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty.
*/
override func max<U: MinMaxType>(property: String) -> U? { return base.max(property) }
/**
Returns the sum of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
- returns: The sum of the given property over all objects in the collection.
*/
override func sum<U: AddableType>(property: String) -> U { return base.sum(property) }
/**
Returns the average of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate average on.
- returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty.
*/
override func average<U: AddableType>(property: String) -> U? { return base.average(property) }
// MARK: Sequence Support
/**
Returns the object at the given `index`.
- parameter index: The index.
- returns: The object at the given `index`.
*/
override subscript(index: Int) -> C.Element { return base[index as! C.Index] as! C.Element } // FIXME: it should be possible to avoid this force-casting
/// Returns a `GeneratorOf<Element>` that yields successive elements in the collection.
override func generate() -> RLMGenerator<Element> { return base.generate() as! RLMGenerator<Element> } // FIXME: it should be possible to avoid this force-casting
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
override var startIndex: Int { return base.startIndex as! Int } // FIXME: it should be possible to avoid this force-casting
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor().
override var endIndex: Int { return base.endIndex as! Int } // FIXME: it should be possible to avoid this force-casting
// MARK: Key-Value Coding
/**
Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects.
:param: key The name of the property.
:returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects.
*/
override func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) }
/**
Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key.
:warning: This method can only be called during a write transaction.
:param: value The object value.
:param: key The name of the property.
*/
override func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) }
}
/**
A type-erased `RealmCollectionType`.
Forwards operations to an arbitrary underlying collection having the same
Element type, hiding the specifics of the underlying `RealmCollectionType`.
*/
public final class AnyRealmCollection<T: Object>: RealmCollectionType {
/// Element type contained in this collection.
public typealias Element = T
private let base: _AnyRealmCollectionBase<T>
/// Creates an AnyRealmCollection wrapping `base`.
public init<C: RealmCollectionType where C.Element == T>(_ base: C) {
self.base = _AnyRealmCollection(base: base)
}
// MARK: Properties
/// The Realm the objects in this collection belong to, or `nil` if the
/// collection's owning object does not belong to a realm (the collection is
/// standalone).
public var realm: Realm? { return base.realm }
/// Returns the number of objects in this collection.
public var count: Int { return base.count }
/// Returns a human-readable description of the objects contained in this collection.
public var description: String { return base.description }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
:param: object The object whose index is being queried.
:returns: The index of the given object, or `nil` if the object is not in the collection.
*/
public func indexOf(object: Element) -> Int? { return base.indexOf(object) }
/**
Returns the index of the first object matching the given predicate,
or `nil` no objects match.
- parameter predicate: The `NSPredicate` used to filter the objects.
- returns: The index of the given object, or `nil` if no objects match.
*/
public func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) }
/**
Returns the index of the first object matching the given predicate,
or `nil` if no objects match.
- parameter predicateFormat: The predicate format string, optionally followed by a variable number
of arguments.
- returns: The index of the given object, or `nil` if no objects match.
*/
public func indexOf(predicateFormat: String, _ args: CVarArgType...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, arguments: getVaList(args))) }
// MARK: Object Retrieval
/// Returns the first object in the collection, or `nil` if empty.
public var first: Element? { return base.first }
/// Returns the last object in the collection, or `nil` if empty.
public var last: Element? { return base.last }
// MARK: Filtering
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicateFormat: The predicate format string which can accept variable arguments.
- returns: `Results` containing collection elements that match the given predicate.
*/
public func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<Element> { return base.filter(NSPredicate(format: predicateFormat, arguments: getVaList(args))) }
/**
Returns `Results` containing collection elements that match the given predicate.
- parameter predicate: The predicate to filter the objects.
- returns: `Results` containing collection elements that match the given predicate.
*/
public func filter(predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) }
// MARK: Sorting
/**
Returns `Results` containing collection elements sorted by the given property.
- parameter property: The property name to sort by.
- parameter ascending: The direction to sort by.
- returns: `Results` containing collection elements sorted by the given property.
*/
public func sorted(property: String, ascending: Bool) -> Results<Element> { return base.sorted(property, ascending: ascending) }
/**
Returns `Results` with elements sorted by the given sort descriptors.
- parameter sortDescriptors: `SortDescriptor`s to sort by.
- returns: `Results` with elements sorted by the given sort descriptors.
*/
public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> { return base.sorted(sortDescriptors) }
// MARK: Aggregate Operations
/**
Returns the minimum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on.
- returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty.
*/
public func min<U: MinMaxType>(property: String) -> U? { return base.min(property) }
/**
Returns the maximum value of the given property.
- warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used.
- parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on.
- returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty.
*/
public func max<U: MinMaxType>(property: String) -> U? { return base.max(property) }
/**
Returns the sum of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
- returns: The sum of the given property over all objects in the collection.
*/
public func sum<U: AddableType>(property: String) -> U { return base.sum(property) }
/**
Returns the average of the given property for objects in the collection.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate average on.
- returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty.
*/
public func average<U: AddableType>(property: String) -> U? { return base.average(property) }
// MARK: Sequence Support
/**
Returns the object at the given `index`.
- parameter index: The index.
- returns: The object at the given `index`.
*/
public subscript(index: Int) -> T { return base[index] }
/// Returns a `GeneratorOf<T>` that yields successive elements in the collection.
public func generate() -> RLMGenerator<T> { return base.generate() }
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return base.startIndex }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor().
public var endIndex: Int { return base.endIndex }
// MARK: Key-Value Coding
/**
Returns an Array containing the results of invoking `valueForKey:` using key on each of the collection's objects.
:param: key The name of the property.
:returns: Array containing the results of invoking `valueForKey:` using key on each of the collection's objects.
*/
public func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) }
/**
Invokes `setValue:forKey:` on each of the collection's objects using the specified value and key.
:warning: This method can only be called during a write transaction.
:param: value The object value.
:param: key The name of the property.
*/
public func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) }
}
|
apache-2.0
|
c2a1674e192510a0d274739f34f82346
| 36.770992 | 184 | 0.695998 | 4.635563 | false | false | false | false |
msencenb/icnam
|
iCNAM/cnam.swift
|
1
|
1502
|
//
// cnam.swift
// iCNAM
//
// Created by Corey Edwards on 8/13/15.
// Copyright (c) 2015 Corey Edwards. All rights reserved.
//
import Foundation
/* Set testing API creds. This will change in the working version to pull creds from CoreData store.
These credentials are EveryoneAPI testing creds only and will not work on actual requests. */
let account_sid = "AC2877277cd21a44af8e9344c53bb1311";
let auth_token = "AUe03f0c1796c04eed8d838061895b4534";
// This is the magic sauce - the API call
func query(phoneNumber: String) {
var api : EveryoneAPI = EveryoneAPI(accountSID: account_sid, withAuthToken: auth_token)
var errorHandler: EveryoneAPIErrorHandler = { readableError in print(readableError) }
var successHandler: EveryoneAPISuccessHandler = { response in print(response.cnam) }
api.getInformation(EveryoneAPIReturnData.CNAM, forPhoneNumber: "2532171703", withSuccessHandler: successHandler, withErrorHandler: errorHandler)
//EveryoneAPI.getInformation(phoneNumber: phoneNumber, withSuccessHandler, withErrorHandler)
/* EveryoneAPI *everyoneAPI = [[EveryoneAPI alloc] initWithAccountSID:@"accountSID" withAuthToken:@"authToken"];
[everyoneAPI getInformation:EveryoneAPIReturnAllInfo forPhoneNumber:@"5551234567" withSuccessHandler:^(EveryoneAPIResponseObject *responseObject){
//Success handler here
} withErrorHandler:^(NSError *error, NSNumber *statusCode, NSString *readableError){
//Error handler here
}]; */
}
|
mit
|
203213318b06383a13763069346baf2b
| 39.621622 | 150 | 0.758322 | 3.942257 | false | true | false | false |
tjw/swift
|
test/Constraints/iuo.swift
|
2
|
4722
|
// RUN: %target-typecheck-verify-swift
func basic() {
var i: Int! = 0
let _: Int = i
i = 7
}
func takesIUOs(i: Int!, j: inout Int!) -> Int {
j = 7
return i
}
struct S {
let i: Int!
var j: Int!
let k: Int
var m: Int
var n: Int! {
get {
return m
}
set {
m = newValue
}
}
var o: Int! {
willSet {
m = newValue
}
didSet {
m = oldValue
}
}
func fn() -> Int! { return i }
static func static_fn() -> Int! { return 0 }
subscript(i: Int) -> Int! {
set {
m = newValue
}
get {
return i
}
}
init(i: Int!, j: Int!, k: Int, m: Int) {
self.i = i
self.j = j
self.k = k
self.m = m
}
init!() {
i = 0
j = 0
k = 0
m = 0
}
}
func takesStruct(s: S) {
let _: Int = s.i
let _: Int = s.j
var t: S! = s
t.j = 7
}
var a: (Int, Int)! = (0, 0)
a.0 = 42
var s: S! = S(i: nil, j: 1, k: 2, m: 3)
_ = s.i
let _: Int = s.j
_ = s.k
s.m = 7
s.j = 3
let _: Int = s[0]
struct T {
let i: Float!
var j: Float!
func fn() -> Float! { return i }
}
func overloaded() -> S { return S(i: 0, j: 1, k: 2, m: 3) }
func overloaded() -> T { return T(i: 0.5, j: 1.5) }
let _: Int = overloaded().i
func cflow(i: Int!, j: inout Bool!, s: S) {
let k: Int? = i
let m: Int = i
let b: Bool! = i == 0
if i == 7 {
if s.i == 7 {
}
}
let _ = b ? i : k
let _ = b ? i : m
let _ = b ? j : b
let _ = b ? s.j : s.k
if b {}
if j {}
let _ = j ? 7 : 0
}
func forcedResultInt() -> Int! {
return 0
}
let _: Int = forcedResultInt()
func forcedResult() -> Int! {
return 0
}
func forcedResult() -> Float! {
return 0
}
func overloadedForcedResult() -> Int {
return forcedResult()
}
func forceMemberResult(s: S) -> Int {
return s.fn()
}
func forceStaticMemberResult() -> Int {
return S.static_fn()
}
func overloadedForceMemberResult() -> Int {
return overloaded().fn()
}
func overloadedForcedStructResult() -> S! { return S(i: 0, j: 1, k: 2, m: 3) }
func overloadedForcedStructResult() -> T! { return T(i: 0.5, j: 1.5) }
let _: S = overloadedForcedStructResult()
let _: Int = overloadedForcedStructResult().i
func id<T>(_ t: T) -> T { return t }
protocol P { }
extension P {
func iuoResult(_ b: Bool) -> Self! { }
static func iuoResultStatic(_ b: Bool) -> Self! { }
}
func cast<T : P>(_ t: T) {
let _: (T) -> (Bool) -> T? = id(T.iuoResult as (T) -> (Bool) -> T?)
let _: (Bool) -> T? = id(T.iuoResult(t) as (Bool) -> T?)
let _: T! = id(T.iuoResult(t)(true))
let _: (Bool) -> T? = id(t.iuoResult as (Bool) -> T?)
let _: T! = id(t.iuoResult(true))
let _: T = id(t.iuoResult(true))
let _: (Bool) -> T? = id(T.iuoResultStatic as (Bool) -> T?)
let _: T! = id(T.iuoResultStatic(true))
}
class rdar37241550 {
public init(blah: Float) { fatalError() }
public convenience init() { fatalError() }
public convenience init!(with void: ()) { fatalError() }
static func f(_ fn: () -> rdar37241550) {}
static func test() {
f(rdar37241550.init) // no error, the failable init is not applicable
}
}
class B {}
class D : B {
var i: Int!
}
func coerceToIUO(d: D?) -> B {
return d as B! // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func forcedDowncastToOptional(b: B?) -> D? {
return b as! D! // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func forcedDowncastToObject(b: B?) -> D {
return b as! D! // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func forcedDowncastToObjectIUOMember(b: B?) -> Int {
return (b as! D!).i // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func forcedUnwrapViaForcedCast(b: B?) -> B {
return b as! B! // expected-warning {{forced cast from 'B?' to 'B' only unwraps optionals; did you mean to use '!'?}}
// expected-warning@-1 {{using '!' here is deprecated and will be removed in a future release}}
}
func conditionalDowncastToOptional(b: B?) -> D? {
return b as? D! // expected-warning {{using '!' here is deprecated and will be removed in a future release}}
}
func conditionalDowncastToObject(b: B?) -> D {
return b as? D! // expected-error {{value of optional type 'D?' not unwrapped; did you mean to use '!' or '?'?}}
// expected-warning@-1 {{using '!' here is deprecated and will be removed in a future release}}
}
// Ensure that we select the overload that does *not* involve forcing an IUO.
func sr6988(x: Int?, y: Int?) -> Int { return x! }
func sr6988(x: Int, y: Int) -> Float { return Float(x) }
var x: Int! = nil
var y: Int = 2
let r = sr6988(x: x, y: y)
let _: Int = r
|
apache-2.0
|
e7bb54a3fce2195ca3fa7e969c02159b
| 19.986667 | 119 | 0.569674 | 2.900491 | false | false | false | false |
crspybits/SMSyncServer
|
iOS/iOSTests/XCTests/SharingUserOperations.swift
|
1
|
26761
|
//
// SharingUserOperations.swift
// Tests
//
// Created by Christopher Prince on 6/17/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
import XCTest
import SMCoreLib
@testable import SMSyncServer
@testable import Tests
class SharingUserOperations: BaseClass {
var downloadingInvitations = [SMPersistItemString]()
var uploadingInvitations = [SMPersistItemString]()
var adminInvitations = [SMPersistItemString]()
let numberInvitationsPerType = 5
func setupPersistentInvitationsFor(sharingType:SMSharingType, inout result:[SMPersistItemString]) {
for invitationNumber in 1...numberInvitationsPerType {
let persisentInvitationName =
"SharingUsers.invitation\(sharingType.rawValue).\(invitationNumber)"
let persisentInvitation = SMPersistItemString(name: persisentInvitationName, initialStringValue: "", persistType: .UserDefaults)
result.append(persisentInvitation)
}
}
override func setUp() {
super.setUp()
self.setupPersistentInvitationsFor(.Downloader, result: &self.downloadingInvitations)
self.setupPersistentInvitationsFor(.Uploader, result: &self.uploadingInvitations)
self.setupPersistentInvitationsFor(.Admin, result: &self.adminInvitations)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func createInvitations(sharingType sharingType:SMSharingType, invitationNumber:Int, inout persistentInvitations:[SMPersistItemString], completed:(()->())?) {
if invitationNumber < self.numberInvitationsPerType {
SMServerAPI.session.createSharingInvitation(sharingType: sharingType.rawValue, completion: { (invitationCode, apiResult) in
XCTAssert(apiResult.error == nil)
XCTAssert(invitationCode != nil)
persistentInvitations[invitationNumber].stringValue = invitationCode!
self.createInvitations(sharingType: sharingType, invitationNumber: invitationNumber+1, persistentInvitations: &persistentInvitations, completed: completed)
})
}
else {
completed?()
}
}
func createDownloadingInvitations(completed:()->()) {
self.createInvitations(sharingType:.Downloader, invitationNumber:0, persistentInvitations: &self.downloadingInvitations) {
completed()
}
}
func createUploadingInvitations(completed:()->()) {
self.createInvitations(sharingType:.Uploader, invitationNumber:0, persistentInvitations: &self.uploadingInvitations) {
completed()
}
}
func createAdminInvitations(completed:()->()) {
self.createInvitations(sharingType:.Admin, invitationNumber:0, persistentInvitations: &self.adminInvitations) {
completed()
}
}
var uploadFile1:TestFile!
var uploadFile2:TestFile!
var uploadFile3:TestFile!
let uploadFile1UUID = SMPersistItemString(name: "SharingUserOperations.uploadFile1", initialStringValue: "", persistType: .UserDefaults)
let uploadFile2UUID = SMPersistItemString(name: "SharingUserOperations.uploadFile2", initialStringValue: "", persistType: .UserDefaults)
let uploadFile3UUID = SMPersistItemString(name: "SharingUserOperations.uploadFile3", initialStringValue: "", persistType: .UserDefaults)
func createUploadFiles(initial initial:Bool) {
if initial {
self.uploadFile1 = TestBasics.session.createTestFile("FileDownloadByDownloadSharingUser")
self.uploadFile1UUID.stringValue = self.uploadFile1.uuidString
self.uploadFile2 = TestBasics.session.createTestFile("DownloadDeletionByDownloadSharingUser")
self.uploadFile2UUID.stringValue = self.uploadFile2.uuidString
self.uploadFile3 = TestBasics.session.createTestFile("UploadDeletionByDownloadSharingUser")
self.uploadFile3UUID.stringValue = self.uploadFile3.uuidString
}
else {
self.uploadFile1 = TestBasics.session.recreateTestFile(fromUUID: self.uploadFile1UUID.stringValue)
self.uploadFile2 = TestBasics.session.recreateTestFile(fromUUID: self.uploadFile2UUID.stringValue)
self.uploadFile3 = TestBasics.session.recreateTestFile(fromUUID: self.uploadFile3UUID.stringValue)
}
}
// Do this before any of the following tests.
// Must be signed in as Owning User.
func testSetupRemainingTests() {
let setupDone = self.expectationWithDescription("Done Setup")
self.extraServerResponseTime = Double(self.numberInvitationsPerType) * 3 * 20
let uploadExpectations1 = UploadFileExpectations(fromTestClass: self)
let uploadExpectations2 = UploadFileExpectations(fromTestClass: self)
let uploadExpectations3 = UploadFileExpectations(fromTestClass: self)
let uploadDeletionExpectations = UploadDeletionExpectations(fromTestClass: self)
self.createUploadFiles(initial:true)
self.waitUntilSyncServerUserSignin() {
self.createDownloadingInvitations() {
self.createUploadingInvitations() {
self.createAdminInvitations() {
SMServerAPI.session.createSharingInvitation(sharingType: SMSharingType.Downloader.rawValue, completion: { (invitationCode, apiResult) in
XCTAssert(apiResult.error == nil)
XCTAssert(invitationCode != nil)
// So I can sign in as a sharing user below.
AppDelegate.sharingInvitationCode = invitationCode!
self.uploadFile(self.uploadFile1, expectations: uploadExpectations1) {
self.uploadFile(self.uploadFile2, expectations: uploadExpectations2) {
self.uploadDeletion(self.uploadFile2, expectation: uploadDeletionExpectations) {
self.uploadFile(self.uploadFile3, expectations: uploadExpectations3) {
setupDone.fulfill()
}
}
}
}
})
}
}
}
}
self.waitForExpectations()
}
class UploadFileExpectations {
var uploadCompleteCallbackExpectation:XCTestExpectation
var singleUploadExpectation:XCTestExpectation
var idleExpectation:XCTestExpectation
init(fromTestClass testClass:XCTestCase) {
self.uploadCompleteCallbackExpectation = testClass.expectationWithDescription("Upload Complete")
self.singleUploadExpectation = testClass.expectationWithDescription("Single Upload Complete")
self.idleExpectation = testClass.expectationWithDescription("Idle")
}
}
class DownloadFileExpectations {
var singleDownloadExpectation:XCTestExpectation
var allDownloadsCompleteExpectation:XCTestExpectation
var idleExpectation:XCTestExpectation
init(fromTestClass testClass:XCTestCase) {
self.singleDownloadExpectation = testClass.expectationWithDescription("Single Download")
self.allDownloadsCompleteExpectation = testClass.expectationWithDescription("All Downloads Complete")
self.idleExpectation = testClass.expectationWithDescription("Idl1")
}
}
class UploadDeletionExpectations {
var deletionExpectation:XCTestExpectation
var idleExpectation:XCTestExpectation
var commitCompleteExpectation:XCTestExpectation
init(fromTestClass testClass:XCTestCase) {
self.deletionExpectation = testClass.expectationWithDescription("Deletion")
self.idleExpectation = testClass.expectationWithDescription("Idle Complete")
self.commitCompleteExpectation = testClass.expectationWithDescription("Commit")
}
}
class DownloadDeletionExpectations {
var clientShouldDeleteFilesExpectation:XCTestExpectation
var idle:XCTestExpectation
init(fromTestClass testClass:XCTestCase) {
self.clientShouldDeleteFilesExpectation = testClass.expectationWithDescription("Deletion")
self.idle = testClass.expectationWithDescription("Idle Complete")
}
}
func uploadFile(testFile:TestFile, expectations:UploadFileExpectations, failureExpected:Bool=false, complete:(()->())?=nil) {
try! SMSyncServer.session.uploadImmutableFile(testFile.url, withFileAttributes: testFile.attr)
if !failureExpected {
self.singleUploadCallbacks.append() { uuid in
XCTAssert(uuid.UUIDString == testFile.uuidString)
expectations.singleUploadExpectation.fulfill()
}
}
self.idleCallbacks.append() {
expectations.idleExpectation.fulfill()
}
if failureExpected {
self.errorCallbacks.append() {
// SMSyncServer.session.cleanupFile(testFile.uuid)
// CoreData.sessionNamed(CoreDataTests.name).removeObject(
// testFile.appFile)
// CoreData.sessionNamed(CoreDataTests.name).saveContext()
SMSyncServer.session.resetFromError() { error in
Log.msg("SMSyncServer.session.resetFromError: Completed")
XCTAssert(error == nil)
// These aren't really true, but we need to fulfil them to clean up.
expectations.uploadCompleteCallbackExpectation.fulfill()
expectations.singleUploadExpectation.fulfill()
complete?()
}
}
}
else {
self.commitCompleteCallbacks.append() { numberUploads in
XCTAssert(numberUploads == 1)
TestBasics.session.checkFileSize(testFile.uuidString, size: testFile.sizeInBytes) {
expectations.uploadCompleteCallbackExpectation.fulfill()
complete?()
}
}
}
try! SMSyncServer.session.commit()
}
func downloadFile(testFile:TestFile, expectations:DownloadFileExpectations,
complete:(()->())?=nil) {
var numberDownloads = 0
SMSyncServer.session.resetMetaData(forUUID: testFile.uuid)
self.singleDownload.append() { (downloadedFile:NSURL, downloadedFileAttr: SMSyncAttributes) in
XCTAssert(downloadedFileAttr.uuid.UUIDString == testFile.uuidString)
let filesAreTheSame = SMFiles.compareFiles(file1: testFile.url, file2: downloadedFile)
XCTAssert(filesAreTheSame)
numberDownloads += 1
expectations.singleDownloadExpectation.fulfill()
}
self.shouldSaveDownloads.append() { downloadedFiles, ack in
XCTAssert(numberDownloads == 1)
XCTAssert(downloadedFiles.count == 1)
let (_, _) = downloadedFiles[0]
expectations.allDownloadsCompleteExpectation.fulfill()
ack()
}
self.idleCallbacks.append() {
expectations.idleExpectation.fulfill()
complete?()
}
// Force the check for downloads.
SMSyncControl.session.nextSyncOperation()
}
func uploadDeletion(testFile:TestFile, expectation:UploadDeletionExpectations, failureExpected:Bool=false, complete:(()->())?=nil) {
try! SMSyncServer.session.deleteFile(testFile.uuid)
if failureExpected {
expectation.deletionExpectation.fulfill()
}
else {
self.deletionCallbacks.append() { uuids in
XCTAssert(uuids.count == 1)
XCTAssert(uuids[0].UUIDString == testFile.uuidString)
expectation.deletionExpectation.fulfill()
}
}
// The .Idle callback gets called first
self.idleCallbacks.append() {
expectation.idleExpectation.fulfill()
}
if failureExpected {
self.errorCallbacks.append() {
//SMSyncServer.session.cleanupFile(testFile.uuid)
//CoreData.sessionNamed(CoreDataTests.name).removeObject(
// testFile.appFile)
//CoreData.sessionNamed(CoreDataTests.name).saveContext()
SMSyncServer.session.resetFromError() { error in
Log.msg("SMSyncServer.session.resetFromError: Completed")
XCTAssert(error == nil)
// This isn't really true, but we need to fulfil them to clean up.
expectation.commitCompleteExpectation.fulfill()
complete?()
}
}
}
else {
self.commitCompleteCallbacks.append() { numberDeletions in
Log.msg("commitCompleteCallbacks: deleteFiles")
XCTAssert(numberDeletions == 1)
let fileAttr = SMSyncServer.session.localFileStatus(testFile.uuid)
XCTAssert(fileAttr != nil)
XCTAssert(fileAttr!.deleted!)
expectation.commitCompleteExpectation.fulfill()
complete?()
}
}
try! SMSyncServer.session.commit()
}
func downloadDeletion(testFile:TestFile, expectation:DownloadDeletionExpectations,
complete:(()->())?=nil) {
SMSyncServer.session.resetMetaData(forUUID: testFile.uuid, resetType: .Undelete)
self.shouldDoDeletions.append() { deletions, acknowledgement in
XCTAssert(deletions.count == 1)
let attr = deletions[0]
XCTAssert(attr.uuid.UUIDString == testFile.uuidString)
let fileAttr = SMSyncServer.session.localFileStatus(testFile.uuid)
XCTAssert(fileAttr != nil)
XCTAssert(fileAttr!.deleted!)
expectation.clientShouldDeleteFilesExpectation.fulfill()
acknowledgement()
}
self.idleCallbacks.append() {
expectation.idle.fulfill()
complete?()
}
SMSyncControl.session.nextSyncOperation()
}
// These two tests have no meaning. In order for a sharing user to sign in to the system, they must have some capabilities-- i.e., they must have at least Downloader capabilities. Thus, the following two tests cannot be carried out.
/*
func testThatFileDownloadByUnauthorizedSharingUserFails() {
}
func testThatDownloadDeletionByUnauthorizedSharingUserFails() {
}
*/
func startTestWithInvitationCode(invitationCode: String, testBody:()->()) {
self.waitUntilSyncServerUserSignin() {
self.idleCallbacks.append() {
testBody()
}
SMSyncServerUser.session.redeemSharingInvitation(invitationCode: invitationCode) { (linkedOwningUserId, error) in
XCTAssert(linkedOwningUserId != nil)
XCTAssert(error == nil)
}
}
self.waitForExpectations()
}
// ***** For the rest: Must be signed in as sharing user.
// 1) Startup the app in Xcode, not doing a test.
// 2) Sign out of owning user.
// 3) Sign in as Facebook user.
// 4) Then do the following:
func testThatFileDownloadByDownloadSharingUserWorks() {
// Redeem Download invitation first.
let downloadInvitation = 0
let invitationCode = self.downloadingInvitations[downloadInvitation].stringValue
let expectations = DownloadFileExpectations(fromTestClass: self)
self.extraServerResponseTime = 30
self.createUploadFiles(initial:false)
self.startTestWithInvitationCode(invitationCode) {
self.downloadFile(self.uploadFile1, expectations: expectations)
}
}
func testThatDownloadDeletionByDownloadSharingUserWorks() {
// Redeem Download invitation first.
let downloadInvitation = 1
let invitationCode = self.downloadingInvitations[downloadInvitation].stringValue
let expectations = DownloadDeletionExpectations(fromTestClass: self)
self.extraServerResponseTime = 30
self.createUploadFiles(initial:false)
self.startTestWithInvitationCode(invitationCode) {
self.downloadDeletion(self.uploadFile2, expectation: expectations)
}
}
func testThatDownloadDeletionByUploadSharingUserWorks() {
let uploadInvitation = 0
let invitationCode = self.uploadingInvitations[uploadInvitation].stringValue
let uploadExpectations = UploadFileExpectations(fromTestClass: self)
let uploadDeletionExpectations = UploadDeletionExpectations(fromTestClass: self)
let downloadDeletionExpectations = DownloadDeletionExpectations(fromTestClass: self)
self.startTestWithInvitationCode(invitationCode) {
let testFile = TestBasics.session.createTestFile(
"DownloadDeletionByUploadSharingUser")
self.uploadFile(testFile, expectations: uploadExpectations) {
self.uploadDeletion(testFile, expectation: uploadDeletionExpectations) {
self.downloadDeletion(testFile, expectation: downloadDeletionExpectations)
}
}
}
}
func testThatFileDownloadByUploadSharingUserWorks() {
let uploadInvitation = 1
// Redeem Upload invitation first.
let invitationCode = self.uploadingInvitations[uploadInvitation].stringValue
let uploadExpectations = UploadFileExpectations(fromTestClass: self)
let downloadExpectations = DownloadFileExpectations(fromTestClass: self)
self.startTestWithInvitationCode(invitationCode) {
let testFile = TestBasics.session.createTestFile(
"FileDownloadByUploadSharingUser")
self.uploadFile(testFile, expectations: uploadExpectations) {
self.downloadFile(testFile, expectations: downloadExpectations)
}
}
}
func testThatDownloadDeletionByAdminSharingUserWorks() {
let adminInvitation = 0
// Redeem Admin invitation first.
let invitationCode = self.adminInvitations[adminInvitation].stringValue
let uploadExpectations = UploadFileExpectations(fromTestClass: self)
let uploadDeletionExpectations = UploadDeletionExpectations(fromTestClass: self)
let downloadDeletionExpectations = DownloadDeletionExpectations(fromTestClass: self)
self.startTestWithInvitationCode(invitationCode) {
let testFile = TestBasics.session.createTestFile(
"DownloadDeletionByAdminSharingUser")
self.uploadFile(testFile, expectations: uploadExpectations) {
self.uploadDeletion(testFile, expectation: uploadDeletionExpectations) {
self.downloadDeletion(testFile, expectation: downloadDeletionExpectations)
}
}
}
}
func testThatFileDownloadByAdminSharingUserWorks() {
let adminInvitation = 1
// Redeem Admin invitation first.
let invitationCode = self.adminInvitations[adminInvitation].stringValue
let uploadExpectations = UploadFileExpectations(fromTestClass: self)
let downloadExpectations = DownloadFileExpectations(fromTestClass: self)
self.startTestWithInvitationCode(invitationCode) {
let testFile = TestBasics.session.createTestFile(
"FileDownloadByAdminSharingUser")
self.uploadFile(testFile, expectations: uploadExpectations) {
self.downloadFile(testFile, expectations: downloadExpectations)
}
}
}
//MARK: Upload tests
func testThatFileUploadByDownloadingSharingUserFails() {
// Redeem Download invitation first.
let downloadInvitation = 2
let invitationCode = self.downloadingInvitations[downloadInvitation].stringValue
let expectations = UploadFileExpectations(fromTestClass: self)
self.extraServerResponseTime = 60
let testFile = TestBasics.session.createTestFile("FileUploadByDownloadingSharingUser")
self.startTestWithInvitationCode(invitationCode) {
self.uploadFile(testFile, expectations: expectations, failureExpected: true)
}
}
func testThatUploadDeletionByDownloadingSharingUserFails() {
// Redeem Download invitation first.
let downloadInvitation = 3
let invitationCode = self.downloadingInvitations[downloadInvitation].stringValue
let uploadDeletionExpectations = UploadDeletionExpectations(fromTestClass: self)
self.createUploadFiles(initial:false)
// The retries upon upload deletion failure take a while to finish.
self.extraServerResponseTime = 120
self.startTestWithInvitationCode(invitationCode) {
self.uploadDeletion(self.uploadFile3, expectation: uploadDeletionExpectations, failureExpected: true) {
// Now need to redeem an uploader invitation, and check for downloads becasue there is still a download pending for self.uploadFile3.
}
}
}
func testThatFileUploadByUploadSharingUserWorks() {
let uploadInvitation = 2
// Redeem Upload invitation first.
let invitationCode = self.uploadingInvitations[uploadInvitation].stringValue
let uploadExpectations = UploadFileExpectations(fromTestClass: self)
self.startTestWithInvitationCode(invitationCode) {
let testFile = TestBasics.session.createTestFile(
"FileUploadByUploadSharingUser")
self.uploadFile(testFile, expectations: uploadExpectations)
}
}
func testThatUploadDeletionByUploadSharingUserWorks() {
let uploadInvitation = 3
// Redeem Upload invitation first.
let invitationCode = self.uploadingInvitations[uploadInvitation].stringValue
let uploadExpectations = UploadFileExpectations(fromTestClass: self)
let uploadDeletionExpectations = UploadDeletionExpectations(fromTestClass: self)
self.startTestWithInvitationCode(invitationCode) {
let testFile = TestBasics.session.createTestFile(
"UploadDeletionByUploadSharingUser")
self.uploadFile(testFile, expectations: uploadExpectations) {
self.uploadDeletion(testFile, expectation: uploadDeletionExpectations)
}
}
}
func testThatFileUploadByAdminSharingUserWorks() {
let adminInvitation = 2
// Redeem Admin invitation first.
let invitationCode = self.adminInvitations[adminInvitation].stringValue
let uploadExpectations = UploadFileExpectations(fromTestClass: self)
self.startTestWithInvitationCode(invitationCode) {
let testFile = TestBasics.session.createTestFile(
"FileUploadByAdminSharingUser")
self.uploadFile(testFile, expectations: uploadExpectations)
}
}
func testThatUploadDeletionByAdminSharingUserWorks() {
let adminInvitation = 3
// Redeem Admin invitation first.
let invitationCode = self.adminInvitations[adminInvitation].stringValue
let uploadExpectations = UploadFileExpectations(fromTestClass: self)
let uploadDeletionExpectations = UploadDeletionExpectations(fromTestClass: self)
self.startTestWithInvitationCode(invitationCode) {
let testFile = TestBasics.session.createTestFile(
"UploadDeletionByAdminSharingUser")
self.uploadFile(testFile, expectations: uploadExpectations) {
self.uploadDeletion(testFile, expectation: uploadDeletionExpectations)
}
}
}
//MARK: Invitation tests
func doInvitation(invitationCode:String, failureExpected:Bool) {
let expectation = self.expectationWithDescription("Invitation Test")
self.startTestWithInvitationCode(invitationCode) {
SMServerAPI.session.createSharingInvitation(sharingType: SMSharingType.Admin.rawValue, completion: { (invitationCode, apiResult) in
if failureExpected {
XCTAssert(apiResult.error != nil)
XCTAssert(invitationCode == nil)
expectation.fulfill()
}
else {
XCTAssert(apiResult.error == nil)
XCTAssert(invitationCode != nil)
expectation.fulfill()
}
})
}
}
func testThatInvitationByDownloadingSharingUserFails() {
// Redeem Download invitation first.
let downloadInvitation = 4
let invitationCode = self.downloadingInvitations[downloadInvitation].stringValue
self.doInvitation(invitationCode, failureExpected: true)
}
func testThatInvitationByUploadSharingUserFails() {
let uploadInvitation = 4
// Redeem Upload invitation first.
let invitationCode = self.uploadingInvitations[uploadInvitation].stringValue
self.doInvitation(invitationCode, failureExpected: true)
}
func testThatInvitationByAdminSharingUserWorks() {
let adminInvitation = 4
// Redeem Admin invitation first.
let invitationCode = self.adminInvitations[adminInvitation].stringValue
self.doInvitation(invitationCode, failureExpected: false)
}
}
|
gpl-3.0
|
f271e245ee8421f12b565d79c9ed38ed
| 40.74727 | 236 | 0.641181 | 5.741257 | false | true | false | false |
curia007/Utilities
|
src/Utilities/Utilities/coreData/ModelProcessor.swift
|
1
|
1990
|
//
// ModelProcessor.swift
// Utilities
//
// Created by Carmelo I. Uria on 10/20/15.
// Copyright © 2015 Carmelo I. Uria. All rights reserved.
//
import Foundation
import CoreData
enum ModelProcessorError: ErrorType {
case Bad
case Worse
case DeleteError
}
public class ModelProcessor
{
public init()
{
}
public func retrieve(table: String, managedObjectContext: NSManagedObjectContext) throws -> [AnyObject]
{
let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: table)
var entities: [AnyObject] = []
entities = try managedObjectContext.executeFetchRequest(fetchRequest)
return entities
}
public func insert(entries: [String : AnyObject], table: String, managedObjectContext: NSManagedObjectContext)
{
let managedObject: NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName(table, inManagedObjectContext: managedObjectContext)
for (key, value) in entries
{
debugPrint("\(__FUNCTION__): key = \(key): value = \(value)")
managedObject.setValue(value, forKey: key)
}
}
public func update(entries: [String : AnyObject], entity: NSManagedObject, managedObjectContext: NSManagedObjectContext) throws
{
if (entity.fault == true)
{
let exception: ModelProcessorException = ModelProcessorException(name: "Fault Exception", reason: "Entity is a fault", userInfo: nil)
exception.raise()
}
for (key, value) in entries
{
debugPrint("\(__FUNCTION__): key = \(key): value = \(value)")
}
}
public func delete(entity: NSManagedObject, managedObjectContext: NSManagedObjectContext) throws
{
if (entity.fault == true)
{
throw ModelProcessorError.DeleteError
}
managedObjectContext.deleteObject(entity)
}
}
|
apache-2.0
|
3ec60bf546f877b037faa06d0e39f318
| 26.246575 | 149 | 0.627954 | 5.126289 | false | false | false | false |
crspybits/SMSyncServer
|
iOS/SharedNotes/Code/EditNoteViewController.swift
|
1
|
8351
|
//
// EditNoteViewController.swift
// SharedNotes
//
// Created by Christopher Prince on 5/4/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
import Foundation
import UIKit
import SMCoreLib
import SMSyncServer
public class EditNoteImageTextView : SMImageTextView {
var didChange = false
var note:Note?
var acquireImage:SMAcquireImage?
weak var parentViewController:UIViewController!
// To deal with a funky interaction of pushing to the large image VC.
var allowShouldBeginEditing = true
func commitChanges() {
if SMSyncServerUser.session.signedIn {
// We should not get an error in the commit now. But might on the setJSONData.
do {
try self.note!.setJSONData(self.contentsToData()!)
try SMSyncServer.session.commit()
} catch (let error) {
Misc.showAlert(fromParentViewController: self.parentViewController, title: "Error on commit!", message: "\(error)")
return
}
self.didChange = false
}
else {
Misc.showAlert(fromParentViewController: self.parentViewController, title: "You have not signed in!", message: "Please sign in.")
}
}
// MARK: UITextView delegate methods; SMImageTextView declares delegate conformance and assigns delegate property.
// Using this for updates based on text-only changes (not for images).
func textViewDidEndEditing(textView: UITextView) {
// Only update if the text has changed, because the update will generate an upload.
// ALSO: We get a call to textViewDidEndEditing when we insert an image into the text view, i.e., when we navigate away to the image picker. Don't want the body of this if executed then.
if self.didChange && !self.acquireImage!.acquiringImage {
self.commitChanges()
}
}
func textViewDidChange(textView: UITextView) {
self.didChange = true
}
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
return self.allowShouldBeginEditing
}
}
class EditNoteViewController : UIViewController {
// Set this before pushing to view controller-- gives the note being edited.
var note:Note?
private var acquireImage:SMAcquireImage!
@IBOutlet weak var imageTextView: EditNoteImageTextView!
private var initialLoadOfJSONData = false
private var addImageBarButton:UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
self.addImageBarButton = UIBarButtonItem(title: "Add Image", style: .Plain, target: self, action: #selector(addImageAction))
// I want to set the font size of the text view in relation to the size of the screen real-estate we have.
let baselineMinSize:CGFloat = 500.0
let baselineFontSize:CGFloat = 30.0
let minSize = min(self.view.frameWidth, self.view.frameHeight)
let fontSize = (minSize/baselineMinSize)*baselineFontSize
self.imageTextView.font = UIFont.systemFontOfSize(fontSize)
let toolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.frameWidth, 50))
toolbar.barStyle = UIBarStyle.Default
toolbar.items = [
UIBarButtonItem(title: "Close", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(dismissKeyboardAction)),
UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil),
self.addImageBarButton
]
toolbar.sizeToFit()
self.imageTextView.inputAccessoryView = toolbar
Log.msg("self.imageTextView: \(self.imageTextView)")
self.imageTextView.imageDelegate = self
self.acquireImage = SMAcquireImage(withParentViewController: self)
self.acquireImage.delegate = self
self.imageTextView.acquireImage = self.acquireImage
self.imageTextView.parentViewController = self
}
@objc private func dismissKeyboardAction() {
self.imageTextView.resignFirstResponder()
}
@objc private func addImageAction() {
self.acquireImage.showAlert(fromBarButton: self.addImageBarButton)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.imageTextView.note = self.note
self.imageTextView.allowShouldBeginEditing = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Pushing to the image picker causes viewDidAppear to be called. Don't want to load contents again when popping back from that.
if !self.initialLoadOfJSONData {
self.initialLoadOfJSONData = true
// Putting this in viewDidAppear because having problems getting images to resize if I put it in viewWillAppear.
self.imageTextView.loadContents(fromJSONData: self.note!.jsonData)
}
}
}
extension EditNoteViewController : SMImageTextViewDelegate {
// User has requested deletion of an image.
func smImageTextView(imageTextView:SMImageTextView, imageWasDeleted imageId:NSUUID?) {
Log.msg("UUID of image: \(imageId)")
if let noteImage = NoteImage.fetch(withUUID: imageId!) {
// Since this is a user request for a deletion, update the server.
do {
try noteImage.removeObject(andUpdateServer: true)
} catch (let error) {
Misc.showAlert(fromParentViewController: self, title: "Error removing image!", message: "\(error)")
}
// TODO: Does this, as a side effect, cause textViewDidEndEditing to be called. I.e., does the updated note text get uploaded?
}
}
// Fetch an image from a file given a UUID
func smImageTextView(imageTextView: SMImageTextView, imageForUUID uuid: NSUUID) -> UIImage? {
if let noteImage = NoteImage.fetch(withUUID: uuid),
let image = UIImage(contentsOfFile: noteImage.fileURL!.path!) {
return image
}
Log.error("Could not fetch image for uuid: \(uuid)")
return nil
}
func smImageTextView(imageTextView: SMImageTextView, imageWasTapped imageId: NSUUID?) {
Log.msg("Tap: \(imageId)")
// There is an odd UI effect where I get the keyboard toolbar being black when I pop back from the large image VC. Deal with this in two ways:
// 1) For tapping on the image when the keyboard is *not* present initially.
self.imageTextView.allowShouldBeginEditing = false
// 2) For when the keyboard is present *prior* to the tap.
imageTextView.resignFirstResponder()
if let largeImageVC = self.storyboard?.instantiateViewControllerWithIdentifier(
"LargeImageViewController") as? LargeImageViewController {
largeImageVC.imageId = imageId
self.navigationController!.pushViewController(largeImageVC, animated: true)
}
}
}
extension EditNoteViewController : SMAcquireImageDelegate {
func smAcquireImageURLForNewImage(acquireImage:SMAcquireImage) -> SMRelativeLocalURL {
return FileExtras().newURLForImage()
}
func smAcquireImage(acquireImage:SMAcquireImage, newImageURL: SMRelativeLocalURL) {
Log.msg("newImageURL \(newImageURL); \(newImageURL.path!)")
if let image = UIImage(contentsOfFile: newImageURL.path!) {
var newNoteImage:NoteImage?
do {
try newNoteImage = (NoteImage.newObjectAndMakeUUID(withURL: newImageURL, ownedBy: self.note!, makeUUIDAndUpload: true) as! NoteImage)
} catch (let error) {
Misc.showAlert(fromParentViewController: self, title: "Error adding image!", message: "\(error)")
}
if newNoteImage != nil {
self.imageTextView.insertImageAtCursorLocation(image, imageId: NSUUID(UUIDString: newNoteImage!.uuid!))
self.imageTextView.commitChanges()
}
}
else {
Log.error("Error creating image from file: \(newImageURL)")
}
}
}
|
gpl-3.0
|
5828971b895cd56b748920ffdd2b8e3d
| 39.931373 | 194 | 0.653653 | 4.976162 | false | false | false | false |
apple/swift-corelibs-foundation
|
Sources/Foundation/DateInterval.swift
|
1
|
8507
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_implementationOnly import CoreFoundation
/// DateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. DateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date.
public struct DateInterval : ReferenceConvertible, Comparable, Hashable {
public typealias ReferenceType = NSDateInterval
/// The start date.
public var start: Date
/// The end date.
///
/// - precondition: `end >= start`
public var end: Date {
get {
return start + duration
}
set {
precondition(newValue >= start, "Reverse intervals are not allowed")
duration = newValue.timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate
}
}
/// The duration.
///
/// - precondition: `duration >= 0`
public var duration: TimeInterval {
willSet {
precondition(newValue >= 0, "Negative durations are not allowed")
}
}
/// Initializes a `DateInterval` with start and end dates set to the current date and the duration set to `0`.
public init() {
let d = Date()
start = d
duration = 0
}
/// Initialize a `DateInterval` with the specified start and end date.
///
/// - precondition: `end >= start`
public init(start: Date, end: Date) {
precondition(end >= start, "Reverse intervals are not allowed")
self.start = start
duration = end.timeIntervalSince(start)
}
/// Initialize a `DateInterval` with the specified start date and duration.
///
/// - precondition: `duration >= 0`
public init(start: Date, duration: TimeInterval) {
precondition(duration >= 0, "Negative durations are not allowed")
self.start = start
self.duration = duration
}
/**
Compare two DateIntervals.
This method prioritizes ordering by start date. If the start dates are equal, then it will order by duration.
e.g. Given intervals a and b
```
a. |-----|
b. |-----|
```
`a.compare(b)` would return `.OrderedAscending` because a's start date is earlier in time than b's start date.
In the event that the start dates are equal, the compare method will attempt to order by duration.
e.g. Given intervals c and d
```
c. |-----|
d. |---|
```
`c.compare(d)` would result in `.OrderedDescending` because c is longer than d.
If both the start dates and the durations are equal, then the intervals are considered equal and `.OrderedSame` is returned as the result.
*/
public func compare(_ dateInterval: DateInterval) -> ComparisonResult {
let result = start.compare(dateInterval.start)
if result == .orderedSame {
if self.duration < dateInterval.duration { return .orderedAscending }
if self.duration > dateInterval.duration { return .orderedDescending }
return .orderedSame
}
return result
}
/// Returns `true` if `self` intersects the `dateInterval`.
public func intersects(_ dateInterval: DateInterval) -> Bool {
return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(start) || dateInterval.contains(end)
}
/// Returns a DateInterval that represents the interval where the given date interval and the current instance intersect.
///
/// In the event that there is no intersection, the method returns nil.
public func intersection(with dateInterval: DateInterval) -> DateInterval? {
if !intersects(dateInterval) {
return nil
}
if self == dateInterval {
return self
}
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalForSelfEnd = end.timeIntervalSinceReferenceDate
let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate
let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate
let resultStartDate : Date
if timeIntervalForGivenStart >= timeIntervalForSelfStart {
resultStartDate = dateInterval.start
} else {
// self starts after given
resultStartDate = start
}
let resultEndDate : Date
if timeIntervalForGivenEnd >= timeIntervalForSelfEnd {
resultEndDate = end
} else {
// given ends before self
resultEndDate = dateInterval.end
}
return DateInterval(start: resultStartDate, end: resultEndDate)
}
/// Returns `true` if `self` contains `date`.
public func contains(_ date: Date) -> Bool {
return (start...end).contains(date)
}
public func hash(into hasher: inout Hasher) {
hasher.combine(start)
hasher.combine(duration)
}
public static func ==(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.start == rhs.start && lhs.duration == rhs.duration
}
public static func <(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
}
extension DateInterval : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "(Start Date) \(start) + (Duration) \(duration) seconds = (End Date) \(end)"
}
public var debugDescription: String {
return description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "start", value: start))
c.append((label: "end", value: end))
c.append((label: "duration", value: duration))
return Mirror(self, children: c, displayStyle: .struct)
}
}
extension DateInterval : _ObjectiveCBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSDateInterval.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDateInterval {
return NSDateInterval(start: start, duration: duration)
}
public static func _forceBridgeFromObjectiveC(_ dateInterval: NSDateInterval, result: inout DateInterval?) {
if !_conditionallyBridgeFromObjectiveC(dateInterval, result: &result) {
fatalError("Unable to bridge \(NSDateInterval.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ dateInterval : NSDateInterval, result: inout DateInterval?) -> Bool {
result = DateInterval(start: dateInterval.startDate, duration: dateInterval.duration)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDateInterval?) -> DateInterval {
var result: DateInterval? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension DateInterval : Codable {
enum CodingKeys: String, CodingKey {
case start
case duration
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let start = try container.decode(Date.self, forKey: .start)
let duration = try container.decode(TimeInterval.self, forKey: .duration)
self.init(start: start, duration: duration)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.start, forKey: .start)
try container.encode(self.duration, forKey: .duration)
}
}
|
apache-2.0
|
2561806ae538ebf1bb9ed21a9e47592e
| 36.148472 | 327 | 0.631127 | 5.20943 | false | false | false | false |
peterlafferty/LuasLife
|
LuasLife/RouteTableViewController.swift
|
1
|
2624
|
//
// RouteTableViewController.swift
// LuasLife
//
// Created by Peter Lafferty on 13/07/2016.
// Copyright © 2016 Peter Lafferty. All rights reserved.
//
import UIKit
import LuasLifeKit
class RouteTableViewController: UITableViewController {
var dataSource = RouteDataSource()
var line = Line(id: 1, name: "Green")
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = dataSource
self.tableView.delegate = dataSource
dataSource.load(line) {
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}
//showRoutesSegue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showStopsSegue" {
if let indexPath = tableView.indexPathForSelectedRow {
if let vc = segue.destination as? StopPickerViewController {
vc.route = dataSource[indexPath]
}
}
}
}
}
class RouteDataSource: NSObject {
var routes = [Route]()
let reuseIdentifier = "RouteCell"
func load(_ line: Line, completionHandler: @escaping (Void) -> (Void)) {
let request = GetRoutesRequest(line: line) { (result) -> Void in
let error: Error?
if case let .error(e) = result {
error = e
} else {
error = nil
}
if case let .success(r) = result {
self.routes = r
} else {
self.routes = [Route]()
}
print(error ?? "no error")
completionHandler()
}
request.start()
}
subscript(indexPath: IndexPath) -> Route {
get {
return routes[indexPath.row]
}
}
}
extension RouteDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return routes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.textLabel?.text = routes[indexPath.row].origin.name + " to " + routes[indexPath.row].destination.name
print("\(indexPath.row ) " + routes[indexPath.row].origin.name + " " + routes[indexPath.row].destination.name
)
return cell
}
}
extension RouteDataSource: UITableViewDelegate {
}
|
mit
|
f832bda7ad70e19f23a86fc8b3c67720
| 25.23 | 117 | 0.592451 | 4.717626 | false | false | false | false |
adelinofaria/Buildasaur
|
Buildasaur/StatusSyncerViewController.swift
|
2
|
11051
|
//
// StatusSyncerViewController.swift
// Buildasaur
//
// Created by Honza Dvorsky on 08/03/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import AppKit
import BuildaUtils
import XcodeServerSDK
class StatusSyncerViewController: StatusViewController, SyncerDelegate {
@IBOutlet weak var statusTextField: NSTextField!
@IBOutlet weak var startStopButton: NSButton!
@IBOutlet weak var statusActivityIndicator: NSProgressIndicator!
@IBOutlet weak var syncIntervalStepper: NSStepper!
@IBOutlet weak var syncIntervalTextField: NSTextField!
@IBOutlet weak var lttmToggle: NSButton!
@IBOutlet weak var postStatusCommentsToggle: NSButton!
var isSyncing: Bool {
set {
if let syncer = self.syncer() {
syncer.active = newValue
}
self.delegate.getProjectStatusViewController().editingAllowed = !newValue
self.delegate.getServerStatusViewController().editingAllowed = !newValue
}
get {
if let syncer = self.syncer() {
return syncer.active
}
return false
}
}
func syncer() -> HDGitHubXCBotSyncer? {
if let syncer = self.storageManager.syncers.first {
if syncer.delegate == nil {
syncer.delegate = self
if syncer.active {
self.syncerBecameActive(syncer)
} else {
self.syncerStopped(syncer)
}
}
return syncer
}
return nil
}
func syncerBecameActive(syncer: Syncer) {
self.report("Syncer is now active...")
}
func syncerStopped(syncer: Syncer) {
self.report("Syncer is stopped")
}
func syncerDidStartSyncing(syncer: Syncer) {
var messages = [
"Syncing in progress..."
]
if let lastStartedSync = self.syncer()?.lastSyncStartDate {
let lastSyncString = "Started sync at \(lastStartedSync)"
messages.append(lastSyncString)
}
self.reportMultiple(messages)
}
func syncerDidFinishSyncing(syncer: Syncer) {
var messages = [
"Syncer is Idle... Waiting for the next sync...",
]
if let ourSyncer = syncer as? HDGitHubXCBotSyncer {
//error?
if let error = ourSyncer.lastSyncError {
messages.insert("Last sync failed with error \(error.localizedDescription)", atIndex: 0)
}
//info reports
let reports = ourSyncer.reports
let reportsArray = reports.keys.map({ "\($0): \(reports[$0]!)" })
messages += reportsArray
}
self.reportMultiple(messages)
}
func syncerEncounteredError(syncer: Syncer, error: NSError) {
self.report("Error: \(error.localizedDescription)")
}
func report(string: String) {
self.reportMultiple([string])
}
func reportMultiple(strings: [String]) {
var itemsToReport = [String]()
if let lastFinishedSync = self.syncer()?.lastSuccessfulSyncFinishedDate {
let lastSyncString = "Last successful sync at \(lastFinishedSync)"
itemsToReport.append(lastSyncString)
}
strings.map { itemsToReport.append($0) }
self.statusTextField.stringValue = "\n".join(itemsToReport)
}
override func viewDidLoad() {
super.viewDidLoad()
self.statusTextField.stringValue = "-"
}
override func viewDidAppear() {
super.viewDidAppear()
if let syncer = self.syncer() {
Log.info("We have a syncer \(syncer)")
}
}
override func reloadStatus() {
self.startStopButton.title = self.isSyncing ? "Stop" : "Start"
self.syncIntervalStepper.enabled = !self.isSyncing
self.lttmToggle.enabled = !self.isSyncing
self.postStatusCommentsToggle.enabled = !self.isSyncing
if self.isSyncing {
self.statusActivityIndicator.startAnimation(nil)
} else {
self.statusActivityIndicator.stopAnimation(nil)
}
if let syncer = self.syncer() {
self.updateIntervalFromUIToValue(syncer.syncInterval)
self.lttmToggle.state = syncer.waitForLttm ? NSOnState : NSOffState
self.postStatusCommentsToggle.state = syncer.postStatusComments ? NSOnState : NSOffState
} else {
self.updateIntervalFromUIToValue(15) //default
self.lttmToggle.state = NSOnState //default is true
self.postStatusCommentsToggle.state = NSOnState //default is true
}
}
func updateIntervalFromUIToValue(value: NSTimeInterval) {
self.syncIntervalTextField.doubleValue = value
self.syncIntervalStepper.doubleValue = value
}
@IBAction func syncIntervalStepperValueChanged(sender: AnyObject) {
if let stepper = sender as? NSStepper {
let value = stepper.doubleValue
self.updateIntervalFromUIToValue(value)
}
}
@IBAction func startStopButtonTapped(sender: AnyObject) {
self.toggleActiveWithCompletion { () -> () in
//
}
}
@IBAction func branchWatchingTapped(sender: AnyObject) {
if let syncer = self.syncer() {
self.performSegueWithIdentifier("showBranchWatching", sender: self)
} else {
UIUtils.showAlertWithText("Syncer must be created first. Click 'Start' and try again.")
}
}
@IBAction func manualBotManagementTapped(sender: AnyObject) {
if let syncer = self.syncer() {
self.performSegueWithIdentifier("showManual", sender: self)
} else {
UIUtils.showAlertWithText("Syncer must be created first. Click 'Start' and try again.")
}
}
@IBAction func helpLttmButtonTapped(sender: AnyObject) {
let urlString = "https://github.com/czechboy0/Buildasaur/blob/master/README.md#the-lttm-barrier"
if let url = NSURL(string: urlString) {
NSWorkspace.sharedWorkspace().openURL(url)
}
}
@IBAction func helpPostStatusCommentsButtonTapped(sender: AnyObject) {
let urlString = "https://github.com/czechboy0/Buildasaur/blob/master/README.md#posting-status-comments"
if let url = NSURL(string: urlString) {
NSWorkspace.sharedWorkspace().openURL(url)
}
}
override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
if let manual = segue.destinationController as? ManualBotManagementViewController {
manual.syncer = self.syncer()!
}
if let branchWatching = segue.destinationController as? BranchWatchingViewController {
branchWatching.syncer = self.syncer()!
}
}
func startSyncing() {
//create a syncer, delete the old one and kick it off
let oldWatchedBranchNames: [String]
if let syncer = self.syncer() {
self.storageManager.removeSyncer(syncer)
oldWatchedBranchNames = syncer.watchedBranchNames
} else {
oldWatchedBranchNames = []
}
let waitForLttm = self.lttmToggle.state == NSOnState
let postStatusComments = self.postStatusCommentsToggle.state == NSOnState
let syncInterval = self.syncIntervalTextField.doubleValue
let project = self.delegate.getProjectStatusViewController().project()!
let serverConfig = self.delegate.getServerStatusViewController().serverConfig()!
if let syncer = self.storageManager.addSyncer(
syncInterval,
waitForLttm: waitForLttm,
postStatusComments: postStatusComments,
project: project,
serverConfig: serverConfig,
watchedBranchNames: oldWatchedBranchNames) {
syncer.active = true
self.isSyncing = true
self.reloadStatus()
} else {
UIUtils.showAlertWithText("Couldn't start syncer, please make sure the sync interval is > 0 seconds.")
}
self.storageManager.saveSyncers()
}
func toggleActiveWithCompletion(completion: () -> ()) {
if self.isSyncing {
//stop syncing
self.isSyncing = false
self.reloadStatus()
} else if self.delegate.getProjectStatusViewController().editing ||
self.delegate.getServerStatusViewController().editing {
UIUtils.showAlertWithText("Please save your configurations above by clicking Done")
} else {
let group = dispatch_group_create()
//validate - check availability for both sources - github and xcodeserver - only kick off if both work
//gather data from the UI + storageManager and try to create a syncer with it
var projectReady: Bool = false
dispatch_group_enter(group)
self.delegate.getProjectStatusViewController().checkAvailability({ (status, done) -> () in
if done {
switch status {
case .Succeeded:
projectReady = true
default:
projectReady = false
}
dispatch_group_leave(group)
}
})
var serverReady: Bool = false
dispatch_group_enter(group)
self.delegate.getServerStatusViewController().checkAvailability({ (status, done) -> () in
if done {
switch status {
case .Succeeded:
serverReady = true
default:
serverReady = false
}
dispatch_group_leave(group)
}
})
dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
let allReady = projectReady && serverReady
if allReady {
self.startSyncing()
} else {
let brokenPart = projectReady ? "Xcode Server" : "Xcode Project"
let message = "Couldn't start syncing, please fix your \(brokenPart) settings and try again."
UIUtils.showAlertWithText(message)
}
})
}
}
}
|
mit
|
bb8c3421113664398d2a260e32198e4d
| 32.589666 | 114 | 0.567098 | 5.553266 | false | false | false | false |
roambotics/swift
|
test/IRGen/fixed_layout_class.swift
|
2
|
8613
|
// RUN: %empty-directory(%t)
// RUN: %{python} %utils/chex.py < %s > %t/class_resilience.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/fixed_layout_class.swiftmodule -module-name=fixed_layout_class -I %t %S/../Inputs/fixed_layout_class.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution %t/class_resilience.swift | %FileCheck %t/class_resilience.swift --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-runtime -DINT=i%target-ptrsize
// RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution -O %t/class_resilience.swift
// This tests @_fixed_layout classes in resilient modules.
import fixed_layout_class
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience20useRootClassPropertyyy013fixed_layout_A0026OutsideParentWithResilientF0CF"(%T18fixed_layout_class34OutsideParentWithResilientPropertyC* %0)
public func useRootClassProperty(_ o: OutsideParentWithResilientProperty) {
// CHECK: getelementptr inbounds %T18fixed_layout_class34OutsideParentWithResilientPropertyC, %T18fixed_layout_class34OutsideParentWithResilientPropertyC* %0, i32 0, i32 1
_ = o.p
// CHECK: load [[INT]], [[INT]]* @"$s18fixed_layout_class34OutsideParentWithResilientPropertyC1s16resilient_struct4SizeVvpWvd"
_ = o.s
// CHECK: load [[INT]], [[INT]]* @"$s18fixed_layout_class34OutsideParentWithResilientPropertyC5colors5Int32VvpWvd"
_ = o.color
// CHECK: ret void
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience19useSubclassPropertyyy013fixed_layout_A012OutsideChildCF"(%T18fixed_layout_class12OutsideChildC* %0)
public func useSubclassProperty(_ o: OutsideChild) {
// CHECK: getelementptr inbounds %T18fixed_layout_class13OutsideParentC, %T18fixed_layout_class13OutsideParentC* %4, i32 0, i32 1
_ = o.property
// CHECK: getelementptr inbounds %T18fixed_layout_class12OutsideChildC, %T18fixed_layout_class12OutsideChildC* %0, i32 0, i32 2
_ = o.childProperty
// CHECK: ret void
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience27useGenericRootClassPropertyyy013fixed_layout_A00D13OutsideParentCyxGlF"(%T18fixed_layout_class20GenericOutsideParentC* %0)
public func useGenericRootClassProperty<A>(_ o: GenericOutsideParent<A>) {
// -- we load the base offset twice, first to get the generic parameter out and
// then for the property itself.
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ({ [[INT]], i32, i32 }, { [[INT]], i32, i32 }* @"$s18fixed_layout_class20GenericOutsideParentCMo", i32 0, i32 0)
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %T18fixed_layout_class20GenericOutsideParentC* %0 to %swift.type**
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]]
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ({ [[INT]], i32, i32 }, { [[INT]], i32, i32 }* @"$s18fixed_layout_class20GenericOutsideParentCMo", i32 0, i32 0)
// CHECK: [[FIELD_OFFSET_OFFSET:%.*]] = add [[INT]] [[BASE]], {{4|8}}
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*
// CHECK: [[FIELD_OFFSET_ADDR:%.*]] = getelementptr inbounds i8, i8* [[METADATA_ADDR]], [[INT]] [[FIELD_OFFSET_OFFSET]]
// CHECK: [[FIELD_OFFSET_PTR:%.*]] = bitcast i8* [[FIELD_OFFSET_ADDR]] to [[INT]]*
// CHECK: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
_ = o.property
// CHECK: ret void
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience27useGenericRootClassPropertyyy013fixed_layout_A00D13OutsideParentCySiGF"(%T18fixed_layout_class20GenericOutsideParentCySiG* %0)
public func useGenericRootClassProperty(_ o: GenericOutsideParent<Int>) {
// CHECK: getelementptr inbounds %T18fixed_layout_class20GenericOutsideParentCySiG, %T18fixed_layout_class20GenericOutsideParentCySiG* %0, i32 0, i32 1
_ = o.property
// CHECK: ret void
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience26useGenericSubclassPropertyyy013fixed_layout_A00D12OutsideChildCyxGlF"(%T18fixed_layout_class19GenericOutsideChildC* %0)
public func useGenericSubclassProperty<A>(_ o: GenericOutsideChild<A>) {
// -- we load the base offset twice, first to get the generic parameter out and
// then for the property itself.
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ({ [[INT]], i32, i32 }, { [[INT]], i32, i32 }* @"$s18fixed_layout_class19GenericOutsideChildCMo", i32 0, i32 0)
// CHECK: [[UPCAST:%.*]] = bitcast %T18fixed_layout_class19GenericOutsideChildC* %0 to %T18fixed_layout_class20GenericOutsideParentC*
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %T18fixed_layout_class20GenericOutsideParentC* [[UPCAST]] to %swift.type**
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]]
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ({ [[INT]], i32, i32 }, { [[INT]], i32, i32 }* @"$s18fixed_layout_class20GenericOutsideParentCMo", i32 0, i32 0)
// CHECK: [[FIELD_OFFSET_OFFSET:%.*]] = add [[INT]] [[BASE]], {{4|8}}
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*
// CHECK: [[FIELD_OFFSET_ADDR:%.*]] = getelementptr inbounds i8, i8* [[METADATA_ADDR]], [[INT]] [[FIELD_OFFSET_OFFSET]]
// CHECK: [[FIELD_OFFSET_PTR:%.*]] = bitcast i8* [[FIELD_OFFSET_ADDR]] to [[INT]]*
// CHECK: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
_ = o.property
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %T18fixed_layout_class19GenericOutsideChildC* %0 to %swift.type**
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]]
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ({ [[INT]], i32, i32 }, { [[INT]], i32, i32 }* @"$s18fixed_layout_class19GenericOutsideChildCMo", i32 0, i32 0)
// CHECK: [[FIELD_OFFSET_OFFSET:%.*]] = add [[INT]] [[BASE]], {{4|8}}
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*
// CHECK: [[FIELD_OFFSET_ADDR:%.*]] = getelementptr inbounds i8, i8* [[METADATA_ADDR]], [[INT]] [[FIELD_OFFSET_OFFSET]]
// CHECK: [[FIELD_OFFSET_PTR:%.*]] = bitcast i8* [[FIELD_OFFSET_ADDR]] to [[INT]]*
// CHECK: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
_ = o.childProperty
// CHECK: ret void
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience26useGenericSubclassPropertyyy013fixed_layout_A00D12OutsideChildCySiGF"(%T18fixed_layout_class19GenericOutsideChildCySiG* %0)
public func useGenericSubclassProperty(_ o: GenericOutsideChild<Int>) {
// CHECK: [[UPCAST:%.*]] = bitcast %T18fixed_layout_class19GenericOutsideChildCySiG* %0 to %T18fixed_layout_class20GenericOutsideParentCySiG*
// CHECK: getelementptr inbounds %T18fixed_layout_class20GenericOutsideParentCySiG, %T18fixed_layout_class20GenericOutsideParentCySiG* [[UPCAST]], i32 0, i32 1
_ = o.property
// CHECK: getelementptr inbounds %T18fixed_layout_class19GenericOutsideChildCySiG, %T18fixed_layout_class19GenericOutsideChildCySiG* %0, i32 0, i32 2
_ = o.childProperty
// CHECK: ret void
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience17callVirtualMethodyy013fixed_layout_A013OutsideParentCF"(%T18fixed_layout_class13OutsideParentC* %0)
public func callVirtualMethod(_ o: OutsideParent) {
// Note: virtual method calls still use dispatch thunks
// CHECK: call swiftcc void @"$s18fixed_layout_class13OutsideParentC6methodyyFTj"
_ = o.method()
// CHECK: ret void
}
@_fixed_layout open class MyChildOfOutsideParent : OutsideParent {
public func newMethod() {}
}
// Make sure we emit the dispatch thunk:
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience22MyChildOfOutsideParentC9newMethodyyFTj"(%T16class_resilience22MyChildOfOutsideParentC* swiftself %0)
|
apache-2.0
|
dbd8608f26a52383b6e03e1a3c48c0a3
| 67.357143 | 254 | 0.708812 | 3.556152 | false | false | false | false |
mr-v/AssertThrows
|
AssertThrows/AssertThrows.swift
|
1
|
2741
|
//
// AssertThrows.swift
// AssertThrows
//
// Copyright (c) 2016 Witold Skibniewski (http://mr-v.github.io/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import XCTest
/// Asserts that error has been thrown.
public func AssertThrows(_ throwingCall: @autoclosure () throws -> Any, file: StaticString = #file, line: UInt = #line) {
do {
_ = try throwingCall()
XCTFail("AssertThrows: No error thrown", file: file, line: line)
} catch {
}
}
/// Asserts that error of specific type has been thrown.
public func AssertThrows<T: Error>(_ type: T.Type, _ throwingCall: @autoclosure () throws -> Any, file: StaticString = #file, line: UInt = #line) {
do {
_ = try throwingCall()
XCTFail("AssertThrows: No error thrown", file: file, line: line)
} catch {
guard error is T else {
return XCTFail("AssertThrows: (\"\(type(of: error))\") is not of type (\"\(T.self)\")", file: file, line: line)
}
}
}
/**
Asserts that error of specific `Equatable` type has been thrown, e.g.
- Swift enums with associated data,
- `NSError`s, where default equality verification relies on checking `code`, `domain` and `userInfo` properties.
*/
public func AssertThrows<T>(_ expected: T, _ throwingCall: @autoclosure () throws -> Any, file: StaticString = #file, line: UInt = #line) where T: Equatable, T: Error {
do {
_ = try throwingCall()
XCTFail()
} catch {
guard let castedError = error as? T, expected == castedError else {
return XCTFail("AssertThrows: (\"\(type(of: expected)) \(expected)\") is not equal to (\"\(error)\")", file: file, line: line)
}
}
}
|
mit
|
5251732fe754cd204b2f30517f4b8f95
| 41.169231 | 168 | 0.677855 | 4.140483 | false | false | false | false |
shridharmalimca/iOSDev
|
iOS/Swift 3.0/Notification/Notification/ViewController.swift
|
2
|
983
|
//
// ViewController.swift
// Notification
//
// Created by Shridhar Mali on 1/9/17.
// Copyright © 2017 Shridhar Mali. 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.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func scheduleNotification(_ sender: Any) {
let localNotification = UILocalNotification()
localNotification.alertBody = "Hi This is notification"
localNotification.fireDate = Date(timeIntervalSinceNow: 5)
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.category = "localNotification"
UIApplication.shared.scheduleLocalNotification(localNotification)
}
}
|
apache-2.0
|
47bbcdad2c0d56651be249e1aa2ac6ae
| 27.057143 | 80 | 0.695519 | 5.643678 | false | false | false | false |
LY-Coder/LYPlayer
|
LYPlayerExample/LYPlayer/LYGestureView.swift
|
1
|
8278
|
//
// LYGestureView.swift
//
// Copyright © 2017年 ly_coder. All rights reserved.
//
// GitHub地址:https://github.com/LY-Coder/LYPlayer
//
import UIKit
import MediaPlayer
public enum Direction {
case leftOrRight
case upOrDown
case none
}
@objc protocol LYGestureViewDelegate {
func progressDragging(_ changeSeconds: Double)
/// 快进、快退
///
/// - Parameter seconds: 移动的秒数
func adjustVideoPlaySeconds(_ changeSeconds: Double)
/// 单击手势代理事件
///
/// - Parameter view: self
func singleTapGestureAction(view: UIImageView)
/// 双击手势代理事件
///
/// - Parameter view: self
func doubleTapGestureAction(view: UIImageView)
}
class LYGestureView: UIImageView {
weak var delegate: LYGestureViewDelegate?
fileprivate var direction: Direction?
// 开始点击时的坐标
fileprivate var startPoint: CGPoint?
// 开始值
fileprivate var startValue: Float?
/** 是否允许拖拽手势 */
var isEnabledDragGesture: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 初始化
fileprivate func initialize() {
isUserInteractionEnabled = true
// 添加单击手势
addGestureRecognizer(singleTapGesture)
// 添加双击手势
addGestureRecognizer(doubleTapGesture)
// 双击手势触发时,取消点击手势
singleTapGesture.require(toFail: doubleTapGesture)
}
/** 单击手势 */
lazy var singleTapGesture: UITapGestureRecognizer = {
let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(singleTapAction))
singleTapGesture.numberOfTapsRequired = 1
singleTapGesture.numberOfTouchesRequired = 1
return singleTapGesture
}()
/** 双击手势 */
lazy var doubleTapGesture: UITapGestureRecognizer = {
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(doubleTapAction))
doubleTapGesture.numberOfTapsRequired = 2
doubleTapGesture.numberOfTouchesRequired = 1
return doubleTapGesture
}()
/** 音量指示器 */
lazy var volumeViewSlider: UISlider? = {
let volumeView = MPVolumeView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
var volumeViewSlider: UISlider? = nil
for view in volumeView.subviews {
if (NSStringFromClass(view.classForCoder) == "MPVolumeSlider") {
volumeViewSlider = view as? UISlider
volumeViewSlider?.sendActions(for: .touchUpInside)
break
}
}
return volumeViewSlider
}()
/** 触摸开始 */
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// 开始触摸点的坐标
startPoint = touches.first?.location(in: self)
// 检测用户是触摸屏幕的左边还是右边,以此判断用户是要调节音量还是亮度,左边是亮度,右边是音量
if (startPoint?.x)! <= frame.size.width / 2.0 {
// 亮度
startValue = Float(UIScreen.main.brightness)
} else {
// 音量
startValue = volumeViewSlider?.value
}
// 方向为无
direction = .none
}
/** 触摸结束 */
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
// 判断是否激活拖拽手势
if isEnabledDragGesture == false {
return
}
let point = touches.first?.location(in: self)
// 计算手指移动的距离
let panPoint = CGPoint(x: (point?.x)! - (startPoint?.x)!, y: (point?.y)! - (startPoint?.y)!)
// 分析用户滑动的方向
switch judgeGesture(point: point) {
case .none:
break
case .leftOrRight:
let seconds = panPoint.x / 10
self.delegate?.adjustVideoPlaySeconds(Double(seconds))
break
case .upOrDown:
break
}
}
/** 触摸移动中 */
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
// 判断是否激活拖拽手势
if isEnabledDragGesture == false {
return
}
var point: CGPoint?
for touch in touches {
point = touch.location(in: self)
}
// 计算手指移动的距离
let panPoint = CGPoint(x: (point?.x)! - (startPoint?.x)!, y: (point?.y)! - (startPoint?.y)!)
// 通过手指滑动的距离,计算音量或亮度需要调整的值
let changeValue = calculateValue(point: panPoint)
// 分析用户滑动的方向
switch judgeGesture(point: point) {
case .none:
break
case .leftOrRight:
// 视频进度
direction = .leftOrRight
case .upOrDown:
// 音量和亮度
direction = .upOrDown
}
if direction == .none {
return
} else if direction == .upOrDown {
// 音量和亮度
if (startPoint?.x)! <= frame.size.width / 2.0 {
// 调节亮度
UIScreen.main.brightness = CGFloat(startValue!) + changeValue
// 判断是增加还是减少
if panPoint.y < 0 {
// 增加亮度
} else {
// 减少亮度
}
let brightnessView = LYBrightnessView.shard as! LYBrightnessView
brightnessView.progress = CGFloat(startValue!) + changeValue
} else {
// 音量
volumeViewSlider?.setValue(startValue! + Float(changeValue), animated: true)
if panPoint.y < 0 {
// 增加音量
} else {
// 减少音量
}
}
} else {
// 视频进度
let seconds = panPoint.x / 10
self.delegate?.progressDragging((Double(seconds)))
}
}
}
// MARK: - FUNC
extension LYGestureView {
/** 调整音量 */
func adjustVolume(volume: Float) {
volumeViewSlider?.setValue(volume, animated: true)
}
/** 根据当前手指坐标判断手势 */
func judgeGesture(point: CGPoint?) -> Direction {
if point == nil {
return .none
}
// 获取x、y轴滑动距离
let lenghtY = fabs(point!.y) - fabs(startPoint!.y)
let lenghtX = fabs(point!.x) - fabs(startPoint!.x)
if fabs(lenghtY) > fabs(lenghtX) {
// 音量和亮度
return .upOrDown
} else if fabs(lenghtY) < fabs(lenghtX) {
// 视频进度
return .leftOrRight
} else {
// 没有手势
return .none
}
}
/** 通过手指滑动的距离,计算音量或亮度需要调整的值 */
func calculateValue(point: CGPoint) -> CGFloat {
// 由于手指离屏幕左上角越近(竖屏),值增加,所以加负号,使手指向右边划时,值增加
// * 3 :在滑动相等距离的情况下,乘的越大,滑动产生的效果越大(value变化快)
let value = -point.y / UIScreen.main.bounds.size.width * 3
return value
}
}
// MARK: - Action
extension LYGestureView {
/// 点击手势事件
@objc fileprivate func singleTapAction() {
self.delegate?.singleTapGestureAction(view: self)
}
/// 双击手势事件
@objc fileprivate func doubleTapAction() {
self.delegate?.doubleTapGestureAction(view: self)
}
}
|
mit
|
95152a930869ebc6ae80abef3fe5fe94
| 26.324723 | 103 | 0.545442 | 4.353322 | false | false | false | false |
Hyfenglin/bluehouseapp
|
iOS/post/post/CommentDetailViewController.swift
|
1
|
3700
|
//
// CommentDetailViewController.swift
// post
//
// Created by Derek Li on 14-10-8.
// Copyright (c) 2014年 Derek Li. All rights reserved.
//
import Foundation
import UIKit
class CommentDetailViewController:ViewController{
var contentLabel: UILabel!
var contentInfoLabel: UILabel!
var createdLabel: UILabel!
var createdInfoLabel: UILabel!
var modifiedLabel: UILabel!
var modifiedInfoLabel: UILabel!
var comment: Comment!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "评论详情"
self.initViewStyle()
self.view.addSubview(contentLabel)
self.view.addSubview(createdLabel)
self.view.addSubview(modifiedLabel)
self.view.addSubview(contentInfoLabel)
self.view.addSubview(createdInfoLabel)
self.view.addSubview(modifiedInfoLabel)
self.getPostData()
}
func getPostData(){
if comment.id == 0 {
return
}
var dl=HttpClient()
var url = "\(Constant().URL_COMMENT_DETAIL)\(comment.id)"
println("\(url)")
dl.downloadFromGetUrl(url, completionHandler: {(data: NSData?, error: NSError?) -> Void in
if (error != nil){
println("error=\(error!.localizedDescription)")
}else{
var dict=NSJSONSerialization.JSONObjectWithData(data!, options:.MutableContainers, error:nil) as? NSDictionary
dict=NSJSONSerialization.JSONObjectWithData(data!, options:.MutableContainers, error:nil) as? NSDictionary
println("\(dict)")
var commentData:NSDictionary = dict?.objectForKey("data") as NSDictionary
self.comment = Comment(dic: commentData)
self.refreshView()
}
})
}
func refreshView(){
self.contentInfoLabel.text = self.comment.content
self.createdInfoLabel.text = self.comment.created
self.modifiedInfoLabel.text = self.comment.modified
self.tableView?.reloadData()
}
func initViewStyle(){
var viewSize = self.view.frame.size
var viewOrgin = self.view.frame.origin
var labelWidth:CGFloat = 100.0
var textFieldWidth:CGFloat = 250.0
var btnWidth:CGFloat = 150.0
var left:CGFloat = (viewSize.width)-btnWidth
contentLabel = UILabel(frame:CGRect(origin: CGPointMake((viewSize.width - labelWidth - textFieldWidth)/2, 80.0), size: CGSizeMake(labelWidth,20)))
contentLabel.text = "内容:"
contentInfoLabel = UILabel(frame:CGRect(origin: CGPointMake((viewSize.width + labelWidth - textFieldWidth)/2, 80.0), size: CGSizeMake(textFieldWidth,20)))
createdLabel = UILabel(frame:CGRect(origin: CGPointMake((viewSize.width - labelWidth - textFieldWidth)/2, 100.0), size: CGSizeMake(labelWidth,20)))
createdLabel.text = "创建时间:"
createdInfoLabel = UILabel(frame:CGRect(origin: CGPointMake((viewSize.width + labelWidth - textFieldWidth)/2, 100.0), size: CGSizeMake(textFieldWidth,20)))
modifiedLabel = UILabel(frame:CGRect(origin: CGPointMake((viewSize.width - labelWidth - textFieldWidth)/2, 120.0), size: CGSizeMake(labelWidth,20)))
modifiedLabel.text = "修改时间:"
modifiedInfoLabel = UILabel(frame:CGRect(origin: CGPointMake((viewSize.width + labelWidth - textFieldWidth)/2, 120.0), size: CGSizeMake(textFieldWidth,20)))
}
}
|
mit
|
0e5689db6f2d8cea458013abad4cf279
| 35.71 | 164 | 0.618256 | 4.809961 | false | false | false | false |
prolificinteractive/IQKeyboardManager
|
IQKeybordManagerSwift/Categories/IQUIWindow+Hierarchy.swift
|
1
|
2244
|
//
// IQUIWindow+Hierarchy.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-14 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
/** @abstract UIWindow hierarchy category. */
extension UIWindow {
/** @return Returns the current Top Most ViewController in hierarchy. */
override func topMostController()->UIViewController? {
var topController = rootViewController
while let presentedController = topController?.presentedViewController {
topController = presentedController
}
return topController
}
/** @return Returns the topViewController in stack of topMostController. */
func currentViewController()->UIViewController? {
var currentViewController = topMostController()
while currentViewController != nil && currentViewController is UINavigationController && (currentViewController as UINavigationController).topViewController != nil {
currentViewController = (currentViewController as UINavigationController).topViewController
}
return currentViewController
}
}
|
mit
|
446f143397ff96da73759e8956c3176c
| 40.555556 | 173 | 0.730392 | 5.638191 | false | false | false | false |
rzrasel/iOS-Swift-2016-01
|
SwiftRatingBarOne/SwiftRatingBarOne/RzLibs/UIImage+Utils.swift
|
2
|
1789
|
//
// UIImage+Utils.swift
// TestTableExmpTestOne
//
// Created by NextDot on 2/3/16.
// Copyright © 2016 RzRasel. All rights reserved.
//
import Foundation
import UIKit
extension UIImage{
//|------------------------------------|
//|------------------------------------|
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
func imageResize(image: UIImage, scaledToSize newSize: CGSize) -> UIImage
{
var width: CGFloat!
var height: CGFloat!
//IMAGE SIZE
if image.size.width/newSize.width >= image.size.height / newSize.height{
width = newSize.width
height = image.size.height / (image.size.width/newSize.width)
}else{
height = newSize.height
width = image.size.width / (image.size.height/newSize.height)
}
let sizeImageSmall = CGSizeMake(width, height)
//end
print(sizeImageSmall)
UIGraphicsBeginImageContext(sizeImageSmall);
image.drawInRect(CGRectMake(0,0,sizeImageSmall.width,sizeImageSmall.height))
let newImage:UIImage=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
class func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
//|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|
}
|
apache-2.0
|
84b53f92e3501a6a015257ae618d4505
| 30.946429 | 84 | 0.555928 | 4.966667 | false | false | false | false |
willpowell8/UIDesignKit_iOS
|
UIDesignKit/Classes/Editor/ColourView/ColorPickerController.swift
|
1
|
1707
|
import UIKit
open class ColorPickerController: NSObject {
open var onColorChange:((_ color:UIColor, _ finished:Bool)->Void)? = nil
// Hue Picker
open var huePicker:HuePicker
// Color Well
open var colorWell:ColorWell {
didSet {
huePicker.setHueFromColor(colorWell.color)
colorPicker.color = colorWell.color
}
}
// Color Picker
open var colorPicker:ColorPicker
open var color:UIColor? {
set(value) {
colorPicker.color = value!
colorWell.color = value!
huePicker.setHueFromColor(value!)
}
get {
return colorPicker.color
}
}
public init(svPickerView:ColorPicker, huePickerView:HuePicker, colorWell:ColorWell) {
self.huePicker = huePickerView
self.colorPicker = svPickerView
self.colorWell = colorWell
self.colorWell.color = colorPicker.color
self.huePicker.setHueFromColor(colorPicker.color)
super.init()
self.colorPicker.onColorChange = {(color, finished) -> Void in
self.huePicker.setHueFromColor(color)
self.colorWell.previewColor = (finished) ? nil : color
if(finished) {self.colorWell.color = color}
self.onColorChange?(color, finished)
}
self.huePicker.onHueChange = {(hue, finished) -> Void in
self.colorPicker.h = CGFloat(hue)
let color = self.colorPicker.color
self.colorWell.previewColor = (finished) ? nil : color
if(finished) {self.colorWell.color = color}
self.onColorChange?(color, finished)
}
}
}
|
mit
|
dc34053c71f8332f1508b548095717ac
| 30.036364 | 89 | 0.598125 | 4.480315 | false | false | false | false |
mshhmzh/firefox-ios
|
Utils/KeychainCache.swift
|
4
|
2252
|
/* 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 XCGLogger
import SwiftKeychainWrapper
private let log = Logger.keychainLogger
public protocol JSONLiteralConvertible {
func asJSON() -> JSON
}
public class KeychainCache<T: JSONLiteralConvertible> {
public let branch: String
public let label: String
public var value: T? {
didSet {
checkpoint()
}
}
public init(branch: String, label: String, value: T?) {
self.branch = branch
self.label = label
self.value = value
}
public class func fromBranch(branch: String, withLabel label: String?, withDefault defaultValue: T? = nil, factory: JSON -> T?) -> KeychainCache<T> {
if let l = label {
if let s = KeychainWrapper.stringForKey("\(branch).\(l)") {
if let t = factory(JSON.parse(s)) {
log.info("Read \(branch) from Keychain with label \(branch).\(l).")
return KeychainCache(branch: branch, label: l, value: t)
} else {
log.warning("Found \(branch) in Keychain with label \(branch).\(l), but could not parse it.")
}
} else {
log.warning("Did not find \(branch) in Keychain with label \(branch).\(l).")
}
} else {
log.warning("Did not find \(branch) label in Keychain.")
}
// Fall through to missing.
log.warning("Failed to read \(branch) from Keychain.")
let label = label ?? Bytes.generateGUID()
return KeychainCache(branch: branch, label: label, value: defaultValue)
}
public func checkpoint() {
log.info("Storing \(self.branch) in Keychain with label \(self.branch).\(self.label).")
// TODO: PII logging.
if let value = value {
let jsonString = value.asJSON().toString(false)
KeychainWrapper.setString(jsonString, forKey: "\(branch).\(label)")
} else {
KeychainWrapper.removeObjectForKey("\(branch).\(label)")
}
}
}
|
mpl-2.0
|
14689f9bf458d81372f462481c9d5ec1
| 35.322581 | 153 | 0.587922 | 4.567951 | false | false | false | false |
codwam/NPB
|
Demos/NPBDemo/NPB/Private/UINavigationBar+NPB.swift
|
1
|
1911
|
//
// UINavigationBar+NPB.swift
// NPBDemo
//
// Created by 李辉 on 2017/4/12.
// Copyright © 2017年 codwam. All rights reserved.
//
import UIKit
extension UINavigationBar: NPBBarProtocol {
fileprivate struct AssociatedKeys {
static var npb_transitionAnimated: Bool?
static var npb_size: CGSize?
}
var npb_transitionAnimated: Bool {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.npb_transitionAnimated) as! Bool
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.npb_transitionAnimated, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if let backgroundView = self.npb_backgroundView, backgroundView.alpha < 1 {
let rect = CGRect(x: 0, y: Double(self.bounds.height) - NPB_NavigationBarHeight, width: Double(self.bounds.width), height: NPB_NavigationBarHeight)
return rect.contains(point)
}
return super.point(inside: point, with: event)
}
// MARK: - NPBBarProtocol
// TODO: 又重复了,不然set不了
var npb_size: CGSize {
get {
guard let npb_size = objc_getAssociatedObject(self, &AssociatedKeys.npb_size) as? CGSize else {
return CGSize.zero
}
return npb_size
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.npb_size, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func npb_sizeThatFits(_ size: CGSize) -> CGSize {
let newSize = npb_sizeThatFits(size)
let width = self.npb_size.width == 0 ? newSize.width : self.npb_size.width
let height = self.npb_size.height == 0 ? newSize.height : self.npb_size.height
return CGSize(width: width, height: height)
}
}
|
mit
|
337c254b8246df7ca988bff2092060b1
| 32.087719 | 159 | 0.623542 | 3.995763 | false | false | false | false |
gregomni/swift
|
stdlib/public/core/ArrayBuffer.swift
|
2
|
22806
|
//===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This is the class that implements the storage and object management for
// Swift Array.
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
import SwiftShims
@usableFromInline
internal typealias _ArrayBridgeStorage
= _BridgeStorage<__ContiguousArrayStorageBase>
@usableFromInline
@frozen
internal struct _ArrayBuffer<Element>: _ArrayBufferProtocol {
@usableFromInline
internal var _storage: _ArrayBridgeStorage
@inlinable
internal init(storage: _ArrayBridgeStorage) {
_storage = storage
}
/// Create an empty buffer.
@inlinable
internal init() {
_storage = _ArrayBridgeStorage(native: _emptyArrayStorage)
}
@inlinable
internal init(nsArray: AnyObject) {
_internalInvariant(_isClassOrObjCExistential(Element.self))
_storage = _ArrayBridgeStorage(objC: nsArray)
}
/// Returns an `_ArrayBuffer<U>` containing the same elements.
///
/// - Precondition: The elements actually have dynamic type `U`, and `U`
/// is a class or `@objc` existential.
@inlinable
__consuming internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> {
_internalInvariant(_isClassOrObjCExistential(Element.self))
_internalInvariant(_isClassOrObjCExistential(U.self))
return _ArrayBuffer<U>(storage: _storage)
}
/// Returns an `_ArrayBuffer<U>` containing the same elements,
/// deferring checking each element's `U`-ness until it is accessed.
///
/// - Precondition: `U` is a class or `@objc` existential derived from
/// `Element`.
@inlinable
__consuming internal func downcast<U>(
toBufferWithDeferredTypeCheckOf _: U.Type
) -> _ArrayBuffer<U> {
_internalInvariant(_isClassOrObjCExistential(Element.self))
_internalInvariant(_isClassOrObjCExistential(U.self))
// FIXME: can't check that U is derived from Element pending
// <rdar://problem/20028320> generic metatype casting doesn't work
// _internalInvariant(U.self is Element.Type)
return _ArrayBuffer<U>(
storage: _ArrayBridgeStorage(native: _native._storage, isFlagged: true))
}
@inlinable
internal var needsElementTypeCheck: Bool {
// NSArray's need an element typecheck when the element type isn't AnyObject
return !_isNativeTypeChecked && !(AnyObject.self is Element.Type)
}
}
extension _ArrayBuffer {
/// Adopt the storage of `source`.
@inlinable
internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) {
_internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
_storage = _ArrayBridgeStorage(native: source._storage)
}
/// `true`, if the array is native and does not need a deferred type check.
@inlinable
internal var arrayPropertyIsNativeTypeChecked: Bool {
return _isNativeTypeChecked
}
/// Returns `true` if this buffer's storage is uniquely referenced;
/// otherwise, returns `false`.
///
/// This function should only be used for internal sanity checks.
/// To guard a buffer mutation, use `beginCOWMutation`.
@inlinable
internal mutating func isUniquelyReferenced() -> Bool {
if !_isClassOrObjCExistential(Element.self) {
return _storage.isUniquelyReferencedUnflaggedNative()
}
return _storage.isUniquelyReferencedNative()
}
/// Returns `true` and puts the buffer in a mutable state if the buffer's
/// storage is uniquely-referenced; otherwise performs no action and
/// returns `false`.
///
/// - Precondition: The buffer must be immutable.
///
/// - Warning: It's a requirement to call `beginCOWMutation` before the buffer
/// is mutated.
@_alwaysEmitIntoClient
internal mutating func beginCOWMutation() -> Bool {
let isUnique: Bool
if !_isClassOrObjCExistential(Element.self) {
isUnique = _storage.beginCOWMutationUnflaggedNative()
} else if !_storage.beginCOWMutationNative() {
return false
} else {
isUnique = _isNative
}
#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED
if isUnique {
_native.isImmutable = false
}
#endif
return isUnique
}
/// Puts the buffer in an immutable state.
///
/// - Precondition: The buffer must be mutable or the empty array singleton.
///
/// - Warning: After a call to `endCOWMutation` the buffer must not be mutated
/// until the next call of `beginCOWMutation`.
@_alwaysEmitIntoClient
@inline(__always)
internal mutating func endCOWMutation() {
#if INTERNAL_CHECKS_ENABLED && COW_CHECKS_ENABLED
_native.isImmutable = true
#endif
_storage.endCOWMutation()
}
/// Convert to an NSArray.
///
/// O(1) if the element type is bridged verbatim, O(*n*) otherwise.
@inlinable
internal func _asCocoaArray() -> AnyObject {
return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative.buffer
}
/// Creates and returns a new uniquely referenced buffer which is a copy of
/// this buffer.
///
/// This buffer is consumed, i.e. it's released.
@_alwaysEmitIntoClient
@inline(never)
@_semantics("optimize.sil.specialize.owned2guarantee.never")
internal __consuming func _consumeAndCreateNew() -> _ArrayBuffer {
return _consumeAndCreateNew(bufferIsUnique: false,
minimumCapacity: count,
growForAppend: false)
}
/// Creates and returns a new uniquely referenced buffer which is a copy of
/// this buffer.
///
/// If `bufferIsUnique` is true, the buffer is assumed to be uniquely
/// referenced and the elements are moved - instead of copied - to the new
/// buffer.
/// The `minimumCapacity` is the lower bound for the new capacity.
/// If `growForAppend` is true, the new capacity is calculated using
/// `_growArrayCapacity`, but at least kept at `minimumCapacity`.
///
/// This buffer is consumed, i.e. it's released.
@_alwaysEmitIntoClient
@inline(never)
@_semantics("optimize.sil.specialize.owned2guarantee.never")
internal __consuming func _consumeAndCreateNew(
bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool
) -> _ArrayBuffer {
let newCapacity = _growArrayCapacity(oldCapacity: capacity,
minimumCapacity: minimumCapacity,
growForAppend: growForAppend)
let c = count
_internalInvariant(newCapacity >= c)
let newBuffer = _ContiguousArrayBuffer<Element>(
_uninitializedCount: c, minimumCapacity: newCapacity)
if bufferIsUnique {
// As an optimization, if the original buffer is unique, we can just move
// the elements instead of copying.
let dest = newBuffer.firstElementAddress
dest.moveInitialize(from: mutableFirstElementAddress,
count: c)
_native.mutableCount = 0
} else {
_copyContents(
subRange: 0..<c,
initializing: newBuffer.mutableFirstElementAddress)
}
return _ArrayBuffer(_buffer: newBuffer, shiftedToStartIndex: 0)
}
/// If this buffer is backed by a uniquely-referenced mutable
/// `_ContiguousArrayBuffer` that can be grown in-place to allow the self
/// buffer store minimumCapacity elements, returns that buffer.
/// Otherwise, returns `nil`.
@inlinable
internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int)
-> NativeBuffer? {
if _fastPath(isUniquelyReferenced()) {
let b = _native
if _fastPath(b.mutableCapacity >= minimumCapacity) {
return b
}
}
return nil
}
@inlinable
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@inlinable
internal func requestNativeBuffer() -> NativeBuffer? {
if !_isClassOrObjCExistential(Element.self) {
return _native
}
return _fastPath(_storage.isNative) ? _native : nil
}
// We have two versions of type check: one that takes a range and the other
// checks one element. The reason for this is that the ARC optimizer does not
// handle loops atm. and so can get blocked by the presence of a loop (over
// the range). This loop is not necessary for a single element access.
@inline(never)
@usableFromInline
internal func _typeCheckSlowPath(_ index: Int) {
if _fastPath(_isNative) {
let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index]
guard element is Element else {
_assertionFailure(
"Fatal error",
"""
Down-casted Array element failed to match the target type
Expected \(Element.self) but found \(type(of: element))
""",
flags: _fatalErrorFlags()
)
}
}
else {
let element = _nonNative[index]
guard element is Element else {
_assertionFailure(
"Fatal error",
"""
NSArray element failed to match the Swift Array Element type
Expected \(Element.self) but found \(type(of: element))
""",
flags: _fatalErrorFlags()
)
}
}
}
@inlinable
internal func _typeCheck(_ subRange: Range<Int>) {
if !_isClassOrObjCExistential(Element.self) {
return
}
if _slowPath(needsElementTypeCheck) {
// Could be sped up, e.g. by using
// enumerateObjectsAtIndexes:options:usingBlock: in the
// non-native case.
for i in subRange.lowerBound ..< subRange.upperBound {
_typeCheckSlowPath(i)
}
}
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@inlinable
@discardableResult
__consuming internal func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native._copyContents(subRange: bounds, initializing: target)
}
let buffer = UnsafeMutableRawPointer(target)
.assumingMemoryBound(to: AnyObject.self)
let result = _nonNative._copyContents(
subRange: bounds,
initializing: buffer)
return UnsafeMutableRawPointer(result).assumingMemoryBound(to: Element.self)
}
@inlinable
internal __consuming func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
if _fastPath(_isNative) {
let (_, c) = _native._copyContents(initializing: buffer)
return (IndexingIterator(_elements: self, _position: c), c)
}
guard buffer.count > 0 else { return (makeIterator(), 0) }
let ptr = UnsafeMutableRawPointer(buffer.baseAddress)?
.assumingMemoryBound(to: AnyObject.self)
let (_, c) = _nonNative._copyContents(
initializing: UnsafeMutableBufferPointer(start: ptr, count: buffer.count))
return (IndexingIterator(_elements: self, _position: c), c)
}
/// Returns a `_SliceBuffer` containing the given sub-range of elements in
/// `bounds` from this buffer.
@inlinable
internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
_typeCheck(bounds)
if _fastPath(_isNative) {
return _native[bounds]
}
return _nonNative[bounds].unsafeCastElements(to: Element.self)
}
set {
fatalError("not implemented")
}
}
/// A pointer to the first element.
///
/// - Precondition: The elements are known to be stored contiguously.
@inlinable
internal var firstElementAddress: UnsafeMutablePointer<Element> {
_internalInvariant(_isNative, "must be a native buffer")
return _native.firstElementAddress
}
/// A mutable pointer to the first element.
///
/// - Precondition: the buffer must be mutable.
@_alwaysEmitIntoClient
internal var mutableFirstElementAddress: UnsafeMutablePointer<Element> {
_internalInvariant(_isNative, "must be a native buffer")
return _native.mutableFirstElementAddress
}
@inlinable
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return _fastPath(_isNative) ? firstElementAddress : nil
}
/// The number of elements the buffer stores.
///
/// This property is obsolete. It's only used for the ArrayBufferProtocol and
/// to keep backward compatibility.
/// Use `immutableCount` or `mutableCount` instead.
@inlinable
internal var count: Int {
@inline(__always)
get {
return _fastPath(_isNative) ? _native.count : _nonNative.endIndex
}
set {
_internalInvariant(_isNative, "attempting to update count of Cocoa array")
_native.count = newValue
}
}
/// The number of elements of the buffer.
///
/// - Precondition: The buffer must be immutable.
@_alwaysEmitIntoClient
internal var immutableCount: Int {
return _fastPath(_isNative) ? _native.immutableCount : _nonNative.endIndex
}
/// The number of elements of the buffer.
///
/// - Precondition: The buffer must be mutable.
@_alwaysEmitIntoClient
internal var mutableCount: Int {
@inline(__always)
get {
_internalInvariant(
_isNative,
"attempting to get mutating-count of non-native buffer")
return _native.mutableCount
}
@inline(__always)
set {
_internalInvariant(_isNative, "attempting to update count of Cocoa array")
_native.mutableCount = newValue
}
}
/// Traps if an inout violation is detected or if the buffer is
/// native and the subscript is out of range.
///
/// wasNative == _isNative in the absence of inout violations.
/// Because the optimizer can hoist the original check it might have
/// been invalidated by illegal user code.
@inlinable
internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) {
_precondition(
_isNative == wasNative,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNative) {
_native._checkValidSubscript(index)
}
}
/// Traps if an inout violation is detected or if the buffer is
/// native and typechecked and the subscript is out of range.
///
/// wasNativeTypeChecked == _isNativeTypeChecked in the absence of
/// inout violations. Because the optimizer can hoist the original
/// check it might have been invalidated by illegal user code.
@inlinable
internal func _checkInoutAndNativeTypeCheckedBounds(
_ index: Int, wasNativeTypeChecked: Bool
) {
_precondition(
_isNativeTypeChecked == wasNativeTypeChecked,
"inout rules were violated: the array was overwritten")
if _fastPath(wasNativeTypeChecked) {
_native._checkValidSubscript(index)
}
}
/// Traps unless the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
///
/// - Precondition: The buffer must be mutable.
@_alwaysEmitIntoClient
internal func _checkValidSubscriptMutating(_ index: Int) {
_native._checkValidSubscriptMutating(index)
}
/// The number of elements the buffer can store without reallocation.
///
/// This property is obsolete. It's only used for the ArrayBufferProtocol and
/// to keep backward compatibility.
/// Use `immutableCapacity` or `mutableCapacity` instead.
@inlinable
internal var capacity: Int {
return _fastPath(_isNative) ? _native.capacity : _nonNative.endIndex
}
/// The number of elements the buffer can store without reallocation.
///
/// - Precondition: The buffer must be immutable.
@_alwaysEmitIntoClient
internal var immutableCapacity: Int {
return _fastPath(_isNative) ? _native.immutableCapacity : _nonNative.count
}
/// The number of elements the buffer can store without reallocation.
///
/// - Precondition: The buffer must be mutable.
@_alwaysEmitIntoClient
internal var mutableCapacity: Int {
_internalInvariant(_isNative, "attempting to get mutating-capacity of non-native buffer")
return _native.mutableCapacity
}
@inlinable
@inline(__always)
internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element {
if _fastPath(wasNativeTypeChecked) {
return _nativeTypeChecked[i]
}
return unsafeBitCast(_getElementSlowPath(i), to: Element.self)
}
@inline(never)
@inlinable // @specializable
internal func _getElementSlowPath(_ i: Int) -> AnyObject {
_internalInvariant(
_isClassOrObjCExistential(Element.self),
"Only single reference elements can be indexed here.")
let element: AnyObject
if _isNative {
// _checkInoutAndNativeTypeCheckedBounds does no subscript
// checking for the native un-typechecked case. Therefore we
// have to do it here.
_native._checkValidSubscript(i)
element = cast(toBufferOf: AnyObject.self)._native[i]
guard element is Element else {
_assertionFailure(
"Fatal error",
"""
Down-casted Array element failed to match the target type
Expected \(Element.self) but found \(type(of: element))
""",
flags: _fatalErrorFlags()
)
}
} else {
// ObjC arrays do their own subscript checking.
element = _nonNative[i]
guard element is Element else {
_assertionFailure(
"Fatal error",
"""
NSArray element failed to match the Swift Array Element type
Expected \(Element.self) but found \(type(of: element))
""",
flags: _fatalErrorFlags()
)
}
}
return element
}
/// Get or set the value of the ith element.
@inlinable
internal subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
}
nonmutating set {
if _fastPath(_isNative) {
_native[i] = newValue
}
else {
var refCopy = self
refCopy.replaceSubrange(
i..<(i + 1),
with: 1,
elementsOf: CollectionOfOne(newValue))
}
}
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage. If no such storage exists, it is
/// created on-demand.
@inlinable
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
if _fastPath(_isNative) {
defer { _fixLifetime(self) }
return try body(
UnsafeBufferPointer(start: firstElementAddress, count: count))
}
return try ContiguousArray(self).withUnsafeBufferPointer(body)
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
///
/// - Precondition: Such contiguous storage exists or the buffer is empty.
@inlinable
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
_internalInvariant(
_isNative || count == 0,
"Array is bridging an opaque NSArray; can't get a pointer to the elements"
)
defer { _fixLifetime(self) }
return try body(UnsafeMutableBufferPointer(
start: firstElementAddressIfContiguous, count: count))
}
/// An object that keeps the elements stored in this buffer alive.
@inlinable
internal var owner: AnyObject {
return _fastPath(_isNative) ? _native._storage : _nonNative.buffer
}
/// An object that keeps the elements stored in this buffer alive.
///
/// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`.
@inlinable
internal var nativeOwner: AnyObject {
_internalInvariant(_isNative, "Expect a native array")
return _native._storage
}
/// A value that identifies the storage used by the buffer. Two
/// buffers address the same elements when they have the same
/// identity and count.
@inlinable
internal var identity: UnsafeRawPointer {
if _isNative {
return _native.identity
}
else {
return UnsafeRawPointer(
Unmanaged.passUnretained(_nonNative.buffer).toOpaque())
}
}
//===--- Collection conformance -------------------------------------===//
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@inlinable
internal var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
@inlinable
internal var endIndex: Int {
return count
}
@usableFromInline
internal typealias Indices = Range<Int>
//===--- private --------------------------------------------------------===//
internal typealias Storage = _ContiguousArrayStorage<Element>
@usableFromInline
internal typealias NativeBuffer = _ContiguousArrayBuffer<Element>
@inlinable
internal var _isNative: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
} else {
return _storage.isNative
}
}
/// `true`, if the array is native and does not need a deferred type check.
@inlinable
internal var _isNativeTypeChecked: Bool {
if !_isClassOrObjCExistential(Element.self) {
return true
} else {
return _storage.isUnflaggedNative
}
}
/// Our native representation.
///
/// - Precondition: `_isNative`.
@inlinable
internal var _native: NativeBuffer {
return NativeBuffer(
_isClassOrObjCExistential(Element.self)
? _storage.nativeInstance : _storage.unflaggedNativeInstance)
}
/// Fast access to the native representation.
///
/// - Precondition: `_isNativeTypeChecked`.
@inlinable
internal var _nativeTypeChecked: NativeBuffer {
return NativeBuffer(_storage.unflaggedNativeInstance)
}
@inlinable
internal var _nonNative: _CocoaArrayWrapper {
get {
_internalInvariant(_isClassOrObjCExistential(Element.self))
return _CocoaArrayWrapper(_storage.objCInstance)
}
}
}
extension _ArrayBuffer: @unchecked Sendable
where Element: Sendable { }
#endif
|
apache-2.0
|
de12c7850ded9e9c1a532de074e9086d
| 31.670487 | 93 | 0.668041 | 4.805901 | false | false | false | false |
dogo/AKSideMenu
|
AKSideMenuExamples/Simple/AKSideMenuSimple/SecondViewController/SecondViewController.swift
|
1
|
1982
|
//
// SecondViewController.swift
// AKSideMenuSimple
//
// Created by Diogo Autilio on 6/7/16.
// Copyright © 2016 AnyKey Entertainment. All rights reserved.
//
import UIKit
final class SecondViewController: UIViewController {
// MARK: - Properties
let secondView = SecondView()
// MARK: - Life Cycle
override func loadView() {
view = secondView
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Second Controller"
addNavigationButtons()
secondView.didTouchButton = { [weak self] in
self?.pushViewController()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
debugPrint("SecondViewController will appear")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
debugPrint("SecondViewController will disappear")
}
// MARK: - Private Methods
private func addNavigationButtons() {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Left",
style: .plain,
target: self,
action: #selector(presentLeftMenuViewController))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Right",
style: .plain,
target: self,
action: #selector(presentRightMenuViewController))
}
private func pushViewController() {
let viewController = UIViewController()
viewController.title = "Pushed Controller"
viewController.view.backgroundColor = .white
self.navigationController?.pushViewController(viewController, animated: true)
}
}
|
mit
|
b15862db05bda3ef4e3e114dd52ae464
| 30.951613 | 110 | 0.559313 | 6.268987 | false | false | false | false |
cornerstonecollege/401
|
stang/first/ex2and3test/ex2and3test/main.swift
|
2
|
924
|
//
// main.swift
// ex2and3test
//
// Created by SG on 2016-09-30.
// Copyright © 2016 SG. All rights reserved.
//
import Foundation
import Darwin
/*let dict = [
"roles" : [["id": "1", "role": "Director"],["id":"2", "role":"Cordinator"],["id": "3","role":"Teacher"],["id":"4","role":"Secretary"] ]
]*/
var roles: [String: String] = [
"id 1": "Director",
"id 2": "Cordinator",
"id 3": "Teacher",
"id 4": "Secretary"
]
var locations: [String: String] = [
"id 1":"location: Vancouver",
"id 2": "location: Richmond"
]
print("Type: 'R' to check roles, 'L' to check locations or 'Q' to quit")
var name = readLine()!
if name == "R"{
for (key, value) in roles{
print("\(key): \(value)")
}
}else if name == "L"{
for (key, value) in locations{
print("\(key): \(value)")
}
}else if name == "Q"{
exit(0)
}else{
print("You typed wrong command")
}
|
gpl-3.0
|
d842d0451631e19555d0cf670afecfab
| 17.46 | 139 | 0.537378 | 2.977419 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk
|
Demos/SharedSource/PublicationListViewController.swift
|
1
|
2698
|
//
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2019 ShopGun. All rights reserved.
import ShopGunSDK
import Incito
import CoreLocation
class PublicationListViewController: UIViewController {
var contentVC: UIViewController? = nil {
didSet {
self.cycleFromViewController(
oldViewController: oldValue,
toViewController: contentVC
)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "ShopGunSDK Demo"
// Show the loading spinner
self.contentVC = LoadingViewController()
// Build the request we wish to send to the coreAPI
let location = CoreAPI.Requests.LocationQuery(coordinate: CLLocationCoordinate2D(latitude:55.631090, longitude: 12.577236), radius: nil)
let publicationReq = CoreAPI.Requests.getPublications(near: location, sortedBy: .newestPublished)
// Perform the request
CoreAPI.shared.request(publicationReq) { [weak self] result in
// Show different contents depending upon the result of the request
switch result {
case let .success(publications):
self?.contentVC = PublicationListContentsViewController(
publications: publications,
shouldOpenIncito: { [weak self] in self?.openIncito(for: $0) },
shouldOpenPagedPub: { [weak self] in self?.openPagedPub(for: $0) }
)
case let .failure(error):
self?.contentVC = ErrorViewController(error: error)
}
}
}
func openIncito(for publication: CoreAPI.PagedPublication) {
// Create an instance of `IncitoLoaderViewController`
let incitoVC = DemoIncitoViewController()
incitoVC.load(publication: publication)
self.navigationController?.pushViewController(incitoVC, animated: true)
}
func openPagedPub(for publication: CoreAPI.PagedPublication) {
// Create a view controller containing a `PagedPublicationView`
let pagedPubVC = DemoPagedPublicationViewController()
pagedPubVC.load(publication: publication)
self.navigationController?.pushViewController(pagedPubVC, animated: true)
}
}
|
mit
|
78fb6af8361d30557a4b4fb19fb333db
| 33.465753 | 144 | 0.581876 | 4.943026 | false | false | false | false |
Lclmyname/BookReader_Swift
|
Pods/SnapKit/Source/ConstraintViewDSL.swift
|
1
|
4508
|
//
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public struct ConstraintViewDSL: ConstraintAttributesDSL {
@discardableResult
public func prepareConstraints(_ closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] {
return ConstraintMaker.prepareConstraints(self.view, closure: closure)
}
public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
ConstraintMaker.makeConstraints(self.view, closure: closure)
}
public func remakeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
ConstraintMaker.remakeConstraints(self.view, closure: closure)
}
public func updateConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
ConstraintMaker.updateConstraints(self.view, closure: closure)
}
public func removeConstraints() {
ConstraintMaker.removeConstraints(self.view)
}
public var contentHuggingHorizontalPriority: Float {
get {
return self.view.contentHuggingPriority(for: .horizontal)
}
set {
self.view.setContentHuggingPriority(newValue, for: .horizontal)
}
}
public var contentHuggingVerticalPriority: Float {
get {
return self.view.contentHuggingPriority(for: .vertical)
}
set {
self.view.setContentHuggingPriority(newValue, for: .vertical)
}
}
public var contentCompressionResistanceHorizontalPriority: Float {
get {
return self.view.contentCompressionResistancePriority(for: .horizontal)
}
set {
self.view.setContentHuggingPriority(newValue, for: .horizontal)
}
}
public var contentCompressionResistanceVerticalPriority: Float {
get {
return self.view.contentCompressionResistancePriority(for: .vertical)
}
set {
self.view.setContentCompressionResistancePriority(newValue, for: .vertical)
}
}
public var target: AnyObject? {
return self.view
}
internal let view: ConstraintView
internal init(view: ConstraintView) {
self.view = view
}
internal var constraints: [Constraint] {
return self.constraintsHashTable.allObjects
}
internal func add(_ constraints: [Constraint]) {
let hashTable = self.constraintsHashTable
for constraint in constraints {
hashTable.add(constraint)
}
}
internal func remove(_ constraints: [Constraint]) {
let hashTable = self.constraintsHashTable
for constraint in constraints {
hashTable.remove(constraint)
}
}
fileprivate var constraintsHashTable: NSHashTable<Constraint> {
let constraints: NSHashTable<Constraint>
if let existing = objc_getAssociatedObject(self.view, &constraintsKey) as? NSHashTable<Constraint> {
constraints = existing
} else {
constraints = NSHashTable<Constraint>()
objc_setAssociatedObject(self.view, &constraintsKey, constraints, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return constraints
}
}
private var constraintsKey: UInt8 = 0
|
mit
|
787ab16b2af9fc16bbf831937c595a6e
| 32.392593 | 113 | 0.663043 | 5.111111 | false | false | false | false |
neerajDamle/OpenWeatherForecast
|
OpenWeatherForecast/OpenWeatherForecast/WeatherDetailsViewController.swift
|
1
|
7555
|
//
// WeatherDetailsViewController.swift
// OpenWeatherForecast
//
// Created by Neeraj Damle on 9/1/15.
// Copyright (c) 2015 Neeraj Damle. All rights reserved.
//
import UIKit
class WeatherDetailsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var weatherDetailsTableView: UITableView!
var cellTapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer();
var isTemperatureCellCollapsed = true;
var tempCellHeight: CGFloat = 44.0;
var weather: Weather = Weather();
var weatherParameters: [String] = [WEATHER_DETAIL_KEY_WEATHER_CONDITION_DESCRIPTION,WEATHER_DETAIL_KEY_CLOUDINESS,WEATHER_DETAIL_KEY_WIND_SPEED,WEATHER_DETAIL_KEY_WIND_DIRECTION_IN_DEGREES,WEATHER_DETAIL_KEY_HUMIDITY,WEATHER_DETAIL_KEY_PRESSURE,WEATHER_DETAIL_KEY_TEMP];
override func viewDidLoad() {
super.viewDidLoad()
cellTapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(WeatherDetailsViewController.collapsableCellTapped(_:)));
cellTapGestureRecognizer.numberOfTapsRequired = 1;
let weatherDate = weather.date;
let dateFormatter = DateFormatter();
dateFormatter.dateFormat = "EEE, MMM dd yyyy";
let strDate = dateFormatter.string(from: weatherDate as Date);
self.navigationItem.title = strDate;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setSelectedDayWeather(_ weather: Weather)
{
self.weather = weather;
}
func getValueForWeatherParameter(_ weatherParameter: String) -> String
{
var weatherParameterValue: String = "";
if(weatherParameter == WEATHER_DETAIL_KEY_WEATHER_CONDITION_DESCRIPTION)
{
weatherParameterValue = self.weather.weatherGroups[0].conditionDescription;
}
else if(weatherParameter == WEATHER_DETAIL_KEY_CLOUDINESS)
{
weatherParameterValue = String(format:"%.1f",self.weather.cloudiness);
weatherParameterValue += "%";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_WIND_SPEED)
{
weatherParameterValue = String(format:"%.1f",self.weather.windSpeed);
weatherParameterValue += " m/sec";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_WIND_DIRECTION_IN_DEGREES)
{
weatherParameterValue = String(format:"%.1f",self.weather.windDirectionInDegrees);
weatherParameterValue += " degrees";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_HUMIDITY)
{
weatherParameterValue = String(format:"%.1f",self.weather.humidity);
weatherParameterValue += "%";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_PRESSURE)
{
weatherParameterValue = String(format:"%.1f",self.weather.pressure);
weatherParameterValue += " hPa";
}
else if(weatherParameter == WEATHER_DETAIL_KEY_TEMP)
{
//For Kelvin
// weatherParameterValue = String(format:"%.2f",self.weather.temeperature.overAllTemp);
// weatherParameterValue += " Kelvin";
//For Celsius
weatherParameterValue = String(format:"%.2f",self.getCelsiusForKelvin(self.weather.temeperature.overAllTemp));
weatherParameterValue += " Celsius";
}
return weatherParameterValue;
}
func getCelsiusForKelvin(_ tempInKelvin: Double) -> Double
{
let tempInCelsius: Double = tempInKelvin - 273.15;
return tempInCelsius;
}
//Tap geture recognizer callback
@IBAction func collapsableCellTapped(_ sender: AnyObject)
{
if(isTemperatureCellCollapsed)
{
tempCellHeight = 204.0;
isTemperatureCellCollapsed = false;
}
else
{
tempCellHeight = 44.0
isTemperatureCellCollapsed = true;
}
// isTemperatureCellCollapsed != isTemperatureCellCollapsed;
// weatherDetailsTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top);
weatherDetailsTableView.reloadData();
}
//UITableView datasource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return weatherParameters.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let weatherParameter = weatherParameters[(indexPath as NSIndexPath).row];
if(weatherParameter != WEATHER_DETAIL_KEY_TEMP)
{
let cell = weatherDetailsTableView.dequeueReusableCell(withIdentifier: "WeatherParameterCell") ;
cell!.textLabel?.text = weatherParameter;
let weatherParameterValue = self.getValueForWeatherParameter(weatherParameter);
cell!.detailTextLabel?.text = weatherParameterValue;
cell!.selectionStyle = UITableViewCellSelectionStyle.none;
cell!.accessoryType = UITableViewCellAccessoryType.none;
return cell!;
}
else
{
let cell: CollapsableTableViewCell = weatherDetailsTableView.dequeueReusableCell(withIdentifier: "WeatherParameterCollapsableCell") as! CollapsableTableViewCell;
cell.setSelectedDayTemperature(self.weather.temeperature);
cell.textLbl.text = weatherParameter;
let weatherParameterValue = self.getValueForWeatherParameter(weatherParameter);
cell.detailTextLbl.text = weatherParameterValue;
cell.addGestureRecognizer(cellTapGestureRecognizer);
cell.selectionStyle = UITableViewCellSelectionStyle.none;
cell.accessoryType = UITableViewCellAccessoryType.none;
UIView.animate(withDuration: TimeInterval(0.8), delay: TimeInterval(0.0), options: [], animations: { () -> Void in
cell.temperatureDetailsTableView.isHidden = self.isTemperatureCellCollapsed;
return;
}, completion: { (finished: Bool) -> Void in
var img: UIImage;
if(self.isTemperatureCellCollapsed)
{
img = UIImage(named: "CollapseArrow")!;
}
else
{
img = UIImage(named: "ExpandArrow")!;
}
cell.expandCollapseArrowImageView.image = img;
})
return cell;
}
}
//UITableView delegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
var cellHeight: CGFloat = 44.0;
let weatherParameter = weatherParameters[(indexPath as NSIndexPath).row];
if(weatherParameter == WEATHER_DETAIL_KEY_TEMP)
{
cellHeight = tempCellHeight;
}
return cellHeight;
}
/*
// 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
|
5f018c7f89f2501af3b946a080417ac6
| 38.554974 | 274 | 0.637591 | 5.253825 | false | false | false | false |
ifels/swiftDemo
|
RealmDemo/RealmDemo/ViewController.swift
|
1
|
2878
|
//
// ViewController.swift
// RealmDemo
//
// Created by 聂鑫鑫 on 16/11/14.
// Copyright © 2016年 ifels. All rights reserved.
//
import UIKit
import RealmSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
testRealm()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func testRealm(){
print("testRealm...")
do {
try FileManager.default.removeItem(at: Realm.Configuration.defaultConfiguration.fileURL!)
} catch {}
// Realms are used to group data together
let realm = try! Realm() // Create realm pointing to default file
print("testRealm2...")
// Set & read properties
let dog1 = Dog()
dog1.name = "dog1"
dog1.age = 9
let dog2 = Dog()
dog2.name = "dog2"
dog2.age = 10
let dog3 = Dog()
dog3.name = "dog3"
dog3.age = 11
let dog4 = Dog()
dog4.name = "dog4"
dog4.age = 5
// Link objects
let person = Person()
person.name = "Tim"
person.dogs.append(dog1)
person.dogs.append(dog2)
let person2 = Person()
person2.name = "Tom"
person2.dogs.append(dog3)
person2.dogs.append(dog4)
try! realm.write {
realm.add(person)
realm.add(person2)
}
let result = realm.objects(Person.self)
let dogs = result.first?.dogs
if dogs != nil {
print("dogs.size = \(dogs!.count)")
for d in dogs!{
print("d.name = \(d.name)")
}
}
// Multi-threading
//DispatchQueue.global().async {
var personalResults = realm.objects(Person.self).sorted(byProperty: "name", ascending: true)
print("Number of personals \(personalResults.count)")
var dp : Person?
for p in personalResults {
print("p.id = \(p.id)")
dp = p
}
var dogResults = realm.objects(Dog.self).filter(NSPredicate(format: "age >= 5"))
print("Number of dogs \(dogResults.count)")
//}
try! realm.write {
if dp != nil {
realm.delete(dp!)
}
}
personalResults = realm.objects(Person.self)
print("2. Number of personals \(personalResults.count)")
dogResults = realm.objects(Dog.self).filter(NSPredicate(format: "age >= 5"))
print("2. Number of dogs \(dogResults.count)")
}
}
|
apache-2.0
|
019d55059fc92790cd2cc8e72ad29c3e
| 25.813084 | 101 | 0.520042 | 4.34697 | false | false | false | false |
moqada/swift-sandbox
|
tutorials/FoodTracker/FoodTracker/RatingControl.swift
|
1
|
2380
|
//
// RatingControl.swift
// FoodTracker
//
// Created by Masahiko Okada on 2015/10/03.
//
//
import UIKit
class RatingControl: UIView {
// MARK: Properties
let spacing = 5
let stars = 5
var rating = 0 {
didSet {
setNeedsLayout()
}
}
var ratingButtons = [UIButton]()
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let filledStarImage = UIImage(named: "filledStar")
let emptyStarImage = UIImage(named: "emptyStar")
for _ in 0..<stars {
let button = UIButton()
button.setImage(emptyStarImage, forState: .Normal)
button.setImage(filledStarImage, forState: .Selected)
button.setImage(filledStarImage, forState: [.Highlighted, .Selected])
button.adjustsImageWhenHighlighted = false
button.addTarget(self, action: "ratingButtonTapped:", forControlEvents: .TouchDown)
ratingButtons += [button]
addSubview(button)
}
}
override func intrinsicContentSize() -> CGSize {
let buttonSize = Int(frame.size.height)
let width = (buttonSize + spacing) * stars
return CGSize(width: width, height: buttonSize)
}
override func layoutSubviews() {
// Set the button's width and height to a square the size of the frame's height.
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)
// Offset each button's origin by the length of the button plus spacing.
for (index, button) in ratingButtons.enumerate() {
buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing))
button.frame = buttonFrame
}
updateButtonSelectionStates()
}
// MARK: Button Action
func ratingButtonTapped(button: UIButton) {
rating = ratingButtons.indexOf(button)! + 1
updateButtonSelectionStates()
}
func updateButtonSelectionStates() {
print("updateButtonSelectionStates")
for (index, button) in ratingButtons.enumerate() {
// If the index of a button is less than the rating, that button should be selected.
print(index < rating)
button.selected = index < rating
}
}
}
|
mit
|
0fd2bda28dc9c47cfd2c8a4dc04bd8f5
| 29.512821 | 96 | 0.614706 | 4.750499 | false | false | false | false |
RoverPlatform/rover-ios-beta
|
Sources/Models/Height.swift
|
2
|
1021
|
//
// Height.swift
// Rover
//
// Created by Sean Rucker on 2018-04-16.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
public enum Height {
case intrinsic
case `static`(value: Double)
}
// MARK: Decodable
extension Height: Decodable {
private enum CodingKeys: String, CodingKey {
case typeName = "__typename"
case value
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let typeName = try container.decode(String.self, forKey: .typeName)
switch typeName {
case "HeightIntrinsic":
self = .intrinsic
case "HeightStatic":
let value = try container.decode(Double.self, forKey: .value)
self = .static(value: value)
default:
throw DecodingError.dataCorruptedError(forKey: CodingKeys.typeName, in: container, debugDescription: "Expected on of HeightIntrinsic or HeightStatic - found \(typeName)")
}
}
}
|
mit
|
a1c0af9069d5c22cd7be7566ca3dea74
| 29 | 182 | 0.642157 | 4.396552 | false | false | false | false |
THREDOpenSource/SYNUtils
|
SYNUtils/SYNUtils/Extensions/CGRect+Utils.swift
|
2
|
1802
|
//
// CGRect+Utils.swift
// SYNUtils
//
// Created by John Hurliman on 6/23/15.
// Copyright (c) 2015 Syntertainment. All rights reserved.
//
import CoreGraphics
extension CGRect {
/// Get the rectangle's midpoint
public var center: CGPoint {
return CGPoint(x: CGRectGetMidX(self), y: CGRectGetMidY(self))
}
/// Scales this rectangle to fill another rectangle. Some portion of this
/// rectangle may extend beyond the bounds of the target rectangle to fill
/// the target rectangle
///
/// CGRectMake(0, 0, 4, 5).aspectFill(CGRectMake(0, 0, 100, 100)) // Returns { 0, -12.5, 100, 125 }
///
/// :param: toRect Target rectangle to fill
/// :returns: A copy of this rectangle, scaled to fill the target rectangle
public func aspectFill(toRect: CGRect) -> CGRect {
let size = self.size.aspectFill(toRect.size)
return CGRect(
x: (toRect.size.width - size.width) * 0.5,
y: (toRect.size.height - size.height) * 0.5,
width: size.width,
height: size.height
)
}
/// Scales this rectangle to fill the interior of another rectangle while
/// maintaining this rectangle's aspect ratio
///
/// CGRectMake(0, 0, 4, 5).aspectFit(CGRectMake(0, 0, 100, 100)) // Returns { 10, 0, 80, 100 }
///
/// :param: toRect Target rectangle to fit inside of
/// :returns: A copy of this rectangle, scaled to fit the target rectangle
public func aspectFit(toRect: CGRect) -> CGRect {
let size = self.size.aspectFit(toRect.size)
var origin = toRect.origin
origin.x += (toRect.size.width - size.width) * 0.5
origin.y += (toRect.size.height - size.height) * 0.5
return CGRect(origin: origin, size: size)
}
}
|
mit
|
d7be2af702a2ab1642325b12369b1cb0
| 35.77551 | 105 | 0.619867 | 3.917391 | false | false | false | false |
jad6/DataStore
|
DataStore/DatStore-CommonTests/DataStoreBackgroundQueueTests.swift
|
1
|
17435
|
//
// DataStoreBackgroundQueueTests.swift
// DataStore
//
// Created by Jad Osseiran on 13/11/2014.
// Copyright (c) 2015 Jad Osseiran. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import XCTest
import CoreData
import DataStore
class DataStoreBackgroundQueueTests: DataStoreTests, DataStoreOperationTests {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
// MARK: Creating
func testCreating() {
let expectation = expectationWithDescription("Inserted")
dataStore.performBackgroundClosure() { [weak self] context in
guard self != nil else {
XCTFail()
return
}
var insertedPerson: DSTPerson?
let entityName = self!.dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "Jad"
person.lastName = "Osseiran"
insertedPerson = person
}
XCTAssertEqual(insertedPerson?.firstName, "Jad")
XCTAssertEqual(insertedPerson?.lastName, "Osseiran")
XCTAssertTrue(context.hasChanges)
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: defaultHandler)
}
func testCreatingAndSave() {
let expectation = expectationWithDescription("Inserted and save")
dataStore.performBackgroundClosureAndSave({ [weak self] context in
guard self != nil else {
XCTFail()
return
}
let entityName = self!.dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "Jad"
person.lastName = "Osseiran"
}
}, completion: { context, error in
XCTAssertFalse(context.hasChanges)
XCTAssertNil(error)
expectation.fulfill()
})
waitForExpectationsWithTimeout(defaultTimeout, handler: defaultHandler)
}
func testCreatingAndWait() {
var insertedPerson: DSTPerson?
dataStore.performBackgroundClosureAndWait() { [unowned self] context in
let entityName = self.dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "Jad"
person.lastName = "Osseiran"
insertedPerson = person
}
}
XCTAssertEqual(insertedPerson?.firstName, "Jad")
XCTAssertEqual(insertedPerson?.lastName, "Osseiran")
XCTAssertTrue(dataStore.backgroundManagedObjectContext.hasChanges)
}
func testCreatingWaitAndSave() {
do {
try dataStore.performBackgroundClosureWaitAndSave({ [unowned self] context in
let entityName = self.dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "Jad"
person.lastName = "Osseiran"
}
})
} catch let error {
XCTFail("Insertion failed \(error)")
}
XCTAssertFalse(dataStore.backgroundManagedObjectContext.hasChanges)
}
// MARK: Synchrnous Tests
func testFetchingExistingSync() {
let entityName = dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
do {
try dataStore.performBackgroundClosureWaitAndSave({ context in
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "Jad"
person.lastName = "Osseiran"
}
})
} catch let error {
XCTFail("Insertion failed \(error)")
}
var person: DSTPerson!
dataStore.performBackgroundClosureAndWait() { context in
do {
let predicate = NSPredicate(format: "firstName == \"Jad\" AND lastName == \"Osseiran\"")
let results = try context.findEntitiesForEntityName(entityName, withPredicate: predicate) as! [DSTPerson]
XCTAssertEqual(results.count, 1, "Only one person was inserted")
person = results.last!
} catch let error {
XCTFail("Fetch failed \(error)")
}
}
XCTAssertEqual(person.firstName, "Jad")
XCTAssertEqual(person.lastName, "Osseiran")
XCTAssertFalse(dataStore.backgroundManagedObjectContext.hasChanges)
}
func testFetchingNonExistingSync() {
let entityName = dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
do {
try dataStore.performBackgroundClosureWaitAndSave({ context in
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "Jad"
person.lastName = "Osseiran"
}
})
} catch let error {
XCTFail("Insertion failed \(error)")
}
dataStore.performBackgroundClosureAndWait() { context in
do {
let predicate = NSPredicate(format: "firstName == \"Nils\" AND lastName == \"Osseiran\"")
let results = try context.findEntitiesForEntityName(entityName, withPredicate: predicate) as! [DSTPerson]
XCTAssertEqual(results.count, 0, "There should be no matches")
} catch let error {
XCTFail("Fetch failed \(error)")
}
}
XCTAssertFalse(dataStore.backgroundManagedObjectContext.hasChanges)
}
func testFetchingWithValueAndKeySync() {
let entityName = dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
do {
try dataStore.performBackgroundClosureWaitAndSave({ context in
let results: [AnyObject]?
do {
results = try context.findOrInsertEntitiesWithEntityName(entityName,
whereKey: "firstName",
equalsValue: "Jad") { insertedObject, inserted in
let person = insertedObject as? DSTPerson
person?.firstName = "Jad"
person?.lastName = "Osseiran"
XCTAssertTrue(inserted)
}
} catch let error {
XCTFail("Insertion failed \(error)")
results = nil
}
XCTAssertNotNil(results)
XCTAssertEqual(results?.count, 1, "No matches should exist")
})
} catch let error {
XCTFail("Save failed \(error)")
}
var person: DSTPerson!
dataStore.performBackgroundClosureAndWait() { context in
do {
let predicate = NSPredicate(format: "firstName == \"Jad\" AND lastName == \"Osseiran\"")
let results = try context.findEntitiesForEntityName(entityName, withPredicate: predicate) as! [DSTPerson]
XCTAssertEqual(results.count, 1, "Only one person was inserted")
person = results.last
} catch let error {
XCTFail("Fetch failed \(error)")
}
}
XCTAssertEqual(person.firstName, "Jad")
XCTAssertEqual(person.lastName, "Osseiran")
XCTAssertFalse(dataStore.backgroundManagedObjectContext.hasChanges)
}
func testFetchingWithOrderSync() {
let entityName = dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
let smallNumber = 10
do {
try dataStore.performBackgroundClosureWaitAndSave({ [unowned self] context in
let entityName = self.dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
for i in 0 ..< smallNumber {
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "\(i)"
person.lastName = "\(i*2)"
}
}
})
} catch let error {
XCTFail("Insertion failed \(error)")
}
var fetchedConcatinatedFirstNameString = String()
dataStore.performBackgroundClosureAndWait() { context in
do {
let sortDescriptor = NSSortDescriptor(key: "firstName", ascending: false)
let results = try context.findEntitiesForEntityName(entityName, withPredicate: nil, andSortDescriptors: [sortDescriptor]) as! [DSTPerson]
XCTAssertEqual(results.count, smallNumber, "The count does not match")
for person in results {
fetchedConcatinatedFirstNameString += person.firstName!
}
} catch let error {
XCTFail("Fetch failed \(error)")
}
}
XCTAssertEqual("9876543210", fetchedConcatinatedFirstNameString)
XCTAssertFalse(dataStore.backgroundManagedObjectContext.hasChanges)
}
// MARK: Asynchrnous Tests
func testFetchingExistingAsync() {
let expectation = expectationWithDescription("Fetch existing")
let entityName = dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
dataStore.performBackgroundClosureAndSave({ context in
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "Jad"
person.lastName = "Osseiran"
}
}, completion: { context, error in
XCTAssertNil(error)
do {
let predicate = NSPredicate(format: "firstName == \"Jad\" AND lastName == \"Osseiran\"")
let results = try context.findEntitiesForEntityName(entityName, withPredicate: predicate) as! [DSTPerson]
XCTAssertEqual(results.count, 1, "Only one person was inserted")
let person = results.last!
XCTAssertEqual(person.firstName, "Jad")
XCTAssertEqual(person.lastName, "Osseiran")
XCTAssertFalse(context.hasChanges)
} catch let fetchError {
XCTFail("Fetch failed \(fetchError)")
}
expectation.fulfill()
})
waitForExpectationsWithTimeout(defaultTimeout, handler: defaultHandler)
}
func testFetchingNonExistingAsync() {
let expectation = expectationWithDescription("Fetch Non-existing")
let entityName = dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
dataStore.performBackgroundClosureAndSave({ context in
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "Jad"
person.lastName = "Osseiran"
}
}, completion: { context, error in
XCTAssertNil(error)
do {
let predicate = NSPredicate(format: "firstName == \"Nils\" AND lastName == \"Osseiran\"")
let results = try context.findEntitiesForEntityName(entityName, withPredicate: predicate) as! [DSTPerson]
XCTAssertEqual(results.count, 0)
XCTAssertFalse(context.hasChanges)
} catch let fetchError {
XCTFail("Fetch failed \(fetchError)")
}
expectation.fulfill()
})
waitForExpectationsWithTimeout(defaultTimeout, handler: defaultHandler)
}
func testFetchingWithValueAndKeyAsync() {
let expectation = expectationWithDescription("Fetch existing key-value")
let entityName = dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
dataStore.performBackgroundClosureAndSave({ context in
do {
try context.findOrInsertEntitiesWithEntityName(entityName, whereKey: "firstName", equalsValue: "Jad") { insertedObject, inserted in
let person = insertedObject as? DSTPerson
person?.firstName = "Jad"
person?.lastName = "Osseiran"
XCTAssertTrue(inserted)
}
} catch let error {
XCTFail("Insertion failed \(error)")
}
}, completion: { context, error in
XCTAssertNil(error)
do {
let predicate = NSPredicate(format: "firstName == \"Jad\" AND lastName == \"Osseiran\"")
let results = try context.findEntitiesForEntityName(entityName, withPredicate: predicate) as! [DSTPerson]
XCTAssertEqual(results.count, 1, "Only one person was inserted")
let person = results.last!
XCTAssertEqual(person.firstName, "Jad")
XCTAssertEqual(person.lastName, "Osseiran")
XCTAssertFalse(context.hasChanges)
} catch let fetchError {
XCTFail("Fetch failed \(fetchError)")
}
expectation.fulfill()
})
waitForExpectationsWithTimeout(defaultTimeout, handler: defaultHandler)
}
func testFetchingWithOrderAsync() {
let expectation = expectationWithDescription("Fetch in order")
let smallNumber = 10
let entityName = dataStore.entityNameForObjectClass(DSTPerson.self, withClassPrefix: "DST")
dataStore.performBackgroundClosureAndSave({ context in
for i in 0 ..< smallNumber {
context.insertObjectWithEntityName(entityName) { object in
let person = object as! DSTPerson
person.firstName = "\(i)"
person.lastName = "\(i*2)"
}
}
}, completion: { context, error in
XCTAssertNil(error)
do {
let sortDescriptor = NSSortDescriptor(key: "firstName", ascending: false)
let results = try context.findEntitiesForEntityName(entityName, withPredicate: nil, andSortDescriptors: [sortDescriptor]) as! [DSTPerson]
var fetchedConcatinatedFirstNameString = String()
for person in results {
fetchedConcatinatedFirstNameString += person.firstName!
}
XCTAssertEqual(results.count, smallNumber)
XCTAssertEqual("9876543210", fetchedConcatinatedFirstNameString)
XCTAssertFalse(context.hasChanges)
} catch let fetchError {
XCTFail("Fetch failed \(fetchError)")
}
expectation.fulfill()
})
waitForExpectationsWithTimeout(defaultTimeout, handler: defaultHandler)
}
}
|
bsd-2-clause
|
68347246071aafc5735ff2649c3119c1
| 40.315166 | 153 | 0.583482 | 6.176054 | false | false | false | false |
StreamOneNL/AppleTV-Demo
|
AppleTV-Demo/MainTabBarController.swift
|
1
|
1855
|
//
// MainTabBarController.swift
// AppleTV-Demo
//
// Created by Nicky Gerritsen on 27-12-15.
// Copyright © 2015 StreamOne. All rights reserved.
//
import UIKit
class MainTabBarController: UITabBarController {
var livestreams: [LiveStream] = []
override func viewDidLoad() {
super.viewDidLoad()
loadLiveStreams()
}
func loadLiveStreams() {
guard let firstVc = self.viewControllers?[0] else {
return
}
self.viewControllers = [firstVc]
ApiManager.loadLiveStreams { result in
switch result {
case .Error:
self.displayLoadingErrorAlert()
case .Success(let livestreams):
do {
self.livestreams = try livestreams.filter { try ApiManager.gemiststreams().contains($0.id) }
for livestream in self.livestreams {
if let vc = R.storyboard.main.itemsViewController() {
vc.livestream = livestream
vc.tabBarItem.title = "Gemist voor \(livestream.title)"
self.viewControllers?.append(vc)
}
}
if try ApiManager.showaccounttab() {
if let vc = R.storyboard.main.itemsViewController() {
vc.tabBarItem.title = "Gemist"
self.viewControllers?.append(vc)
}
}
} catch {
self.displayLoadingErrorAlert()
}
}
}
}
private func displayLoadingErrorAlert() {
let title = "Kan live niet laden"
let message = "Probeer het a.u.b. opnieuw"
displayOKAlert(title, message: message)
}
}
|
mit
|
2b0780f05423cbcc0cbbc1503beffb14
| 27.96875 | 112 | 0.510248 | 4.790698 | false | false | false | false |
Connorrr/ParticleAlarm
|
IOS/Carthage/Checkouts/spark-setup-ios/Carthage/Checkouts/onepassword-extension/Demos/App Demo for iOS Swift/App Demo for iOS Swift/LoginViewController.swift
|
4
|
2896
|
//
// LoginViewController.swift
// App Demo for iOS Swift
//
// Created by Rad Azzouz on 2015-05-14.
// Copyright (c) 2015 Agilebits. All rights reserved.
//
import Foundation
class LoginViewController: UIViewController {
@IBOutlet weak var onepasswordButton: UIButton!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var oneTimePasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
if let patternImage = UIImage(named: "login-background.png") {
self.view.backgroundColor = UIColor(patternImage: patternImage)
}
self.onepasswordButton.hidden = (false == OnePasswordExtension.sharedExtension().isAppExtensionAvailable())
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if OnePasswordExtension.sharedExtension().isAppExtensionAvailable() == false {
let alertController = UIAlertController(title: "1Password is not installed", message: "Get 1Password from the App Store", preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "Get 1Password", style: .Default) { (action) in UIApplication.sharedApplication().openURL(NSURL(string: "https://itunes.apple.com/app/1password-password-manager/id568903335")!)
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
@IBAction func findLoginFrom1Password(sender:AnyObject) -> Void {
OnePasswordExtension.sharedExtension().findLoginForURLString("https://www.acme.com", forViewController: self, sender: sender, completion: { (loginDictionary, error) -> Void in
if loginDictionary == nil {
if error!.code != Int(AppExtensionErrorCodeCancelledByUser) {
print("Error invoking 1Password App Extension for find login: \(error)")
}
return
}
self.usernameTextField.text = loginDictionary?[AppExtensionUsernameKey] as? String
self.passwordTextField.text = loginDictionary?[AppExtensionPasswordKey] as? String
if let generatedOneTimePassword = loginDictionary?[AppExtensionTOTPKey] as? String {
self.oneTimePasswordTextField.hidden = false
self.oneTimePasswordTextField.text = generatedOneTimePassword
// Important: It is recommended that you submit the OTP/TOTP to your validation server as soon as you receive it, otherwise it may expire.
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue(), { () -> Void in
self.performSegueWithIdentifier("showThankYouViewController", sender: self)
})
}
})
}
}
|
mit
|
5cb63f5ee33cff12f07d748beb176900
| 38.671233 | 215 | 0.759669 | 4.25257 | false | false | false | false |
steelwheels/Canary
|
UnitTest/UnitTest/UTText.swift
|
1
|
1254
|
/**
* @file UTText.swift
* @brief Unit test for CNText class
* @par Copyright
* Copyright (C) 2017 Steel Wheels Project
*/
import Canary
import Foundation
public func UTText() -> Bool
{
let console = CNConsole()
let line0 = CNTextLine(string: "")
print(console: console, title: "Empty line", text: line0)
line0.append(string: "ABCD")
print(console: console, title: "Append \"ABCD\"to line", text: line0)
let section0 = CNTextSection()
print(console: console, title: "Empty section", text: section0)
section0.add(text: line0)
section0.add(string: ", EFGH")
section0.addMultiLines(string: "1\n2\n3\n4")
section0.append(string: "5")
print(console: console, title: "Add line0", text: section0)
let text1 = CNAddStringToText(text: line0, string: "Hello")
let text2 = CNAddStringToText(text: text1, string: "World")
print(console: console, title: "CNAddStringToText", text: text2)
let text3 = CNAddStringsToText(text: CNTextLine(string: "abcd"), strings: ["Hello", ",World"])
print(console: console, title: "CNAddStringsToText", text: text3)
return true
}
private func print(console cons: CNConsole, title ttl: String, text txt: CNText)
{
cons.print(string: "***** \(ttl) *****\n")
txt.print(console: cons, indent: 0)
}
|
gpl-2.0
|
946681499caac9d6781359dfd9a4bdc3
| 27.5 | 95 | 0.699362 | 3.007194 | false | false | false | false |
dclelland/HOWL
|
Pods/ProtonomeAudioKitControls/Classes/Plots/AudioPlot.swift
|
2
|
5605
|
//
// AudioPlot.swift
// ProtonomeAudioKitControls
//
// Created by Daniel Clelland on 5/12/15.
// Copyright © 2015 Daniel Clelland. All rights reserved.
//
import UIKit
#if !TARGET_INTERFACE_BUILDER
import AudioKit
#endif
/// IBDesignable `UIControl` subclass which draws the current CSound buffer as a waveform in `drawRect:`.
@IBDesignable open class AudioPlot: UIControl {
// MARK: - Parameters
// MARK: State
@IBInspectable override open var isSelected: Bool {
didSet {
setNeedsDisplay()
}
}
@IBInspectable override open var isHighlighted: Bool {
didSet {
setNeedsDisplay()
}
}
// MARK: Scale
/// The factor by which the waveform is scaled vertically. Defaults to 1.0.
@IBInspectable open var plotScale: CGFloat = 1.0 {
didSet {
setNeedsDisplay()
}
}
// MARK: Color
/// The hue used to draw the background and waveform. Defaults to 0.0.
@IBInspectable open var colorHue: CGFloat = 0.0 {
didSet {
setNeedsDisplay()
}
}
/// The saturation used to draw the background and waveform. Defaults to 0.0.
@IBInspectable open var colorSaturation: CGFloat = 1.0 {
didSet {
setNeedsDisplay()
}
}
// MARK: Corner radius
/// The control's corner radius. The radius given to the rounded rect created in `drawRect:`.
@IBInspectable open var cornerRadius: CGFloat = 0.0 {
didSet {
setNeedsLayout()
}
}
// MARK: - Private vars
fileprivate var data = Data()
fileprivate var samples = [Float]() {
didSet {
setNeedsDisplay()
}
}
#if !TARGET_INTERFACE_BUILDER
fileprivate var csound: CsoundObj?
#endif
// MARK: - Initialization
deinit {
#if !TARGET_INTERFACE_BUILDER
AKManager.removeBinding(self)
#endif
}
// MARK: - Overrides
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
var testSamples = [Float](repeating: 0.0, count: 512)
for index in testSamples.indices {
testSamples[index] = sin(Float(index / 2) / 256.0 * (2.0 * .pi))
}
samples = testSamples
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
#if !TARGET_INTERFACE_BUILDER
if (superview == nil) {
AKManager.removeBinding(self)
} else {
AKManager.addBinding(self)
}
#endif
}
override open func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
context.clear(rect)
context.setFillColor(backgroundPathColor.cgColor)
backgroundPath.fill()
backgroundPath.addClip()
context.setFillColor(foregroundPathColor.cgColor)
foregroundPath.fill()
}
// MARK: - Private getters
private var backgroundPath: UIBezierPath {
return UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
}
private var foregroundPath: UIBezierPath {
let path = CGMutablePath()
let length = samples.count / 2
for i in 0..<length {
let sample = CGFloat(samples[i * 2])
let safeSample = sample.isNaN ? 0.0 : sample
let x = CGFloat(i) / CGFloat(length - 1)
let y = safeSample.lerp(min: 0.5, max: 0.5 + plotScale * 0.5)
let location = CGPoint(x: x, y: y).lerp(rect: bounds)
if (i == 0) {
path.move(to: location)
} else {
path.addLine(to: location)
}
}
for i in (0..<length).reversed() {
let sample = CGFloat(samples[i * 2 + 1])
let safeSample = sample.isNaN ? 0.0 : sample
let x = CGFloat(i) / CGFloat(length - 1)
let y = safeSample.lerp(min: 0.5, max: 0.5 - plotScale * 0.5)
let location = CGPoint(x: x, y: y).lerp(rect: bounds)
path.addLine(to: location)
}
if length > 0 {
path.closeSubpath()
}
return UIBezierPath(cgPath: path)
}
private var backgroundPathColor: UIColor {
switch (isHighlighted, isSelected) {
case (true, _):
return .protonomeMedium(hue: colorHue, saturation: colorSaturation)
case (_, true):
return .protonomeDark(hue: colorHue, saturation: colorSaturation)
default:
return .protonomeDarkGray
}
}
private var foregroundPathColor: UIColor {
return .protonomeLight(hue: colorHue, saturation: colorSaturation)
}
}
#if !TARGET_INTERFACE_BUILDER
extension AudioPlot: CsoundBinding {
open func setup(_ csoundObj: CsoundObj) {
csound = csoundObj
}
open func updateValuesFromCsound() {
guard let csound = csound else {
return
}
data = csound.getOutSamples()
var samples = [Float](repeating: 0.0, count: data.count / MemoryLayout<Float>.size)
(data as NSData).getBytes(&samples, length:data.count)
DispatchQueue.main.async {
self.samples = samples
}
}
}
#endif
|
mit
|
3bc401ab8881a728a4a0f648ae13b573
| 24.706422 | 105 | 0.551749 | 4.66223 | false | false | false | false |
tehprofessor/SwiftyFORM
|
Source/FormItems/ButtonFormItem.swift
|
1
|
734
|
//
// ButtonFormItem.swift
// SwiftyFORM
//
// Created by Simon Strandgaard on 20-06-15.
// Copyright © 2015 Simon Strandgaard. All rights reserved.
//
import Foundation
public class ButtonFormItem: FormItem {
override func accept(visitor: FormItemVisitor) {
visitor.visitButton(self)
}
public var title: String = ""
public var subtitle: String = ""
public func title(title: String, subtitle: String = "") -> Self {
self.title = title
self.subtitle = subtitle
return self
}
public var textAlignment: NSTextAlignment = NSTextAlignment.Left
public var detailAlignment: NSTextAlignment = NSTextAlignment.Right
public var styleBlock: ((ButtonCell) -> Void)? = nil
public var action: Void -> Void = {}
}
|
mit
|
5675c3d9781edf09bd798fc031939223
| 25.178571 | 69 | 0.71487 | 3.983696 | false | false | false | false |
Tylerflick/ImageDiff
|
ImageDiff/main.swift
|
1
|
1019
|
//
// main.swift
// ImageDiff
//
// Created by Tyler Hoeflicker on 7/6/17.
// Copyright © 2017 Tyler Hoeflicker. All rights reserved.
//
import Foundation
import MetalKit
func fileExists(path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
let arguments = CommandLine.arguments
if arguments.count < 5 {
fatalError("Arguments mismatch. Two input image paths, one output image path, c to specify CPU based or m to specify Metal based")
}
if !fileExists(path: arguments[1]) || !fileExists(path: arguments[2]) {
fatalError("Input file(s) do not exist")
}
print("Starting up ImageDiff")
let start = Date()
var differ : Differ
if arguments[4] == "m" {
differ = MetalDiffer()
} else if arguments[4] == "s" {
differ = SoftwareDiffer()
} else {
differ = CoreImageDiffer()
}
var diffs = differ.applyDiff(to: arguments[1], second: arguments[2], output: arguments[3])
let runtime = start.timeIntervalSinceNow
print("Total runtime (seconds): \(abs(runtime))")
exit(diffs)
|
apache-2.0
|
7d2e116c3427e9d75a686933ddfadc14
| 25.102564 | 134 | 0.702358 | 3.534722 | false | false | false | false |
ben-ng/swift
|
stdlib/public/core/String.swift
|
1
|
30400
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// FIXME: complexity documentation for most of methods on String is ought to be
// qualified with "amortized" at least, as Characters are variable-length.
/// A Unicode string value.
///
/// A string is a series of characters, such as `"Swift"`. Strings in Swift are
/// Unicode correct, locale insensitive, and designed to be efficient. The
/// `String` type bridges with the Objective-C class `NSString` and offers
/// interoperability with C functions that works with strings.
///
/// You can create new strings using string literals or string interpolations.
/// A string literal is a series of characters enclosed in quotes.
///
/// let greeting = "Welcome!"
///
/// String interpolations are string literals that evaluate any included
/// expressions and convert the results to string form. String interpolations
/// are an easy way to build a string from multiple pieces. Wrap each
/// expression in a string interpolation in parentheses, prefixed by a
/// backslash.
///
/// let name = "Rosa"
/// let personalizedGreeting = "Welcome, \(name)!"
///
/// let price = 2
/// let number = 3
/// let cookiePrice = "\(number) cookies: $\(price * number)."
///
/// Combine strings using the concatenation operator (`+`).
///
/// let longerGreeting = greeting + " We're glad you're here!"
/// print(longerGreeting)
/// // Prints "Welcome! We're glad you're here!"
///
/// Modifying and Comparing Strings
/// ===============================
///
/// Strings always have value semantics. Modifying a copy of a string leaves
/// the original unaffected.
///
/// var otherGreeting = greeting
/// otherGreeting += " Have a nice time!"
/// print(otherGreeting)
/// // Prints "Welcome! Have a nice time!"
///
/// print(greeting)
/// // Prints "Welcome!"
///
/// Comparing strings for equality using the equal-to operator (`==`) or a
/// relational operator (like `<` and `>=`) is always performed using the
/// Unicode canonical representation. This means that different
/// representations of a string compare as being equal.
///
/// let cafe1 = "Cafe\u{301}"
/// let cafe2 = "Café"
/// print(cafe1 == cafe2)
/// // Prints "true"
///
/// The Unicode code point `"\u{301}"` modifies the preceding character to
/// include an accent, so `"e\u{301}"` has the same canonical representation
/// as the single Unicode code point `"é"`.
///
/// Basic string operations are not sensitive to locale settings. This ensures
/// that string comparisons and other operations always have a single, stable
/// result, allowing strings to be used as keys in `Dictionary` instances and
/// for other purposes.
///
/// Representing Strings: Views
/// ===========================
///
/// A string is not itself a collection. Instead, it has properties that
/// present its contents as meaningful collections. Each of these collections
/// is a particular type of *view* of the string's visible and data
/// representation.
///
/// To demonstrate the different views available for every string, the
/// following examples use this `String` instance:
///
/// let cafe = "Cafe\u{301} du 🌍"
/// print(cafe)
/// // Prints "Café du 🌍"
///
/// Character View
/// --------------
///
/// A string's `characters` property is a collection of *extended grapheme
/// clusters*, which approximate human-readable characters. Many individual
/// characters, such as "é", "김", and "🇮🇳", can be made up of multiple Unicode
/// code points. These code points are combined by Unicode's boundary
/// algorithms into extended grapheme clusters, represented by Swift's
/// `Character` type. Each element of the `characters` view is represented by
/// a `Character` instance.
///
/// print(cafe.characters.count)
/// // Prints "9"
/// print(Array(cafe.characters))
/// // Prints "["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]"
///
/// Each visible character in the `cafe` string is a separate element of the
/// `characters` view.
///
/// Unicode Scalar View
/// -------------------
///
/// A string's `unicodeScalars` property is a collection of Unicode scalar
/// values, the 21-bit codes that are the basic unit of Unicode. Each scalar
/// value is represented by a `UnicodeScalar` instance and is equivalent to a
/// UTF-32 code unit.
///
/// print(cafe.unicodeScalars.count)
/// // Prints "10"
/// print(Array(cafe.unicodeScalars))
/// // Prints "["C", "a", "f", "e", "\u{0301}", " ", "d", "u", " ", "\u{0001F30D}"]"
/// print(cafe.unicodeScalars.map { $0.value })
/// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 127757]"
///
/// The `unicodeScalars` view's elements comprise each Unicode scalar value in
/// the `cafe` string. In particular, because `cafe` was declared using the
/// decomposed form of the `"é"` character, `unicodeScalars` contains the code
/// points for both the letter `"e"` (101) and the accent character `"´"`
/// (769).
///
/// UTF-16 View
/// -----------
///
/// A string's `utf16` property is a collection of UTF-16 code units, the
/// 16-bit encoding form of the string's Unicode scalar values. Each code unit
/// is stored as a `UInt16` instance.
///
/// print(cafe.utf16.count)
/// // Prints "11"
/// print(Array(cafe.utf16))
/// // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]"
///
/// The elements of the `utf16` view are the code units for the string when
/// encoded in UTF-16.
///
/// The elements of this collection match those accessed through indexed
/// `NSString` APIs.
///
/// let nscafe = cafe as NSString
/// print(nscafe.length)
/// // Prints "11"
/// print(nscafe.character(at: 3))
/// // Prints "101"
///
/// UTF-8 View
/// ----------
///
/// A string's `utf8` property is a collection of UTF-8 code units, the 8-bit
/// encoding form of the string's Unicode scalar values. Each code unit is
/// stored as a `UInt8` instance.
///
/// print(cafe.utf8.count)
/// // Prints "14"
/// print(Array(cafe.utf8))
/// // Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]"
///
/// The elements of the `utf8` view are the code units for the string when
/// encoded in UTF-8. This representation matches the one used when `String`
/// instances are passed to C APIs.
///
/// let cLength = strlen(cafe)
/// print(cLength)
/// // Prints "14"
///
/// Counting the Length of a String
/// ===============================
///
/// When you need to know the length of a string, you must first consider what
/// you'll use the length for. Are you measuring the number of characters that
/// will be displayed on the screen, or are you measuring the amount of
/// storage needed for the string in a particular encoding? A single string
/// can have greatly differing lengths when measured by its different views.
///
/// For example, an ASCII character like the capital letter *A* is represented
/// by a single element in each of its four views. The Unicode scalar value of
/// *A* is `65`, which is small enough to fit in a single code unit in both
/// UTF-16 and UTF-8.
///
/// let capitalA = "A"
/// print(capitalA.characters.count)
/// // Prints "1"
/// print(capitalA.unicodeScalars.count)
/// // Prints "1"
/// print(capitalA.utf16.count)
/// // Prints "1"
/// print(capitalA.utf8.count)
/// // Prints "1"
///
/// On the other hand, an emoji flag character is constructed from a pair of
/// Unicode scalars values, like `"\u{1F1F5}"` and `"\u{1F1F7}"`. Each of
/// these scalar values, in turn, is too large to fit into a single UTF-16 or
/// UTF-8 code unit. As a result, each view of the string `"🇵🇷"` reports a
/// different length.
///
/// let flag = "🇵🇷"
/// print(flag.characters.count)
/// // Prints "1"
/// print(flag.unicodeScalars.count)
/// // Prints "2"
/// print(flag.utf16.count)
/// // Prints "4"
/// print(flag.utf8.count)
/// // Prints "8"
///
/// To check whether a string is empty, use its `isEmpty` property instead
/// of comparing the length of one of the views to `0`. Unlike `isEmpty`,
/// calculating a view's `count` property requires iterating through the
/// elements of the string.
///
/// Accessing String View Elements
/// ==============================
///
/// To find individual elements of a string, use the appropriate view for your
/// task. For example, to retrieve the first word of a longer string, you can
/// search the `characters` view for a space and then create a new string from
/// a prefix of the `characters` view up to that point.
///
/// let name = "Marie Curie"
/// let firstSpace = name.characters.index(of: " ")!
/// let firstName = String(name.characters.prefix(upTo: firstSpace))
/// print(firstName)
/// // Prints "Marie"
///
/// You can convert an index into one of a string's views to an index into
/// another view.
///
/// let firstSpaceUTF8 = firstSpace.samePosition(in: name.utf8)
/// print(Array(name.utf8.prefix(upTo: firstSpaceUTF8)))
/// // Prints "[77, 97, 114, 105, 101]"
///
/// Performance Optimizations
/// =========================
///
/// Although strings in Swift have value semantics, strings use a copy-on-write
/// strategy to store their data in a buffer. This buffer can then be shared
/// by different copies of a string. A string's data is only copied lazily,
/// upon mutation, when more than one string instance is using the same
/// buffer. Therefore, the first in any sequence of mutating operations may
/// cost O(*n*) time and space.
///
/// When a string's contiguous storage fills up, a new buffer must be allocated
/// and data must be moved to the new storage. String buffers use an
/// exponential growth strategy that makes appending to a string a constant
/// time operation when averaged over many append operations.
///
/// Bridging between String and NSString
/// ====================================
///
/// Any `String` instance can be bridged to `NSString` using the type-cast
/// operator (`as`), and any `String` instance that originates in Objective-C
/// may use an `NSString` instance as its storage. Because any arbitrary
/// subclass of `NSString` can become a `String` instance, there are no
/// guarantees about representation or efficiency when a `String` instance is
/// backed by `NSString` storage. Because `NSString` is immutable, it is just
/// as though the storage was shared by a copy: The first in any sequence of
/// mutating operations causes elements to be copied into unique, contiguous
/// storage which may cost O(*n*) time and space, where *n* is the length of
/// the string's encoded representation (or more, if the underlying `NSString`
/// has unusual performance characteristics).
///
/// For more information about the Unicode terms used in this discussion, see
/// the [Unicode.org glossary][glossary]. In particular, this discussion
/// mentions [extended grapheme clusters][clusters],
/// [Unicode scalar values][scalars], and [canonical equivalence][equivalence].
///
/// [glossary]: http://www.unicode.org/glossary/
/// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster
/// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value
/// [equivalence]: http://www.unicode.org/glossary/#canonical_equivalent
///
/// - SeeAlso: `String.CharacterView`, `String.UnicodeScalarView`,
/// `String.UTF16View`, `String.UTF8View`
@_fixed_layout
public struct String {
/// Creates an empty string.
public init() {
_core = _StringCore()
}
public // @testable
init(_ _core: _StringCore) {
self._core = _core
}
public // @testable
var _core: _StringCore
}
extension String {
public // @testable
static func _fromWellFormedCodeUnitSequence<Encoding, Input>(
_ encoding: Encoding.Type, input: Input
) -> String
where
Encoding: UnicodeCodec,
Input: Collection,
Input.Iterator.Element == Encoding.CodeUnit {
return String._fromCodeUnitSequence(encoding, input: input)!
}
public // @testable
static func _fromCodeUnitSequence<Encoding, Input>(
_ encoding: Encoding.Type, input: Input
) -> String?
where
Encoding: UnicodeCodec,
Input: Collection,
Input.Iterator.Element == Encoding.CodeUnit {
let (stringBufferOptional, _) =
_StringBuffer.fromCodeUnits(input, encoding: encoding,
repairIllFormedSequences: false)
return stringBufferOptional.map { String(_storage: $0) }
}
public // @testable
static func _fromCodeUnitSequenceWithRepair<Encoding, Input>(
_ encoding: Encoding.Type, input: Input
) -> (String, hadError: Bool)
where
Encoding: UnicodeCodec,
Input: Collection,
Input.Iterator.Element == Encoding.CodeUnit {
let (stringBuffer, hadError) =
_StringBuffer.fromCodeUnits(input, encoding: encoding,
repairIllFormedSequences: true)
return (String(_storage: stringBuffer!), hadError)
}
}
extension String : _ExpressibleByBuiltinUnicodeScalarLiteral {
@effects(readonly)
public // @testable
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
self = String._fromWellFormedCodeUnitSequence(
UTF32.self, input: CollectionOfOne(UInt32(value)))
}
}
extension String : ExpressibleByUnicodeScalarLiteral {
/// Creates an instance initialized to the given Unicode scalar value.
///
/// Do not call this initializer directly. It may be used by the compiler when
/// you initialize a string using a string literal that contains a single
/// Unicode scalar value.
public init(unicodeScalarLiteral value: String) {
self = value
}
}
extension String : _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
@effects(readonly)
@_semantics("string.makeUTF8")
public init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1) {
self = String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(start),
count: Int(utf8CodeUnitCount)))
}
}
extension String : ExpressibleByExtendedGraphemeClusterLiteral {
/// Creates an instance initialized to the given extended grapheme cluster
/// literal.
///
/// Do not call this initializer directly. It may be used by the compiler when
/// you initialize a string using a string literal containing a single
/// extended grapheme cluster.
public init(extendedGraphemeClusterLiteral value: String) {
self = value
}
}
extension String : _ExpressibleByBuiltinUTF16StringLiteral {
@effects(readonly)
@_semantics("string.makeUTF16")
public init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word
) {
self = String(
_StringCore(
baseAddress: UnsafeMutableRawPointer(start),
count: Int(utf16CodeUnitCount),
elementShift: 1,
hasCocoaBuffer: false,
owner: nil))
}
}
extension String : _ExpressibleByBuiltinStringLiteral {
@effects(readonly)
@_semantics("string.makeUTF8")
public init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1) {
if Bool(isASCII) {
self = String(
_StringCore(
baseAddress: UnsafeMutableRawPointer(start),
count: Int(utf8CodeUnitCount),
elementShift: 0,
hasCocoaBuffer: false,
owner: nil))
}
else {
self = String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(start),
count: Int(utf8CodeUnitCount)))
}
}
}
extension String : ExpressibleByStringLiteral {
/// Creates an instance initialized to the given string value.
///
/// Do not call this initializer directly. It is used by the compiler when you
/// initialize a string using a string literal. For example:
///
/// let nextStop = "Clark & Lake"
///
/// This assignment to the `nextStop` constant calls this string literal
/// initializer behind the scenes.
public init(stringLiteral value: String) {
self = value
}
}
extension String : CustomDebugStringConvertible {
/// A representation of the string that is suitable for debugging.
public var debugDescription: String {
var result = "\""
for us in self.unicodeScalars {
result += us.escaped(asASCII: false)
}
result += "\""
return result
}
}
extension String {
/// Returns the number of code units occupied by this string
/// in the given encoding.
func _encodedLength<
Encoding: UnicodeCodec
>(_ encoding: Encoding.Type) -> Int {
var codeUnitCount = 0
self._encode(encoding, into: { _ in codeUnitCount += 1 })
return codeUnitCount
}
// FIXME: this function does not handle the case when a wrapped NSString
// contains unpaired surrogates. Fix this before exposing this function as a
// public API. But it is unclear if it is valid to have such an NSString in
// the first place. If it is not, we should not be crashing in an obscure
// way -- add a test for that.
// Related: <rdar://problem/17340917> Please document how NSString interacts
// with unpaired surrogates
func _encode<
Encoding: UnicodeCodec
>(
_ encoding: Encoding.Type,
into processCodeUnit: (Encoding.CodeUnit) -> Void
) {
return _core.encode(encoding, into: processCodeUnit)
}
}
// Support for copy-on-write
extension String {
/// Appends the given string to this string.
///
/// The following example builds a customized greeting by using the
/// `append(_:)` method:
///
/// var greeting = "Hello, "
/// if let name = getUserName() {
/// greeting.append(name)
/// } else {
/// greeting.append("friend")
/// }
/// print(greeting)
/// // Prints "Hello, friend"
///
/// - Parameter other: Another string.
public mutating func append(_ other: String) {
_core.append(other._core)
}
/// Appends the given Unicode scalar to the string.
///
/// - Parameter x: A Unicode scalar value.
///
/// - Complexity: Appending a Unicode scalar to a string averages to O(1)
/// over many additions.
@available(*, unavailable, message: "Replaced by append(_: String)")
public mutating func append(_ x: UnicodeScalar) {
Builtin.unreachable()
}
public // SPI(Foundation)
init(_storage: _StringBuffer) {
_core = _StringCore(_storage)
}
}
extension String {
@effects(readonly)
@_semantics("string.concat")
public static func + (lhs: String, rhs: String) -> String {
if lhs.isEmpty {
return rhs
}
var lhs = lhs
lhs._core.append(rhs._core)
return lhs
}
// String append
public static func += (lhs: inout String, rhs: String) {
if lhs.isEmpty {
lhs = rhs
}
else {
lhs._core.append(rhs._core)
}
}
/// Constructs a `String` in `resultStorage` containing the given UTF-8.
///
/// Low-level construction interface used by introspection
/// implementation in the runtime library.
@_silgen_name("swift_stringFromUTF8InRawMemory")
public // COMPILER_INTRINSIC
static func _fromUTF8InRawMemory(
_ resultStorage: UnsafeMutablePointer<String>,
start: UnsafeMutablePointer<UTF8.CodeUnit>,
utf8CodeUnitCount: Int
) {
resultStorage.initialize(to:
String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(start: start, count: utf8CodeUnitCount)))
}
}
extension Sequence where Iterator.Element == String {
/// Returns a new string by concatenating the elements of the sequence,
/// adding the given separator between each element.
///
/// The following example shows how an array of strings can be joined to a
/// single, comma-separated string:
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let list = cast.joined(separator: ", ")
/// print(list)
/// // Prints "Vivien, Marlon, Kim, Karl"
///
/// - Parameter separator: A string to insert between each of the elements
/// in this sequence. The default separator is an empty string.
/// - Returns: A single, concatenated string.
public func joined(separator: String = "") -> String {
var result = ""
// FIXME(performance): this code assumes UTF-16 in-memory representation.
// It should be switched to low-level APIs.
let separatorSize = separator.utf16.count
let reservation = self._preprocessingPass {
() -> Int in
var r = 0
for chunk in self {
// FIXME(performance): this code assumes UTF-16 in-memory representation.
// It should be switched to low-level APIs.
r += separatorSize + chunk.utf16.count
}
return r - separatorSize
}
if let n = reservation {
result.reserveCapacity(n)
}
if separatorSize == 0 {
for x in self {
result.append(x)
}
return result
}
var iter = makeIterator()
if let first = iter.next() {
result.append(first)
while let next = iter.next() {
result.append(separator)
result.append(next)
}
}
return result
}
}
#if _runtime(_ObjC)
@_silgen_name("swift_stdlib_NSStringLowercaseString")
func _stdlib_NSStringLowercaseString(_ str: AnyObject) -> _CocoaString
@_silgen_name("swift_stdlib_NSStringUppercaseString")
func _stdlib_NSStringUppercaseString(_ str: AnyObject) -> _CocoaString
#else
internal func _nativeUnicodeLowercaseString(_ str: String) -> String {
var buffer = _StringBuffer(
capacity: str._core.count, initialSize: str._core.count, elementWidth: 2)
// Allocation of a StringBuffer requires binding the memory to the correct
// encoding type.
let dest = buffer.start.bindMemory(
to: UTF16.CodeUnit.self, capacity: str._core.count)
// Try to write it out to the same length.
let z = _swift_stdlib_unicode_strToLower(
dest, Int32(str._core.count),
str._core.startUTF16, Int32(str._core.count))
let correctSize = Int(z)
// If more space is needed, do it again with the correct buffer size.
if correctSize != str._core.count {
buffer = _StringBuffer(
capacity: correctSize, initialSize: correctSize, elementWidth: 2)
let dest = buffer.start.bindMemory(
to: UTF16.CodeUnit.self, capacity: str._core.count)
_swift_stdlib_unicode_strToLower(
dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count))
}
return String(_storage: buffer)
}
internal func _nativeUnicodeUppercaseString(_ str: String) -> String {
var buffer = _StringBuffer(
capacity: str._core.count, initialSize: str._core.count, elementWidth: 2)
// Allocation of a StringBuffer requires binding the memory to the correct
// encoding type.
let dest = buffer.start.bindMemory(
to: UTF16.CodeUnit.self, capacity: str._core.count)
// Try to write it out to the same length.
let z = _swift_stdlib_unicode_strToUpper(
dest, Int32(str._core.count),
str._core.startUTF16, Int32(str._core.count))
let correctSize = Int(z)
// If more space is needed, do it again with the correct buffer size.
if correctSize != str._core.count {
buffer = _StringBuffer(
capacity: correctSize, initialSize: correctSize, elementWidth: 2)
let dest = buffer.start.bindMemory(
to: UTF16.CodeUnit.self, capacity: str._core.count)
_swift_stdlib_unicode_strToUpper(
dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count))
}
return String(_storage: buffer)
}
#endif
// Unicode algorithms
extension String {
// FIXME: implement case folding without relying on Foundation.
// <rdar://problem/17550602> [unicode] Implement case folding
/// A "table" for which ASCII characters need to be upper cased.
/// To determine which bit corresponds to which ASCII character, subtract 1
/// from the ASCII value of that character and divide by 2. The bit is set iff
/// that character is a lower case character.
internal var _asciiLowerCaseTable: UInt64 {
@inline(__always)
get {
return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
}
}
/// The same table for upper case characters.
internal var _asciiUpperCaseTable: UInt64 {
@inline(__always)
get {
return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000
}
}
/// Returns a lowercase version of the string.
///
/// Here's an example of transforming a string to all lowercase letters.
///
/// let cafe = "Café 🍵"
/// print(cafe.lowercased())
/// // Prints "café 🍵"
///
/// - Returns: A lowercase copy of the string.
///
/// - Complexity: O(*n*)
public func lowercased() -> String {
if let asciiBuffer = self._core.asciiBuffer {
let count = asciiBuffer.count
let source = asciiBuffer.baseAddress!
let buffer = _StringBuffer(
capacity: count, initialSize: count, elementWidth: 1)
let dest = buffer.start
for i in 0..<count {
// For each character in the string, we lookup if it should be shifted
// in our ascii table, then we return 0x20 if it should, 0x0 if not.
// This code is equivalent to:
// switch source[i] {
// case let x where (x >= 0x41 && x <= 0x5a):
// dest[i] = x &+ 0x20
// case let x:
// dest[i] = x
// }
let value = source[i]
let isUpper =
_asciiUpperCaseTable >>
UInt64(((value &- 1) & 0b0111_1111) >> 1)
let add = (isUpper & 0x1) << 5
// Since we are left with either 0x0 or 0x20, we can safely truncate to
// a UInt8 and add to our ASCII value (this will not overflow numbers in
// the ASCII range).
dest.storeBytes(of: value &+ UInt8(truncatingBitPattern: add),
toByteOffset: i, as: UInt8.self)
}
return String(_storage: buffer)
}
#if _runtime(_ObjC)
return _cocoaStringToSwiftString_NonASCII(
_stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl()))
#else
return _nativeUnicodeLowercaseString(self)
#endif
}
/// Returns an uppercase version of the string.
///
/// The following example transforms a string to uppercase letters:
///
/// let cafe = "Café 🍵"
/// print(cafe.uppercased())
/// // Prints "CAFÉ 🍵"
///
/// - Returns: An uppercase copy of the string.
///
/// - Complexity: O(*n*)
public func uppercased() -> String {
if let asciiBuffer = self._core.asciiBuffer {
let count = asciiBuffer.count
let source = asciiBuffer.baseAddress!
let buffer = _StringBuffer(
capacity: count, initialSize: count, elementWidth: 1)
let dest = buffer.start
for i in 0..<count {
// See the comment above in lowercaseString.
let value = source[i]
let isLower =
_asciiLowerCaseTable >>
UInt64(((value &- 1) & 0b0111_1111) >> 1)
let add = (isLower & 0x1) << 5
dest.storeBytes(of: value &- UInt8(truncatingBitPattern: add),
toByteOffset: i, as: UInt8.self)
}
return String(_storage: buffer)
}
#if _runtime(_ObjC)
return _cocoaStringToSwiftString_NonASCII(
_stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl()))
#else
return _nativeUnicodeUppercaseString(self)
#endif
}
/// Creates an instance from the description of a given
/// `LosslessStringConvertible` instance.
public init<T : LosslessStringConvertible>(_ value: T) {
self = value.description
}
}
extension String : CustomStringConvertible {
public var description: String {
return self
}
}
extension String : LosslessStringConvertible {
public init?(_ description: String) {
self = description
}
}
extension String {
@available(*, unavailable, renamed: "append(_:)")
public mutating func appendContentsOf(_ other: String) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "append(contentsOf:)")
public mutating func appendContentsOf<S : Sequence>(_ newElements: S)
where S.Iterator.Element == Character {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "insert(contentsOf:at:)")
public mutating func insertContentsOf<S : Collection>(
_ newElements: S, at i: Index
) where S.Iterator.Element == Character {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "replaceSubrange")
public mutating func replaceRange<C : Collection>(
_ subRange: Range<Index>, with newElements: C
) where C.Iterator.Element == Character {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "replaceSubrange")
public mutating func replaceRange(
_ subRange: Range<Index>, with newElements: String
) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "remove(at:)")
public mutating func removeAtIndex(_ i: Index) -> Character {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "removeSubrange")
public mutating func removeRange(_ subRange: Range<Index>) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "lowercased()")
public var lowercaseString: String {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "uppercased()")
public var uppercaseString: String {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "init(describing:)")
public init<T>(_: T) {
Builtin.unreachable()
}
}
extension Sequence where Iterator.Element == String {
@available(*, unavailable, renamed: "joined(separator:)")
public func joinWithSeparator(_ separator: String) -> String {
Builtin.unreachable()
}
}
|
apache-2.0
|
e517276b64061d9ed6ea9cdc15609838
| 33.137233 | 94 | 0.658363 | 4.16011 | false | false | false | false |
tnantoka/GameplayKitSandbox
|
GameplayKitSandbox/ExampleViewController.swift
|
1
|
1519
|
//
// ExampleViewController.swift
// GameplayKitSandbox
//
// Created by Tatsuya Tobioka on 2015/09/20.
// Copyright © 2015年 tnantoka. All rights reserved.
//
import UIKit
import SpriteKit
class ExampleViewController: UIViewController {
weak var skView: SKView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
edgesForExtendedLayout = UIRectEdge()
var frame = view.bounds
frame.size.height -= navigationController!.navigationBar.frame.height + UIApplication.shared.statusBarFrame.height
let skView = SKView(frame: frame)
view.addSubview(skView)
self.skView = skView
#if DEBUG
skView.showsDrawCount = true
skView.showsFields = true
skView.showsFPS = true
skView.showsNodeCount = true
skView.showsPhysics = true
skView.showsQuadCount = true
#endif
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
7447a41d9000f5e01b793c9677f063b5
| 26.563636 | 122 | 0.658971 | 5.174061 | false | false | false | false |
auth0/Lock.iOS-OSX
|
Lock/ConnectionLoadingPresenter.swift
|
2
|
2581
|
// ConnectionLoadingPresenter.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class ConnectionLoadingPresenter: Presentable, Loggable {
var messagePresenter: MessagePresenter?
let loader: RemoteConnectionLoader
let navigator: Navigable
let options: Options
let dispatcher: Dispatcher
init(loader: RemoteConnectionLoader, navigator: Navigable, dispatcher: Dispatcher, options: Options) {
self.loader = loader
self.navigator = navigator
self.options = options
self.dispatcher = dispatcher
}
var view: View {
self.loader.load { error, connections in
guard error == nil else {
#if DEBUG
if let error = error {
assertionFailure(error.localizableMessage)
}
#endif
return Queue.main.async {
self.navigator.navigate(.unrecoverableError(error: error!))
self.dispatcher.dispatch(result: .error(error!))
}
}
guard let connections = connections, !connections.isEmpty else {
return self.navigator.exit(withError: UnrecoverableError.clientWithNoConnections)
}
Queue.main.async {
self.logger.debug("Loaded connections. Moving to root view")
self.navigator.reload(with: connections)
}
}
return LoadingView()
}
}
|
mit
|
3a09fa84d42553912aeeb1ab5d65cc3f
| 40.629032 | 106 | 0.664859 | 5.01165 | false | false | false | false |
VladasZ/iOSTools
|
Sources/iOS/Tools/UIApplicationDelegateTools.swift
|
1
|
979
|
//
// UIApplicationDelegateTools.swift
// iOSTools
//
// Created by Vladas Zakrevskis on 2/13/18.
// Copyright © 2018 Vladas Zakrevskis. All rights reserved.
//
import UIKit
public extension UIApplicationDelegate {
static func changeRootControllerAnimated(_ controller: UIViewController) {
guard let _window = UIApplication.shared.delegate?.window else { LogError(); return }
guard let window = _window else { LogError(); return }
guard let snapshot = window.snapshotView(afterScreenUpdates: true) else { LogError(); return }
controller.view.addSubview(snapshot);
window.rootViewController = controller
UIView.animate(withDuration: 0.3, animations: {() in
snapshot.layer.opacity = 0;
snapshot.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5);
}, completion: {
(value: Bool) in
snapshot.removeFromSuperview();
});
}
}
|
mit
|
0bae97de63ac9249b3ceaccc010aae80
| 31.6 | 102 | 0.643149 | 4.591549 | false | false | false | false |
tadasz/MistikA
|
MistikA/IndoorPuzzleViewController.swift
|
1
|
7928
|
//
// ViewController.swift
// MistikA
//
// Created by Tadas Ziemys on 11/07/14.
// Copyright (c) 2014 Tadas Ziemys. All rights reserved.
//
import UIKit
import MapKit
class IndoorPuzzleViewController: BaseViewController, CLLocationManagerDelegate {
@IBOutlet weak var textLabel: LTMorphingLabel?
@IBOutlet weak var secondTextLabel: LTMorphingLabel?
@IBOutlet weak var firstButton: UIButton?
@IBOutlet weak var secondButton: UIButton?
var i = 0
var j = 0
var texts: Array<String> = ["Ar tai yra mistika?","Ar tai yra nežinomybė?","Kas slepiasi?","Už jūrų?","Už marių?","Už kalnų?","Kas tai pasakys?","Kas yra mistika?","..mistika. .","s. ..tka. .",". ..a.."]
var secondTexts = ["kas", "skaito", "raso", "valgyt", "nepraso", "keliauk", "uz juru", "uz mariu", "uz vandenynu", "pas indena sena", "ten rasi ausko klodus", "keliauk i miesta", "vardu", "Santiago", "Santiago.", "Santiago..", "Santiago....."]
// var locationManager = CLLocationManager()
var regionSantiago = CLCircularRegion(center: CLLocationCoordinate2D(latitude: -33.4450847, longitude: -70.7087122), radius: 30000, identifier: "Santiago")
var regionMadrid = CLCircularRegion(center: CLLocationCoordinate2D(latitude: 40.4378271, longitude: -3.6795367), radius: 30000, identifier: "Madrid")
// (circularRegionWithCenter: CLLocationCoordinate2D(latitude: 54.874262, longitude: 23.904696), radius: 5, identifier: "namai_aleksotas1")
override func viewDidLoad() {
super.viewDidLoad()
performAction(1)
secondTextLabel!.morphingEffect = LTMorphingEffect.Evaporate
textLabel!.morphingEffect = LTMorphingEffect.Pixelate
registerForSantiago()
let tapRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("tapped"))
tapRecognizer.direction = UISwipeGestureRecognizerDirection.Down
tapRecognizer.delaysTouchesBegan = true
view.addGestureRecognizer(tapRecognizer)
}
func tapped() {
UIAlertView(title: "SUKČIAI!!", message: "na gerai, eik tooooliau... mystyka!?!...", delegate: self, cancelButtonTitle: "OK").show()
GameController.sharedInstance.currentGameStage = GameStage.TimerPuzzle
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func performAction(sender: AnyObject)
{
if texts.count <= i {
i = 0
j++
}
let text = texts[i++]
textLabel!.text = text
if j == 3 {
firstButton!.hidden = true
UIView.animateWithDuration(2.5,
animations: {
self.textLabel!.alpha = 0
self.secondTextLabel!.alpha = 1
}, completion: {
(value: Bool) in
self.secondButton!.hidden = false
self.i = 0
self.j = 0
})
}
}
@IBAction func performSecondAction(sender: AnyObject) {
if secondTexts.count <= i {
i = 0
j++
}
let text = secondTexts[i++]
secondTextLabel!.text = text
if j == 1 {
// registerForSantiago()
}
}
func registerForSantiago() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.locationManager.startMonitoringForRegion(regionSantiago)
appDelegate.locationManager.startMonitoringForRegion(regionMadrid)
}
// let beaconIdentifier = "com.tadas.mistika.beikonas"
// var uuid: NSUUID = NSUUID(UUIDString: "78E408FD-48DA-4325-9123-0AEA40925EFF")!
// //NSUUID(string: "78E408FD-48DA-4325-9123-0AEA40925EFF")
// var major: NSNumber?
// var minor: NSNumber?
// var monitoredRegion: CLBeaconRegion?
// func registerForBeacon() {
// if (monitoredRegion == nil) {
// monitoredRegion = CLBeaconRegion(proximityUUID: uuid, identifier: beaconIdentifier)
// self.locationManager.delegate = self
// self.locationManager.startMonitoringForRegion(monitoredRegion)
// }
//
//
// var region = locationManager.monitoredRegions.member(monitoredRegion!) as? CLBeaconRegion
// if region == nil
//// {
////// self.enabled = YES;
//// self.uuid = region!.proximityUUID;
//// self.major = region!.major;
//// self.minor = region!.minor;
////// self.notifyOnEntry = region.notifyOnEntry;
////// self.notifyOnExit = region.notifyOnExit;
////// self.notifyOnDisplay = region.notifyEntryStateOnDisplay;
//// }
//// else
// {
//// self.uuid =
// self.major = nil
// self.minor = nil
// self.locationManager.delegate = self
// if self.locationManager.respondsToSelector(Selector("startMonitoringForRegion:")) {
// println("yes respond")
// self.locationManager.startMonitoringForRegion(monitoredRegion)
// } else {
// println("no respond")
// }
//// self.notifyOnEntry = self.notifyOnExit = YES;
//// self.notifyOnDisplay = NO;
// }
// }
//
//// func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
////
//// }
//
// func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) {
// manager.requestStateForRegion(monitoredRegion)
// }
//
// func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
// println("didEnterRegion...")
// enteredRegion()
// }
//
// func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion region: CLRegion!) {
// println("didDetermineState")
// if region.identifier == beaconIdentifier {
// if (state == CLRegionState.Inside) {
// println("didDetermineState, inside")
// enteredRegion()
// } else if (state == CLRegionState.Outside) {
// exitedRegion()
// }
// }
// }
//
// var showingEnteredAlert = false
// var showingExitAlert = false
//
// func enteredRegion() {
// if !showingEnteredAlert {
// let alert = UIAlertView(title: "jau arti...", message: "ieškok manęs... rrr... grrr...", delegate: self, cancelButtonTitle: "gerai")
// alert.tag = 1
// alert.show()
// showingEnteredAlert = true
// }
// }
//
// func exitedRegion() {
// if !showingExitAlert {
// let alert = UIAlertView(title: "ne čia...", message: "aš kiturrrr... rrr.. rr.", delegate: self, cancelButtonTitle: "utruti")
// alert.tag = 2
// alert.show()
// showingExitAlert = true
// }
// }
//
// override func alertView(alertView: UIAlertView!, didDismissWithButtonIndex buttonIndex: Int) {
// if alertView.tag == 1 {
// showingEnteredAlert = false
// locationManager.stopMonitoringForRegion(monitoredRegion)
//
// NSUserDefaults.standardUserDefaults().setValue("FindPalepe", forKey: "place")
// performSegueWithIdentifier("show_FindPalepe", sender: self)
//
// }
// else if alertView.tag == 2 {
// showingExitAlert = false
// }
// else {
// super.alertView(alertView, didDismissWithButtonIndex: buttonIndex)
// }
// }
}
|
mit
|
477269fea3995be53852520b7b5b4603
| 35.136986 | 247 | 0.584281 | 4.238886 | false | false | false | false |
Harley-xk/SimpleDataKit
|
Example/Pods/Comet/Comet/Classes/Path.swift
|
1
|
6515
|
//
// Path.swift
// Comet
//
// Created by Harley.xk on 16/6/27.
//
//
import Foundation
import MobileCoreServices
// MARK: - 文件路径,快速获取各种文件路径
open class Path {
/// 使用路径字符串构建实例
public init(_ path: String) {
string = path
}
/// 完整路径字符串
open var string: String
/// URL 实例
open var url: URL {
return URL(fileURLWithPath: string)
}
/// 获取沙盒 Documents 路径
open class func documents() -> Path {
return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0].path
}
/// 获取沙盒 Library 路径
open class func library() -> Path {
return NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0].path
}
/// 获取沙盒 Cache 路径
open class func cache() -> Path {
return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0].path
}
/// 获取沙盒 Temp 路径
open class func temp() -> Path {
return NSTemporaryDirectory().path
}
/// 获取沙盒 Application Support 路径,不存在时会自动创建
open class func applicationSupport() -> Path {
let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)[0].path
if !path.exist {
path.createDirectory()
}
return path
}
/// 根据名称获取Bundle
///
/// - Parameter name: Bundle 名称,默认为 nil,表示 main bundle
open class func bundle(_ name: String? = nil) -> Bundle? {
if name == nil {
return Bundle.main
}
return Bundle(identifier: name!)
}
/// 获取当前目录下的资源文件路径
///
/// - Parameter name: 资源文件名(含扩展名)
open func resource(_ name: String) -> Path {
let directory = string as NSString
return directory.appendingPathComponent(name).path
}
// MARK: - Path Utils
/// 文件管理器
open var fileManager: FileManager {
return FileManager.default
}
/// 路径是否存在,无论文件或者文件夹
open var exist: Bool {
return fileManager.fileExists(atPath: string)
}
/// 文件是否存在, 返回是否存在,以及是否是文件
open var fileExist: (exist: Bool, isFile: Bool) {
var isDirectory = ObjCBool(false)
let exist = fileManager.fileExists(atPath: string, isDirectory: &isDirectory)
return (exist, !isDirectory.boolValue)
}
/// 文件扩展名
open var pathExtension: String? {
let path = string as NSString
return path.pathExtension
}
/// 创建路径
open func createDirectory() {
try? fileManager.createDirectory(atPath: string, withIntermediateDirectories: true, attributes: nil)
}
/// 获取文件 mime type
open var mimeType: String? {
if let ext = pathExtension as NSString? {
if let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext, nil)?.takeUnretainedValue() {
if let MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType) {
let mimeTypeCFString = MIMEType.takeUnretainedValue() as CFString
return mimeTypeCFString as String
}
}
}
return nil
}
/// 获取文件大小,如果是文件夹,会遍历整个目录及子目录计算所有文件大小
open var size: UInt64 {
let fileExist = self.fileExist
if fileExist.exist {
if fileExist.isFile {
return fileSize()
}else {
return folderSize()
}
}
return 0
}
/// 获取文件夹大小,并且格式化为可读字符串
open var sizeString: String {
return Path.string(fromBytes: size)
}
/// 转换字节数为最大单位可读字符串
open class func string(fromBytes bytes: UInt64) -> String {
let kb = Double(bytes)/1024;
if (kb < 1) {
return "\(bytes)B"
}
let mb = kb/1024.0;
if (mb < 1) {
return String(format: "%.0fKB", kb)
}
let gb = mb/1024.0;
if (gb < 1) {
return String(format: "%.1fMB", mb)
}
let tb = gb/1024.0;
if (tb < 1) {
return String(format: "%.1fG", gb)
} else {
return String(format: "%.1fT", tb)
}
}
// MARK: - Private
internal func fileSize() -> UInt64 {
let fileExist = self.fileExist
if fileExist.exist && fileExist.isFile {
if let attributes = try? fileManager.attributesOfItem(atPath: string) as NSDictionary {
return attributes.fileSize()
}
}
return 0
}
internal func folderSize() -> UInt64 {
var folderSize: UInt64 = 0
let fileExist = self.fileExist
if fileExist.exist && !fileExist.isFile {
if let contents = try? fileManager.contentsOfDirectory(atPath: string) {
for file in contents {
let path = resource(file)
let subFileExist = path.fileExist
if subFileExist.exist {
if subFileExist.isFile {
folderSize += path.fileSize()
}else {
folderSize += path.folderSize()
}
}
}
}
}
return folderSize
}
}
public extension Bundle
{
/// 获取应用程序资源包下的路径
///
/// - Parameters:
/// - name: 资源名称
/// - Returns: 返回资源路径
public func resource(_ name: String) -> Path? {
let path = name as NSString
let pathExtension = path.pathExtension
var nameWithoutExtension = name
if !pathExtension.isEmpty {
nameWithoutExtension = path.deletingPathExtension
}
let string = self.path(forResource: nameWithoutExtension, ofType: pathExtension)
return string == nil ? nil : Path(string!)
}
}
public extension String
{
public var path: Path {
return Path(self)
}
}
|
mit
|
f228f43f9a64de1019af2dcb69f0eeaa
| 26.259091 | 127 | 0.554277 | 4.688819 | false | false | false | false |
bparish628/iFarm-Health
|
iOS/iFarm-Health/Pods/Charts/Source/Charts/Utils/Transformer.swift
|
4
|
5890
|
//
// Transformer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// Transformer class that contains all matrices and is responsible for transforming values into pixels on the screen and backwards.
@objc(ChartTransformer)
open class Transformer: NSObject
{
/// matrix to map the values to the screen pixels
@objc internal var _matrixValueToPx = CGAffineTransform.identity
/// matrix for handling the different offsets of the chart
@objc internal var _matrixOffset = CGAffineTransform.identity
@objc internal var _viewPortHandler: ViewPortHandler
@objc public init(viewPortHandler: ViewPortHandler)
{
_viewPortHandler = viewPortHandler
}
/// Prepares the matrix that transforms values to pixels. Calculates the scale factors from the charts size and offsets.
@objc open func prepareMatrixValuePx(chartXMin: Double, deltaX: CGFloat, deltaY: CGFloat, chartYMin: Double)
{
var scaleX = (_viewPortHandler.contentWidth / deltaX)
var scaleY = (_viewPortHandler.contentHeight / deltaY)
if CGFloat.infinity == scaleX
{
scaleX = 0.0
}
if CGFloat.infinity == scaleY
{
scaleY = 0.0
}
// setup all matrices
_matrixValueToPx = CGAffineTransform.identity
_matrixValueToPx = _matrixValueToPx.scaledBy(x: scaleX, y: -scaleY)
_matrixValueToPx = _matrixValueToPx.translatedBy(x: CGFloat(-chartXMin), y: CGFloat(-chartYMin))
}
/// Prepares the matrix that contains all offsets.
@objc open func prepareMatrixOffset(inverted: Bool)
{
if !inverted
{
_matrixOffset = CGAffineTransform(translationX: _viewPortHandler.offsetLeft, y: _viewPortHandler.chartHeight - _viewPortHandler.offsetBottom)
}
else
{
_matrixOffset = CGAffineTransform(scaleX: 1.0, y: -1.0)
_matrixOffset = _matrixOffset.translatedBy(x: _viewPortHandler.offsetLeft, y: -_viewPortHandler.offsetTop)
}
}
/// Transform an array of points with all matrices.
// VERY IMPORTANT: Keep matrix order "value-touch-offset" when transforming.
open func pointValuesToPixel(_ points: inout [CGPoint])
{
let trans = valueToPixelMatrix
for i in 0 ..< points.count
{
points[i] = points[i].applying(trans)
}
}
open func pointValueToPixel(_ point: inout CGPoint)
{
point = point.applying(valueToPixelMatrix)
}
@objc open func pixelForValues(x: Double, y: Double) -> CGPoint
{
return CGPoint(x: x, y: y).applying(valueToPixelMatrix)
}
/// Transform a rectangle with all matrices.
open func rectValueToPixel(_ r: inout CGRect)
{
r = r.applying(valueToPixelMatrix)
}
/// Transform a rectangle with all matrices with potential animation phases.
open func rectValueToPixel(_ r: inout CGRect, phaseY: Double)
{
// multiply the height of the rect with the phase
var bottom = r.origin.y + r.size.height
bottom *= CGFloat(phaseY)
let top = r.origin.y * CGFloat(phaseY)
r.size.height = bottom - top
r.origin.y = top
r = r.applying(valueToPixelMatrix)
}
/// Transform a rectangle with all matrices.
open func rectValueToPixelHorizontal(_ r: inout CGRect)
{
r = r.applying(valueToPixelMatrix)
}
/// Transform a rectangle with all matrices with potential animation phases.
open func rectValueToPixelHorizontal(_ r: inout CGRect, phaseY: Double)
{
// multiply the height of the rect with the phase
let left = r.origin.x * CGFloat(phaseY)
let right = (r.origin.x + r.size.width) * CGFloat(phaseY)
r.size.width = right - left
r.origin.x = left
r = r.applying(valueToPixelMatrix)
}
/// transforms multiple rects with all matrices
open func rectValuesToPixel(_ rects: inout [CGRect])
{
let trans = valueToPixelMatrix
for i in 0 ..< rects.count
{
rects[i] = rects[i].applying(trans)
}
}
/// Transforms the given array of touch points (pixels) into values on the chart.
open func pixelsToValues(_ pixels: inout [CGPoint])
{
let trans = pixelToValueMatrix
for i in 0 ..< pixels.count
{
pixels[i] = pixels[i].applying(trans)
}
}
/// Transforms the given touch point (pixels) into a value on the chart.
open func pixelToValues(_ pixel: inout CGPoint)
{
pixel = pixel.applying(pixelToValueMatrix)
}
/// - returns: The x and y values in the chart at the given touch point
/// (encapsulated in a CGPoint). This method transforms pixel coordinates to
/// coordinates / values in the chart.
@objc open func valueForTouchPoint(_ point: CGPoint) -> CGPoint
{
return point.applying(pixelToValueMatrix)
}
/// - returns: The x and y values in the chart at the given touch point
/// (x/y). This method transforms pixel coordinates to
/// coordinates / values in the chart.
@objc open func valueForTouchPoint(x: CGFloat, y: CGFloat) -> CGPoint
{
return CGPoint(x: x, y: y).applying(pixelToValueMatrix)
}
@objc open var valueToPixelMatrix: CGAffineTransform
{
return
_matrixValueToPx.concatenating(_viewPortHandler.touchMatrix
).concatenating(_matrixOffset
)
}
@objc open var pixelToValueMatrix: CGAffineTransform
{
return valueToPixelMatrix.inverted()
}
}
|
apache-2.0
|
bfa05c48f8c5a5f8671b7a35c902c20a
| 31.541436 | 153 | 0.637861 | 4.84375 | false | false | false | false |
naokits/my-programming-marathon
|
RxSwiftDemo/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/TableViewWithEditingCommands/RandomUserAPI.swift
|
9
|
1825
|
//
// RandomUserAPI.swift
// RxExample
//
// Created by carlos on 28/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
class RandomUserAPI {
static let sharedAPI = RandomUserAPI()
private init() {}
func getExampleUserResultSet() -> Observable<[User]> {
let url = NSURL(string: "http://api.randomuser.me/?results=20")!
return NSURLSession.sharedSession().rx_JSON(url)
.map { json in
guard let json = json as? [String: AnyObject] else {
throw exampleError("Casting to dictionary failed")
}
return try self.parseJSON(json)
}
}
private func parseJSON(json: [String: AnyObject]) throws -> [User] {
guard let results = json["results"] as? [[String: AnyObject]] else {
throw exampleError("Can't find results")
}
let users = results.map { $0["user"] as? [String: AnyObject] }.filter { $0 != nil }
let userParsingError = exampleError("Can't parse user")
let searchResults: [User] = try users.map { user in
let name = user?["name"] as? [String: String]
let pictures = user?["picture"] as? [String: String]
guard let firstName = name?["first"], let lastName = name?["last"], let imageURL = pictures?["medium"] else {
throw userParsingError
}
let returnUser = User(
firstName: firstName.capitalizedString,
lastName: lastName.capitalizedString,
imageURL: imageURL
)
return returnUser
}
return searchResults
}
}
|
mit
|
6d754a12efc5f020f04b9603d9ec6845
| 29.932203 | 121 | 0.544956 | 4.825397 | false | false | false | false |
vokal/Xcode-Template
|
Vokal-Swift.xctemplate/ResetPasswordAPI.swift
|
2
|
3301
|
//
// ___FILENAME___
// ___PACKAGENAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// ___COPYRIGHT___
//
import Foundation
/**
API for requesting password resets then actually resetting the password.
*/
struct ResetPasswordAPI {
// MARK: - Reset Password Enums
private enum JSONKey: String {
case
RequestEmail = "email",
UpdatedPassword = "password",
ResetCode = "code"
}
private enum PasswordResetPath: String, APIVersionable {
case
Request = "password-reset/request",
Confirm = "password-reset/confirm"
}
private static var headerDict: [HTTPHeaderKey: HTTPHeaderValue] {
return MainAPIUtility
.sharedUtility
.requestHeaders(withAuthToken: false)
}
// MARK: - Reset Password Methods
/**
Requests a password reset for a given email address. If the email exists, this will trigger
an email to the user with a reset request code which they can then use to reset their
password. If the email doesn't exist, the server just smiles and nods to avoid disclosing
what emails are actually related to accounts.
- parameter email: The email the user is requesting a password reset for.
- parameter success: The closure to execute if the request succeeds.
- parameter failure: The closure to execute if the request fails.
*/
static func requestPasswordReset(forEmail email: String,
success: @escaping APIDictionaryCompletion,
failure: @escaping APIFailureCompletion) {
let parameters = [
JSONKey.RequestEmail.rawValue: email,
]
let resetPasswordRequestPath = PasswordResetPath.Request.path(forVersion: .v1)
MainAPIUtility
.sharedUtility
.postJSON(to: resetPasswordRequestPath,
headers: headerDict,
params: parameters,
success: success,
failure: failure)
}
/**
Resets the password for a user who has received a password reset code via email.
- parameter code: The reset password code provided by the user.
- parameter updatedPassword: The password the user now wants to use.
- parameter success: The closure to execute if the request succeeds.
- parameter failure: The closure to execute if the request fails.
*/
static func resetPassword(withCode code: String,
updatedPassword: String,
success: @escaping APIDictionaryCompletion,
failure: @escaping APIFailureCompletion) {
let parameters = [
JSONKey.ResetCode.rawValue: code,
JSONKey.UpdatedPassword.rawValue: updatedPassword,
]
let resetPasswordPath = PasswordResetPath.Confirm.path(forVersion: .v1)
MainAPIUtility
.sharedUtility
.postJSON(to: resetPasswordPath,
headers: headerDict,
params: parameters,
success: success,
failure: failure)
}
}
|
mit
|
826b1f7f084a0b61ad96f840ff9148d0
| 34.880435 | 96 | 0.591639 | 5.350081 | false | false | false | false |
mathewa6/Practise
|
Identicon.playground/Contents.swift
|
1
|
10885
|
import UIKit
let
identiconMix: [String] = [
"4ADCB1A8-477D-475A-9E58-1A9AABCBF0F1",
"B46B594B-0891-455C-BB83-839708CB031E",
"28F6FAA1-8C48-4CDD-A068-38348A3EE98A",
"211627EF-1AE7-4158-B7CF-A1C582F805C1",
"330A88AC-93D0-478C-B0AC-C8356B083061",
"4685658E-F184-4901-AB95-61789DBC3F96",
"B07C82AC-A8BE-4A92-8F9B-975C520C346B",
"10C2BBE7-4E47-41EA-8045-4C88B4E34F1A",
"7AA2D934-BC6C-4F71-9DF6-341D55979011",
"0FFD8746-D886-4BCB-8AB2-8540E4A65DAE",
"9FE90ED7-8836-4399-9D9D-C42C313FF348",
"8BF27D40-D85A-47F0-82D8-3FA9CF7FC2FE",
"35AEB57A-EAE6-41DD-917F-76F8B4A7EC01",
"1E41F17F-4F1B-415D-8B2E-C32B8379F613",
"AA606E02-B806-46C3-B1E8-17192E4A93A1",
"A809BBE5-858B-4BEE-AFD7-5894D89D6556",
"7E20BE54-94E3-46EA-92FC-283E919009DB",
"7EE0061C-7131-4B47-A05B-E5139ACAA922",
"A42D69D6-5F41-4E75-A09A-E6FDFA46E3EB",
"BF020678-DCE2-4207-B49E-E2E94577A917",
"7BEC8FB7-516B-4851-A950-B768283525A6",
"C2141630-1703-4257-AFC4-E39006CC933E",
"DC58A155-5DE2-4F83-B080-A827EA1423C6",
"C0850E86-6092-4849-9041-EF20806BCA28",
"021838E8-B573-4B47-A81C-E265F34763FA",
"87B50882-4D99-4E3B-B845-0B90ABB1C5B6",
"697FA66B-8486-4A7C-A063-5830E2768450",
"E08837D1-B0FC-4C2C-BB1F-1CCA151DCDD9",
"514E1DE2-8714-4A66-B381-8E4EAD017F31",
"3F0FF748-1C92-4201-B4CB-BBBB2368F8B7",
"ADB689A8-EF03-4C40-BCC7-0DB797030DC2",
"2B506692-0DF9-4B48-89A0-77E1F51F6E82"
]
public extension UIColor {
class func randomNormalizedColor() -> UIColor {
let hue: CGFloat = CGFloat(arc4random_uniform(256))/255
let sat: CGFloat = CGFloat(arc4random_uniform(128))/255 + 0.5
let bri: CGFloat = CGFloat(arc4random_uniform(128))/255 + 0.5
return UIColor(hue: hue,
saturation: sat,
brightness: bri,
alpha: 1.0)
}
class var tintMuted: UIColor {
let factor: Float = 0.66
return UIColor(red: CGFloat((12/255.0) + factor)/2,
green: CGFloat((150/255.0) + factor)/2,
blue: CGFloat((75/255.0) + factor)/2,
alpha: 1.0)
}
}
public extension CGColor {
static func color(from number: UInt16) -> CGColor {
let blue = CGFloat(number & 0b11111) / 31;
let green = CGFloat((number >> 5) & 0b11111) / 31;
let red = CGFloat((number >> 10) & 0b11111) / 31;
return CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [ red, green, blue, 1 ])!
}
}
public class GitHubIdenticon {
private let numberOfColumns = 5
private let numberOfColumnComponents = 5
private let numberOfRows = 5
private let numberOfRowComponents = 5
public let size: CGSize = CGSize(width: 600, height: 600)
public init() {}
public func identity(using value: Int, withRows rows: Int, columns: Int) -> CGImage {
let context = CGContext(
data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 8,
bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)!
context.setShouldAntialias(false)
var color = UIColor.tintMuted.cgColor
let cellSize = CGSize(width: size.width / CGFloat(rows), height: size.height / CGFloat(columns));
for row in 0..<rows {
for col in 0..<columns - columns/2 {
let offset = Int(row * columns + col)
let digit: Int = (value >> offset)
if (digit & 0b1) == 0 {
continue
}
if row == 0 || row == rows - 1 {
if col == 0 || col == columns - 1 {
continue
}
}
color = color.copy(alpha: CGFloat(0.51 + Double((digit & 0b1111))/16.0)) ?? color
context.setFillColor(color)
var rects = [CGRect]()
rects.append(self.rect(forRow: row, column: col, size: cellSize))
let mirroredCol = (columns - col - 1)
if (mirroredCol > col) {
rects.append(self.rect(forRow: row, column: mirroredCol, size: cellSize))
}
context.fill(rects)
}
}
let image = context.makeImage()!
return image
}
public func icon(from number: Int, size: CGSize) -> CGImage {
let context = CGContext(
data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 8,
bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)!
context.setShouldAntialias(false)
let color = UIColor.randomNormalizedColor().cgColor
context.setFillColor(color)
let cellSize = CGSize(width: size.width / CGFloat(numberOfRows), height: size.height / CGFloat(numberOfColumns));
for row in 0..<numberOfRowComponents {
for col in 0..<numberOfColumnComponents {
let offset = Int(row * numberOfColumns + col)
if ((number >> offset) & 0b1) == 0 {
continue
}
var rects = [CGRect]()
rects.append(self.rect(forRow: row, column: col, size: cellSize))
let mirroredCol = (numberOfColumns - col - 1)
if (mirroredCol > col) {
rects.append(self.rect(forRow: row, column: mirroredCol, size: cellSize))
}
context.fill(rects)
}
}
let image = context.makeImage()!
return image
}
public func generated() {
UIGraphicsBeginImageContext(CGSize(width:5,height:5))
guard let g = UIGraphicsGetCurrentContext() else {
return
}
var t = 0,
c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).cgColor
srand48(time(&t))
for x in 0..<3 {
for y in 0..<5 {
g.setFillColor(drand48()>0.5 ? c : UIColor.white.cgColor)
var r = [CGRect(x:x,y:y,width:1,height:1)]
if x<2 {
let m = x==0 ? 4 : 3;
r.append(CGRect(x:m,y:y,width:1,height:1))
}
g.fill(r)
}
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
private func rect(forRow row: Int, column: Int, size: CGSize) -> CGRect {
return CGRect(
x: CGFloat(column) * size.width,
y: CGFloat(row) * size.height,
width: size.width,
height: size.height
)
}
}
let str = "211627EF"
let num = Int(exactly: str.hash)!
for char in str.characters {
print(char.description.hash % 2)
}
var truths: [Int] = []
Array(str.characters).map { truths.append( $0.description.hash % 2 == 0 ? 1 : 0)}
truths
// Array(str.characters)[4].description.hash
let x = GitHubIdenticon()
UIImage(cgImage: x.icon(from: num, size: CGSize(width: 44, height: 44)))
let image = UIImage(cgImage: x.identity(using: "D441DDE7-27D5-471F-B426-A2A745D400F0".hash, withRows: 5, columns: 5))
// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/Identicon.png"
let url: URL = URL(fileURLWithPath: filePath)
print(url.description)
for id in identiconMix {
let x = GitHubIdenticon()
UIImage(cgImage: x.icon(from: num, size: CGSize(width: 44, height: 44)))
let image = UIImage(cgImage: x.identity(using: id.hash, withRows: 5, columns: 5))
// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/\(id).png"
let url: URL = URL(fileURLWithPath: filePath)
print(url.description)
let
imageView: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
imageView.layer.cornerRadius = 7.5
imageView.backgroundColor = UIColor(red: 235/250,
green: 235/250,
blue: 235/250,
alpha: 1.0)
imageView.image = image
// Save image.
do {
try UIImagePNGRepresentation(image)?.write(to: url)
} catch let error as NSError {
print("Error")
}
}
let
imageView: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
imageView.layer.cornerRadius = 7.5
imageView.backgroundColor = UIColor(red: 235/250,
green: 235/250,
blue: 235/250,
alpha: 1.0)
imageView.image = image
// Save image.
do {
try UIImagePNGRepresentation(image)?.write(to: url)
} catch let error as NSError {
print("Error")
}
x.generated()
class IdentityView: UIView {
public let text: String = "211627EF"
override func draw(_ rect: CGRect) {
guard let g: CGContext = UIGraphicsGetCurrentContext() else {
return
}
let cellSize = CGSize(width: rect.width / CGFloat(5), height: rect.height / CGFloat(5))
var t = 0,
c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).cgColor
for x in 0..<3 {
for y in 0..<5 { // limit less than text.length
g.setFillColor( drand48() > 0.5 ? c : UIColor.white.cgColor)
var r = [CGRect(x: CGFloat(x) * cellSize.width,
y: CGFloat(y) * cellSize.height,
width: cellSize.width,
height: cellSize.height)]
if x<2 {
let m = x==0 ? 4 : 3;
r.append(CGRect(x: CGFloat(m) * cellSize.width,
y: CGFloat(y) * cellSize.height,
width: cellSize.width,
height: cellSize.height))
}
g.fill(r)
}
}
}
}
let v = IdentityView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
|
mit
|
36ae4385dd5e86eb75cfc0dec025c613
| 32.69969 | 121 | 0.541938 | 3.669926 | false | false | false | false |
Haidora/HaidoraCommonWrapperSwift
|
Pod/Classes/AlertView/HaidoraAlertViewManager.swift
|
1
|
7100
|
//
// HaidoraAlertViewManager.swift
// Pods
//
// Created by Dailingchi on 15/6/11.
//
//
import Foundation
import UIKit
public typealias HDClickBlock = (AnyObject, Int) -> Void
/**
* 如果要自定义弹出框,弹出框需要实现该协议
*/
@objc public protocol HDAlertDelegate {
func alertWithMessage(message: String)
func alertWithTitle(title: String, message: String)
func alertWithTitle(title: String, message: String, cancelTitle: String, okTitle: String?)
func alertWithTitle(title: String, message: String, clickAction: HDClickBlock?, cancelTitle: String, otherButtonTitles: [String]?)
func alertWithError(error: NSError)
}
@objc public class HDAlertViewManager {
public var alertDelegate: HDAlertDelegate
public class func shareInstance() -> HDAlertViewManager {
struct HDAlertViewManagerSingleton {
static var predicate: dispatch_once_t = 0
static var instance: HDAlertViewManager? = nil;
}
dispatch_once(&HDAlertViewManagerSingleton.predicate, {
HDAlertViewManagerSingleton.instance = HDAlertViewManager(alertDelegate: HDAlertView())
})
return HDAlertViewManagerSingleton.instance!
}
init(alertDelegate: HDAlertDelegate) {
self.alertDelegate = alertDelegate;
}
}
public extension HDAlertViewManager {
public class func alertWithMessage(message: String) {
HDAlertViewManager.shareInstance().alertDelegate.alertWithMessage(message)
}
public class func alertWithTitle(title: String, message: String) {
HDAlertViewManager.shareInstance().alertDelegate.alertWithTitle(title, message: message)
}
public class func alertWithTitle(title: String, message: String, cancelTitle: String, okTitle: String?) {
HDAlertViewManager.shareInstance().alertDelegate.alertWithTitle(title, message: message, cancelTitle: cancelTitle, okTitle: okTitle)
}
/**
兼容Objective-C版本
:param: title
:param: message
:param: clickAction
:param: cancelTitle
:param: moreButtonTitles 多个参数用数组代替
*/
public class func alertWithTitle(title: String, message: String, clickAction: HDClickBlock?, cancelTitle: String, moreButtonTitles: [String]?) {
HDAlertViewManager.shareInstance().alertDelegate.alertWithTitle(title, message: message, clickAction: clickAction, cancelTitle: cancelTitle, otherButtonTitles: moreButtonTitles)
}
public class func alertWithTitle(title: String, message: String, clickAction: HDClickBlock?, cancelTitle: String, _ moreButtonTitles: String... ) {
var buttonTitles = [String]()
for buttonTitle in moreButtonTitles {
buttonTitles.append(buttonTitle)
}
HDAlertViewManager.shareInstance().alertDelegate.alertWithTitle(title, message: message, clickAction: clickAction, cancelTitle: cancelTitle, otherButtonTitles: buttonTitles)
}
public class func alertWithError(error: NSError) {
HDAlertViewManager.shareInstance().alertDelegate.alertWithError(error)
}
}
//MAKR:
//MAKR:NSError
public extension NSError {
/**
弹出错误描述
:param: title 错误提示标题
:param: message 错误提示内容
:returns:
*/
public convenience init(title: String?, message: String?) {
self.init(domain: "HDAlertViewManagerDomain", code: -1, userInfo: nil)
self.title = title;
self.message = message;
}
}
internal extension NSError {
private struct AssociatedKeys {
static var kHD_NSError_title = "kHD_NSError_title"
static var kHD_NSError_message = "kHD_NSError_message"
}
internal var title: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.kHD_NSError_title) as? String
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.kHD_NSError_title, newValue, UInt(OBJC_ASSOCIATION_COPY_NONATOMIC))
}
}
internal var message: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.kHD_NSError_message) as? String
}
set(newValue) {
objc_setAssociatedObject(self, &AssociatedKeys.kHD_NSError_message, newValue, UInt(OBJC_ASSOCIATION_COPY_NONATOMIC))
}
}
}
//MAKR:
//MAKR:UIAlertView
extension UIAlertView: UIAlertViewDelegate {
/**
兼容Objective-C版本
:param: title
:param: message
:param: clickAction
:param: cancelButtonTitle
:param: moreButtonTitles 多个参数用数组代替
:returns:
*/
public convenience init(title: String, message: String, clickAction: HDClickBlock?, cancelButtonTitle: String?, moreButtonTitles: [String]?) {
self.init(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle)
if let click = clickAction {
self.delegate = self
self.clickAction = click
}
if let moreButtonTitles = moreButtonTitles {
for buttonTitle in moreButtonTitles {
self.addButtonWithTitle(buttonTitle)
}
}
}
public convenience init(title: String, message: String, clickAction: HDClickBlock?, cancelButtonTitle: String?, _ moreButtonTitles: String...) {
self.init(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle)
if let click = clickAction {
self.delegate = self
self.clickAction = click
}
for buttonTitle in moreButtonTitles {
self.addButtonWithTitle(buttonTitle)
}
}
//MAKR: UIAlertViewDelegate
public func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
self.clickAction?(alertView, buttonIndex)
}
}
private extension UIAlertView {
private struct AssociatedKeys {
static var kHD_UIAlertView_clickAction = "kHD_UIAlertView_clickAction"
}
private class ClosureWrapper: NSObject, NSCopying {
var closure: HDClickBlock?
convenience init(closure: HDClickBlock?) {
self.init()
self.closure = closure
}
@objc func copyWithZone(zone: NSZone) -> AnyObject {
var wrapper: ClosureWrapper = ClosureWrapper()
wrapper.closure = closure
return wrapper
}
}
private var clickAction: HDClickBlock? {
get {
if let closure = objc_getAssociatedObject(self, &AssociatedKeys.kHD_UIAlertView_clickAction) as? ClosureWrapper {
return closure.closure;
}
else {
return nil;
}
}
set(newValue) {
if let newValue = newValue {
objc_setAssociatedObject(self, &AssociatedKeys.kHD_UIAlertView_clickAction, ClosureWrapper(closure: newValue), UInt(OBJC_ASSOCIATION_COPY_NONATOMIC))
}
}
}
}
|
mit
|
f56230af478eafe38ca6f6ac8798e988
| 31.287037 | 185 | 0.657729 | 4.744218 | false | false | false | false |
LeeShiYoung/DouYu
|
DouYuAPP/DouYuAPP/Classes/Home/View/Yo_HomeCycleView.swift
|
1
|
1108
|
//
// Yo_HomeCycleView.swift
// DouYuAPP
//
// Created by shying li on 2017/4/1.
// Copyright © 2017年 李世洋. All rights reserved.
//
import UIKit
import FSPagerView
class Yo_HomeCycleView: FSPagerView {
override init(frame: CGRect) {
super.init(frame: frame)
register(FSPagerViewCell.self, forCellWithReuseIdentifier: cycleViewCellID)
itemSize = .zero
automaticSlidingInterval = 3.0
addSubview(pageControl)
pageControl.snp.makeConstraints { (maker) in
maker.bottom.left.right.equalTo(self)
maker.height.equalTo(20)
}
}
public lazy var pageControl: FSPageControl = {
let pageControl = FSPageControl()
pageControl.contentHorizontalAlignment = .right
pageControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 10)
pageControl.setFillColor(UIColor.orange, for: .selected)
return pageControl
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
e5b8338f4f2e72031e15ef9b31c6af10
| 25.166667 | 88 | 0.640582 | 4.46748 | false | false | false | false |
proversity-org/edx-app-ios
|
Source/LoadStateViewController.swift
|
1
|
9179
|
//
// LoadStateViewController.swift
// edX
//
// Created by Akiva Leffert on 5/13/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import edXCore
public enum LoadState {
case Initial
case Loaded
case Empty(icon : Icon?, message : String?, attributedMessage : NSAttributedString?, accessibilityMessage : String?, buttonInfo : MessageButtonInfo?)
// if attributed message is set then message is ignored
// if message is set then the error is ignored
case Failed(error : NSError?, icon : Icon?, message : String?, attributedMessage : NSAttributedString?, accessibilityMessage : String?, buttonInfo : MessageButtonInfo?)
var accessibilityMessage : String? {
switch self {
case .Initial: return nil
case .Loaded: return nil
case let .Empty(info): return info.accessibilityMessage
case let .Failed(info): return info.accessibilityMessage
}
}
var isInitial : Bool {
switch self {
case .Initial: return true
default: return false
}
}
var isLoaded : Bool {
switch self {
case .Loaded: return true
default: return false
}
}
var isError : Bool {
switch self {
case .Failed(_): return true
default: return false
}
}
static func failed(error : NSError? = nil, icon : Icon? = .UnknownError, message : String? = nil, attributedMessage : NSAttributedString? = nil, accessibilityMessage : String? = nil, buttonInfo : MessageButtonInfo? = nil) -> LoadState {
return LoadState.Failed(error : error, icon : icon, message : message, attributedMessage : attributedMessage, accessibilityMessage : accessibilityMessage, buttonInfo : buttonInfo)
}
static func empty(icon : Icon?, message : String? = nil, attributedMessage : NSAttributedString? = nil, accessibilityMessage : String? = nil, buttonInfo : MessageButtonInfo? = nil) -> LoadState {
return LoadState.Empty(icon: icon, message: message, attributedMessage: attributedMessage, accessibilityMessage : accessibilityMessage, buttonInfo : buttonInfo)
}
}
/// A controller should implement this protocol to support reloading with fullscreen errors for unknownErrors
@objc protocol LoadStateViewReloadSupport {
func loadStateViewReload()
}
class LoadStateViewController : UIViewController {
private let loadingView : UIView
private var contentView : UIView?
private let messageView : IconMessageView
private var delegate: LoadStateViewReloadSupport?
private var madeInitialAppearance : Bool = false
var state : LoadState = .Initial {
didSet {
// this sets a background color so when the view is pushed in it doesn't have a black or weird background
switch state {
case .Initial:
view.backgroundColor = OEXStyles.shared().standardBackgroundColor()
default:
view.backgroundColor = UIColor.clear
}
updateAppearanceAnimated(animated: madeInitialAppearance)
}
}
var insets : UIEdgeInsets = .zero {
didSet {
view.setNeedsUpdateConstraints()
}
}
init() {
messageView = IconMessageView()
loadingView = SpinnerView(size: .Large, color: .Primary)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var messageStyle : OEXTextStyle {
return messageView.messageStyle
}
override func loadView() {
view = PassthroughView()
}
@objc func setupInController(controller : UIViewController, contentView : UIView) {
controller.addChild(self)
didMove(toParent: controller)
self.contentView = contentView
contentView.alpha = 0
controller.view.addSubview(loadingView)
controller.view.addSubview(messageView)
controller.view.addSubview(view)
if isSupportingReload() {
delegate = controller as? LoadStateViewReloadSupport
}
}
func loadStateViewReload() {
if isSupportingReload() {
delegate?.loadStateViewReload()
}
}
func isSupportingReload() -> Bool {
if let _ = parent as? LoadStateViewReloadSupport as? UIViewController {
return true
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
messageView.alpha = 0
view.addSubview(messageView)
view.addSubview(loadingView)
state = .Initial
view.setNeedsUpdateConstraints()
view.isUserInteractionEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
madeInitialAppearance = true
}
override func updateViewConstraints() {
loadingView.snp.remakeConstraints { make in
make.center.equalTo(view)
}
messageView.snp.remakeConstraints { make in
make.center.equalTo(view)
}
view.snp.remakeConstraints { make in
if let superview = view.superview {
make.edges.equalTo(superview).inset(insets)
}
}
super.updateViewConstraints()
}
private func showOfflineSnackBarIfNecessary() {
DispatchQueue.main.async { [weak self] in
if let parent = self?.parent as? OfflineSupportViewController {
parent.showOfflineSnackBarIfNecessary()
}
}
}
private func updateAppearanceAnimated(animated : Bool) {
var alphas : (loading : CGFloat, message : CGFloat, content : CGFloat, touchable : Bool) = (loading : 0, message : 0, content : 0, touchable : false)
UIView.animate(withDuration: 0.3 * TimeInterval()) { [weak self] in
guard let owner = self else { return }
switch owner.state {
case .Initial:
alphas = (loading : 1, message : 0, content : 0, touchable : false)
case .Loaded:
alphas = (loading : 0, message : 0, content : 1, touchable : false)
owner.showOfflineSnackBarIfNecessary()
case let .Empty(info):
owner.messageView.buttonInfo = info.buttonInfo
UIView.performWithoutAnimation {
if let message = info.attributedMessage {
owner.messageView.attributedMessage = message
}
else {
owner.messageView.message = info.message
}
owner.messageView.icon = info.icon
}
alphas = (loading : 0, message : 1, content : 0, touchable : true)
case let .Failed(info):
owner.messageView.buttonInfo = info.buttonInfo
UIView.performWithoutAnimation {
if let error = info.error, error.oex_isNoInternetConnectionError {
owner.messageView.showError(message: Strings.networkNotAvailableMessageTrouble, icon: .InternetError)
}
else if let error = info.error as? OEXAttributedErrorMessageCarrying {
owner.messageView.showError(message: error.attributedDescription(withBaseStyle: owner.messageStyle), icon: info.icon)
}
else if let message = info.attributedMessage {
owner.messageView.showError(message: message, icon: info.icon)
}
else if let message = info.message {
owner.messageView.showError(message: message, icon: info.icon)
}
else if let error = info.error, error.errorIsThisType(NSError.oex_unknownNetworkError()) {
owner.messageView.showError(message: Strings.unknownError, icon: info.icon)
}
else if let error = info.error, error.errorIsThisType(NSError.oex_outdatedVersionError()) {
owner.messageView.setupForOutdatedVersionError()
}
else {
owner.messageView.showError(message: info.error?.localizedDescription, icon: info.icon)
}
}
alphas = (loading : 0, message : 1, content : 0, touchable : true)
DispatchQueue.main.async {
owner.parent?.hideSnackBar()
}
}
owner.messageView.accessibilityMessage = self?.state.accessibilityMessage
owner.loadingView.alpha = alphas.loading
owner.messageView.alpha = alphas.message
owner.contentView?.alpha = alphas.content
owner.view.isUserInteractionEnabled = alphas.touchable
}
}
}
|
apache-2.0
|
9cecdd12e9d15a624444b6801ca1dd3f
| 36.313008 | 240 | 0.595054 | 5.3899 | false | false | false | false |
Shopify/mobile-buy-sdk-ios
|
Buy/Generated/Storefront/Currency.swift
|
1
|
3710
|
//
// Currency.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// A currency.
open class CurrencyQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = Currency
/// The ISO code of the currency.
@discardableResult
open func isoCode(alias: String? = nil) -> CurrencyQuery {
addField(field: "isoCode", aliasSuffix: alias)
return self
}
/// The name of the currency.
@discardableResult
open func name(alias: String? = nil) -> CurrencyQuery {
addField(field: "name", aliasSuffix: alias)
return self
}
/// The symbol of the currency.
@discardableResult
open func symbol(alias: String? = nil) -> CurrencyQuery {
addField(field: "symbol", aliasSuffix: alias)
return self
}
}
/// A currency.
open class Currency: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CurrencyQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "isoCode":
guard let value = value as? String else {
throw SchemaViolationError(type: Currency.self, field: fieldName, value: fieldValue)
}
return CurrencyCode(rawValue: value) ?? .unknownValue
case "name":
guard let value = value as? String else {
throw SchemaViolationError(type: Currency.self, field: fieldName, value: fieldValue)
}
return value
case "symbol":
guard let value = value as? String else {
throw SchemaViolationError(type: Currency.self, field: fieldName, value: fieldValue)
}
return value
default:
throw SchemaViolationError(type: Currency.self, field: fieldName, value: fieldValue)
}
}
/// The ISO code of the currency.
open var isoCode: Storefront.CurrencyCode {
return internalGetIsoCode()
}
func internalGetIsoCode(alias: String? = nil) -> Storefront.CurrencyCode {
return field(field: "isoCode", aliasSuffix: alias) as! Storefront.CurrencyCode
}
/// The name of the currency.
open var name: String {
return internalGetName()
}
func internalGetName(alias: String? = nil) -> String {
return field(field: "name", aliasSuffix: alias) as! String
}
/// The symbol of the currency.
open var symbol: String {
return internalGetSymbol()
}
func internalGetSymbol(alias: String? = nil) -> String {
return field(field: "symbol", aliasSuffix: alias) as! String
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
|
mit
|
fe139c943dd5b531b73812c1a6c63ee0
| 30.709402 | 89 | 0.709973 | 4.023861 | false | false | false | false |
venetucci/tips
|
tips/ViewController.swift
|
1
|
1404
|
//
// ViewController.swift
// tips
//
// Created by Michelle Venetucci Harvey on 1/17/15.
// Copyright (c) 2015 codepath. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipLabel.text = "$0.00"
tipLabel.text = "$0.00"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onEditingChanged(sender: AnyObject) {
var tipPercentages = [0.18, 0.2, 0.22]
var tipPercentage = tipPercentages[tipControl.selectedSegmentIndex]
var billAmount = NSString(string: billField.text).doubleValue
var tip = billAmount * tipPercentage
var total = billAmount + tip
tipLabel.text = "$\(tip)"
totalLabel.text = "$\(total)"
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
}
|
mit
|
496be17708e25fd8570bdf66e3b024fc
| 27.08 | 80 | 0.633191 | 4.588235 | false | false | false | false |
kArTeL/SwiftTMDB
|
swifttmdb/BaseMoviesViewModel.swift
|
2
|
2292
|
//
// BaseViewModel.swift
// swifttmdb
//
// Created by Christopher Jimenez on 7/24/15.
// Copyright (c) 2015 greenpixels. All rights reserved.
//
import UIKit
import RxViewModel
import RxSwift
import RxCocoa
public class BaseMoviesViewModel: RxViewModel {
/// Array of movies
public var movies = [Movie]()
/// Signal to be sent when network activity starts
public let beginLoadingSignal = PublishSubject<AnyObject?>()
/// Signal to be sent when network activity ends
public let endLoadingSignal = PublishSubject<AnyObject?>()
/// Signal to be sent when there is data to show
public let updateContentSignal = PublishSubject<[Movie]?>()
/// Reachability
//let reachability = Reachability.reachabilityForInternetConnection()
/// Current page to start the request
var currentPage = 1
/// Number of sections in the collection view
var numbersOfSections:Int{
get { return 1 }
}
/**
Number of items in the collection
:param: section section
:returns: movies count
*/
func numberOfItemsInSection(section: Int) -> Int {
return self.movies.count
}
/**
Get movie at an index path
:param: indexPath
:returns:
*/
func movieAtIndexPath(indexPath: NSIndexPath)-> Movie{
let movie = movies[indexPath.row]
return movie
}
/**
Init ViewModel
:returns: self
*/
override init(){
super.init()
self.didBecomeActive >- subscribeNext { [weak self] _ in
if let strongSelf = self{
strongSelf.active = false
strongSelf.loadData()
sendNext(strongSelf.beginLoadingSignal, nil)
}
}
}
/**
Gets data from the server and parse it
*/
func loadData(){
preconditionFailure("This method must be overridden")
}
/**
Load more movies from API
For movies in theaters we are only interested in the first 2 pages
*/
func loadMore()
{
preconditionFailure("This method must be overridden")
}
}
|
mit
|
afc2fcd02967017e8defd2cc9606b1fe
| 21.470588 | 73 | 0.577225 | 5.293303 | false | false | false | false |
JohnCoates/Aerial
|
Aerial/Source/Views/PrefPanel/InfoCommonView.swift
|
1
|
7289
|
//
// InfoCommonView.swift
// Aerial
//
// Created by Guillaume Louel on 17/12/2019.
// Copyright © 2019 Guillaume Louel. All rights reserved.
//
import Cocoa
class InfoCommonView: NSView {
var forType: InfoType = .location
var controller: OverlaysViewController?
@IBOutlet var enabledButton: NSButton!
@IBOutlet var fontLabel: NSTextField!
@IBOutlet var displaysPopup: NSPopUpButton!
@IBOutlet var posTopLeft: NSButton!
@IBOutlet var posTopCenter: NSButton!
@IBOutlet var posTopRight: NSButton!
@IBOutlet var posBottomLeft: NSButton!
@IBOutlet var posBottomCenter: NSButton!
@IBOutlet var posBottomRight: NSButton!
@IBOutlet var posScreenCenter: NSButton!
@IBOutlet var posRandom: NSButton!
// MARK: - init(ish)
// This is what tells us what we are editing exactly
func setType(_ forType: InfoType, controller: OverlaysViewController) {
// We need the controller for callbacks, when we update the isEnabled state,
// we need to update the list view on the left too
self.controller = controller
// Store type
self.forType = forType
// Update our states
enabledButton.state = PrefsInfo.ofType(forType).isEnabled ? .on : .off
setPosition(PrefsInfo.ofType(forType).corner)
displaysPopup.selectItem(at: PrefsInfo.ofType(forType).displays.rawValue)
fontLabel.stringValue = PrefsInfo.ofType(forType).fontName + ", \(PrefsInfo.ofType(forType).fontSize) pt"
switch forType {
case .location:
//controller.infoBox.title = "Video location information"
posRandom.isHidden = false
case .message:
//controller.infoBox.title = "Custom message"
posRandom.isHidden = true
case .clock:
//controller.infoBox.title = "Current time"
posRandom.isHidden = true
case .date:
//controller.infoBox.title = "Current date"
posRandom.isHidden = true
case .battery:
//controller.infoBox.title = "Battery status"
posRandom.isHidden = true
case .updates:
//controller.infoBox.title = "Updates notifications"
posRandom.isHidden = true
case .weather:
//controller.infoBox.title = "Weather provided by OpenWeather"
posRandom.isHidden = true
case .countdown:
//controller.infoBox.title = "Countdown to a time/date"
posRandom.isHidden = true
case .timer:
//controller.infoBox.title = "Timer"
posRandom.isHidden = true
case .music:
//controller.infoBox.title = "Music"
posRandom.isHidden = true
}
}
// MARK: - Position on screen
func setPosition(_ corner: InfoCorner) {
switch corner {
case .topLeft:
posTopLeft.state = .on
case .topCenter:
posTopCenter.state = .on
case .topRight:
posTopRight.state = .on
case .bottomLeft:
posBottomLeft.state = .on
case .bottomCenter:
posBottomCenter.state = .on
case .bottomRight:
posBottomRight.state = .on
case .screenCenter:
posScreenCenter.state = .on
case .random:
posRandom.state = .on
case .absTopRight:
posTopRight.state = .on
}
}
@IBAction func changePosition(_ sender: NSButton) {
var pos: InfoCorner
// Which button ?
switch sender {
case posTopLeft:
pos = .topLeft
case posTopCenter:
pos = .topCenter
case posTopRight:
pos = .topRight
case posBottomLeft:
pos = .bottomLeft
case posBottomCenter:
pos = .bottomCenter
case posBottomRight:
pos = .bottomRight
case posScreenCenter:
pos = .screenCenter
case posRandom:
pos = .random
default:
pos = .bottomLeft
}
// Then set pref
PrefsInfo.setCorner(forType, corner: pos)
}
// MARK: - Displays it should appear on
@IBAction func changeDisplays(_ sender: NSPopUpButton) {
PrefsInfo.setDisplayMode(forType, mode: InfoDisplays(rawValue: sender.indexOfSelectedItem)!)
}
// MARK: - enabled
@IBAction func enabledClick(_ sender: NSButton) {
PrefsInfo.setEnabled(forType, value: sender.state == .on)
// We need to update the side column!
controller!.infoTableView.reloadDataKeepingSelection()
}
// MARK: - Font picker
@IBAction func changeFontClick(_ sender: Any) {
// Make sure we get the callback
NSFontManager.shared.target = self
// Make a panel
if let fp = NSFontManager.shared.fontPanel(true) {
fp.setPanelFont(makeFont(name: PrefsInfo.ofType(forType).fontName,
size: PrefsInfo.ofType(forType).fontSize), isMultiple: false)
// Push the panel
fp.makeKeyAndOrderFront(sender)
}
}
func makeFont(name: String, size: Double) -> NSFont {
if let font = NSFont(name: name, size: CGFloat(size)) {
return font
} else {
// This is probably enough
return NSFont(name: "Helvetica Neue Medium", size: 28)!
}
}
@IBAction func resetFontClick(_ sender: Any) {
// We use a default font for all types
PrefsInfo.setFontName(forType, name: "Helvetica Neue Medium")
// Default Size varies though per type
switch forType {
case .location:
PrefsInfo.location.fontSize = 28
case .message:
PrefsInfo.message.fontSize = 20
case .clock:
PrefsInfo.clock.fontSize = 50
case .date:
PrefsInfo.date.fontSize = 20
case .battery:
PrefsInfo.battery.fontSize = 20
case .updates:
PrefsInfo.updates.fontSize = 20
case .weather:
PrefsInfo.weather.fontSize = 20
case .countdown:
PrefsInfo.countdown.fontSize = 100
case .timer:
PrefsInfo.timer.fontSize = 100
case .music:
PrefsInfo.music.fontSize = 20
}
fontLabel.stringValue = PrefsInfo.ofType(forType).fontName + ", \(PrefsInfo.ofType(forType).fontSize) pt"
}
}
// MARK: - Font Panel Delegates
extension InfoCommonView: NSFontChanging {
func validModesForFontPanel(_ fontPanel: NSFontPanel) -> NSFontPanel.ModeMask {
return [.size, .collection, .face]
}
func changeFont(_ sender: NSFontManager?) {
// Set current font
let oldFont = makeFont(name: PrefsInfo.ofType(forType).fontName,
size: PrefsInfo.ofType(forType).fontSize)
if let newFont = sender?.convert(oldFont) {
PrefsInfo.setFontName(forType, name: newFont.fontName)
PrefsInfo.setFontSize(forType, size: Double(newFont.pointSize))
fontLabel.stringValue = newFont.fontName + ", \(Double(newFont.pointSize)) pt"
} else {
errorLog("New font failure")
}
}
}
|
mit
|
0fc4840f0bc1cb078680b14f0263c887
| 31.247788 | 113 | 0.59742 | 4.695876 | false | false | false | false |
wireapp/wire-ios-data-model
|
Tests/Source/Model/Messages/Composite/BaseCompositeMessageTests.swift
|
1
|
2358
|
//
// Wire
// Copyright (C) 2020 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
@testable import WireDataModel
class BaseCompositeMessageTests: BaseZMMessageTests {
func compositeItemButton(buttonID: String = "1") -> Composite.Item {
return Composite.Item.with { $0.button = Button.with {
$0.text = "Button text"
$0.id = buttonID
}}
}
func compositeItemText() -> Composite.Item {
return Composite.Item.with { $0.text = Text.with { $0.content = "Text" } }
}
func compositeProto(items: Composite.Item...) -> Composite {
return Composite.with { $0.items = items }
}
func compositeMessage(with proto: Composite, nonce: UUID = UUID()) -> ZMClientMessage {
let genericMessage = GenericMessage.with {
$0.composite = proto
$0.messageID = nonce.transportString()
}
let message = ZMClientMessage(nonce: nonce, managedObjectContext: uiMOC)
do {
try message.setUnderlyingMessage(genericMessage)
} catch {
XCTFail()
}
return message
}
func conversation(withMessage message: ZMClientMessage, addSender: Bool = true) -> ZMConversation {
let user = ZMUser.insertNewObject(in: uiMOC)
user.remoteIdentifier = UUID()
message.sender = user
let conversation = ZMConversation.insertNewObject(in: uiMOC)
conversation.append(message)
guard addSender else { return conversation }
let participantRole = ParticipantRole.insertNewObject(in: uiMOC)
participantRole.user = user
conversation.participantRoles = Set([participantRole])
return conversation
}
}
|
gpl-3.0
|
de206bc9ce5addf466e6d51bbe30c519
| 32.685714 | 103 | 0.665394 | 4.605469 | false | false | false | false |
vasarhelyia/SwiftySheetsDemo
|
SwiftySheetsDemo/MasterViewController.swift
|
1
|
3293
|
//
// MasterViewController.swift
// SwiftySheetsDemo
//
// Created by Agnes Vasarhelyi on 03/07/16.
// Copyright © 2016 Agnes Vasarhelyi. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
|
mit
|
6d2cbd3c782bb01de4c5643705fff900
| 34.021277 | 154 | 0.759417 | 4.826979 | false | false | false | false |
mibaldi/IOS_MIMO_APP
|
iosAPP/BD/NotificationsDataHelper.swift
|
1
|
4934
|
//
// RecipeDataHelper.swift
// iosAPP
//
// Created by mikel balduciel diaz on 17/2/16.
// Copyright © 2016 mikel balduciel diaz. All rights reserved.
//
import Foundation
import SQLite
class NotificationsDataHelper: DataHelperProtocol {
static let TABLE_NAME = "Notifications"
static let table = Table(TABLE_NAME)
static let recipeId = Expression<Int64>("recipeId")
static let notificationId = Expression<Int64>("notificationId")
static let taskId = Expression<Int64>("taskId")
static let firedate = Expression<NSDate>("firedate")
typealias T = Notification
static func createTable() throws {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
do {
let _ = try DB.run(table.create(temporary: false, ifNotExists: true) { t in
t.column(notificationId, primaryKey: true)
t.column(recipeId)
t.column(taskId)
t.column(firedate)
})
}catch _ {
print("error create table")
}
}
static func insert (item: T) throws -> Int64 {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let insert = table.insert(recipeId <- item.recipeId,taskId <- item.taskId,firedate <- item.firedate)
do {
let rowId = try DB.run(insert)
guard rowId > 0 else {
throw DataAccessError.Insert_Error
}
return rowId
}catch _ {
throw DataAccessError.Insert_Error
}
}
static func delete (item: T) throws -> Void {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(notificationId == item.notificationId)
do {
let tmp = try DB.run(query.delete())
guard tmp == 1 else {
throw DataAccessError.Delete_Error
}
} catch _ {
throw DataAccessError.Delete_Error
}
}
static func findNotificationByTask(idTask: Int64) throws -> T? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(taskId == idTask)
let items = try DB.prepare(query)
for item in items {
let notification = Notification()
notification.notificationId = item[notificationId]
notification.taskId = item[taskId]
notification.recipeId = item[recipeId]
notification.firedate = item[firedate]
return notification
}
return nil
}
static func find(id: Int64) throws -> T? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
let query = table.filter(notificationId == id)
let items = try DB.prepare(query)
for item in items {
let notification = Notification()
notification.notificationId = item[notificationId]
notification.taskId = item[taskId]
notification.recipeId = item[recipeId]
notification.firedate = item[firedate]
return notification
}
return nil
}
static func findAll() throws -> [T]? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
var retArray = [T]()
let items = try DB.prepare(table)
for item in items {
let notification = Notification()
notification.notificationId = item[notificationId]
notification.taskId = item[taskId]
notification.recipeId = item[recipeId]
notification.firedate = item[firedate]
retArray.append(notification)
}
return retArray
}
static func findAllNotifications(id: Int64) throws -> [T]? {
guard let DB = SQLiteDataStore.sharedInstance.DB else {
throw DataAccessError.Datastore_Connection_Error
}
var retArray = [T]()
let query = table.filter(recipeId == id)
let items = try DB.prepare(query)
for item in items {
let notification = Notification()
notification.notificationId = item[notificationId]
notification.taskId = item[taskId]
notification.recipeId = item[recipeId]
notification.firedate = item[firedate]
retArray.append(notification)
}
return retArray
}
}
|
apache-2.0
|
669755d3c16af554bcb012e520e21b97
| 31.460526 | 108 | 0.58058 | 4.879327 | false | false | false | false |
sweetmans/SMInstagramPhotoPicker
|
SMInstagramPhotoPicker/Classes/AlbumModel.swift
|
2
|
3946
|
//
// AlbumModel.swift
// SMInstagramPhotosPicker
//
// Created by MacBook Pro on 2017/4/19.
// Copyright © 2017年 Sweetman, Inc. All rights reserved.
//
import Foundation
import UIKit
import Photos
public class AlbumModel {
let name:String
let count:Int
let collection:PHAssetCollection
let assets: PHFetchResult<PHAsset>
init(name:String, count:Int, collection:PHAssetCollection, assets: PHFetchResult<PHAsset>) {
self.name = name
self.count = count
self.collection = collection
self.assets = assets
}
static func listAlbums() -> [AlbumModel] {
var album:[AlbumModel] = [AlbumModel]()
let options = PHFetchOptions()
let systemAlbums = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.any, options: options)
systemAlbums.enumerateObjects({ (object: AnyObject!, count: Int, stop: UnsafeMutablePointer) in
if object is PHAssetCollection {
let obj:PHAssetCollection = object as! PHAssetCollection
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
let assets = PHAsset.fetchAssets(in: obj, options: fetchOptions)
if assets.count > 0 {
let newAlbum = AlbumModel(name: obj.localizedTitle!, count: assets.count, collection:obj, assets: assets)
album.append(newAlbum)
}
}
})
let userAlbums = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.album, subtype: PHAssetCollectionSubtype.any, options: options)
userAlbums.enumerateObjects({ (object: AnyObject!, count: Int, stop: UnsafeMutablePointer) in
if object is PHAssetCollection {
let obj:PHAssetCollection = object as! PHAssetCollection
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
let assets = PHAsset.fetchAssets(in: obj, options: fetchOptions)
if assets.count > 0 {
let newAlbum = AlbumModel(name: obj.localizedTitle!, count: assets.count, collection: obj, assets: assets)
album.append(newAlbum)
}
}
})
return album
}
func fetchFirstImage(returnImage: @escaping (UIImage) -> Void) {
DispatchQueue.global(qos: .default).async(execute: {
let op = PHFetchOptions()
op.fetchLimit = 1
op.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let assets = PHAsset.fetchAssets(in: self.collection, options: op)
let rop = PHImageRequestOptions()
rop.isNetworkAccessAllowed = true
if assets.firstObject != nil {
let ts = CGSize(width: assets.firstObject!.pixelWidth, height: assets.firstObject!.pixelHeight)
PHImageManager.default().requestImage(for: assets.firstObject!, targetSize: ts, contentMode: .aspectFill, options: rop, resultHandler: { (image, info) in
if image != nil {
DispatchQueue.main.async {
returnImage(image!)
}
}
})
}
})
}
}
|
mit
|
a6f42724fdca9b4f47f5f4b1274fc950
| 35.509259 | 169 | 0.583566 | 5.561354 | false | false | false | false |
jainanisha90/codepath_Twitter
|
Twitter/TwitterClient.swift
|
1
|
6555
|
//
// TwitterClient.swift
// Twitter
//
// Created by Anisha Jain on 4/14/17.
// Copyright © 2017 Anisha Jain. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
let twitterConsumerKey = "2wBWxpkRFY6io5dZTY0uT7y61"
let twitterConsumerSecret = "6NdyWeWsDOMCpwHsntMTraTIWX6iSjYFF6J1yuTo4UNHxhQOvk"
let twitterBaseURL = URL(string: "https://api.twitter.com")
class TwitterClient: BDBOAuth1SessionManager {
var loginSuccess: (() -> ())?
var loginFailure: ((Error) -> ())?
class var sharedInstance: TwitterClient {
struct Static {
static let instance = TwitterClient(baseURL: twitterBaseURL, consumerKey: twitterConsumerKey, consumerSecret: twitterConsumerSecret)
}
return Static.instance!
}
func login(success: @escaping () -> (), failure: @escaping (Error) -> ()) {
loginSuccess = success
loginFailure = failure
// Fetch request token and redirect to authorization page
requestSerializer.removeAccessToken()
fetchRequestToken(withPath: "oauth/request_token", method: "GET", callbackURL:
URL(string: "twitterdemotrial://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -> Void in
print("Got request token")
let authURL = URL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token!)")
UIApplication.shared.open(authURL!)
}) { (error: Error!) -> Void in
print("failed to get request token")
self.loginFailure?(error)
}
print("escaping")
}
func logout() {
User.currentUser = nil
deauthorize()
NotificationCenter.default.post(name: Notifications.userDidLogoutNotification.name, object: nil)
}
func currentAccount(success: @escaping (User) -> (), failure: @escaping (Error) -> ()) {
self.get("1.1/account/verify_credentials.json", parameters: nil, success:
{ (operation: URLSessionDataTask!, response: Any!) -> Void in
let user = User(dictionary: response as! NSDictionary)
success(user)
User.currentUser = user
print("user: ", user.name!)
self.loginSuccess?()
}, failure: { (operation: URLSessionDataTask!, error: Error!) -> Void in
failure(error)
print("Error getting current user")
})
}
func homeTimelineWithParams(params: NSDictionary?, completion: @escaping (_ tweets: [Tweet]?, _ error: Error?) -> ()) {
get("1.1/statuses/home_timeline.json", parameters: params,
success: { (operation: URLSessionDataTask!, response: Any!) -> Void in
let tweets = Tweet.tweetsWithArray(array: response as! [NSDictionary])
completion(tweets, nil)
//print("hometimeline: ", response)
}, failure: { (operation: URLSessionDataTask!, error: Error!) -> Void in
print("Error getting home timeline", error)
completion(nil, error)
})
}
private func sendUpdate(params: Any?, success: @escaping () -> (), failure: @escaping (Error) -> ()) {
post("1.1/statuses/update.json", parameters: params,
success: { (operation: URLSessionDataTask, response: Any) in
success()
//print("newTweet response: ", response)
}) { (urlSessionDataTask, error) in
print("Falied to post a tweet")
failure(error)
}
}
func newTweet(tweetMessage: String, success: @escaping () -> (), failure: @escaping (Error) -> ()) {
let params = ["status": tweetMessage]
sendUpdate(params: params, success: success, failure: failure)
}
func reply(tweetMessage: String, tweetId: String, success: @escaping () ->(), failure: @escaping (Error) -> ()) {
let params = ["status": tweetMessage, "in_reply_to_status_id": tweetId]
sendUpdate(params: params, success: success, failure: failure)
}
func retweet(tweetId: String, success: @escaping () -> (), failure: @escaping (Error) -> ()) {
print("tweet API: 1.1/statuses/retweet/\(tweetId).json")
post("1.1/statuses/retweet/\(tweetId).json", parameters: nil,
success: { (operation: URLSessionDataTask, response: Any) in
success()
//print("retweet response: ", response)
}) { (urlSessionDataTask, error) in
print("Falied to retweet")
failure(error)
}
}
func createFavorite(tweetId: String, success: @escaping () -> (), failure: @escaping (Error) -> ()) {
let params = ["id": tweetId]
post("1.1/favorites/create.json", parameters: params,
success: { (operation: URLSessionDataTask, response: Any) in
success()
//print("createFavorite response: ", response)
}) { (urlSessionDataTask, error) in
print("Falied to create favorite tweet")
failure(error)
}
}
func removeFavorite(tweetId: String, success: @escaping () -> (), failure: @escaping (Error) -> ()) {
let params = ["id": tweetId]
post("1.1/favorites/destroy.json", parameters: params,
success: { (operation: URLSessionDataTask, response: Any) in
success()
//print("removeFavorite response: ", response)
}) { (urlSessionDataTask, error) in
print("Falied to remove favorite tweet")
failure(error)
}
}
func handleOpenURL(url: URL) {
fetchAccessToken(withPath: "oauth/access_token",
method: "POST",
requestToken: BDBOAuth1Credential(queryString: url.query),
success: { (access_token: BDBOAuth1Credential!) -> Void in
print("got access token")
self.requestSerializer.saveAccessToken(access_token)
self.currentAccount(success: { (user: User) in
User.currentUser = user
self.loginSuccess?()
}, failure: { (error: Error) in
self.loginFailure?(error)
})
}) { (error: Error!) -> Void in
print("failed to get access token")
self.loginFailure?(error)
}
}
}
|
mit
|
a5ca58ea1cf75ac2eec9ea6881a97216
| 41.836601 | 144 | 0.570644 | 4.641643 | false | false | false | false |
matthewpurcell/firefox-ios
|
Client/Frontend/Browser/Browser.swift
|
1
|
16171
|
/* 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 WebKit
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
protocol BrowserHelper {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol BrowserDelegate {
func browser(browser: Browser, didAddSnackbar bar: SnackBar)
func browser(browser: Browser, didRemoveSnackbar bar: SnackBar)
func browser(browser: Browser, didSelectFindInPageForSelection selection: String)
optional func browser(browser: Browser, didCreateWebView webView: WKWebView)
optional func browser(browser: Browser, willDeleteWebView webView: WKWebView)
}
class Browser: NSObject, BrowserWebViewDelegate {
private var _isPrivate: Bool = false
internal private(set) var isPrivate: Bool {
get {
if #available(iOS 9, *) {
return _isPrivate
} else {
return false
}
}
set {
_isPrivate = newValue
}
}
var webView: WKWebView? = nil
var browserDelegate: BrowserDelegate? = nil
var bars = [SnackBar]()
var favicons = [Favicon]()
var lastExecutedTime: Timestamp?
var sessionData: SessionData?
var lastRequest: NSURLRequest? = nil
var restoring: Bool = false
var pendingScreenshot = false
/// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs.
var lastTitle: String?
/// Whether or not the desktop site was requested with the last request, reload or navigation. Note that this property needs to
/// be managed by the web view's navigation delegate.
var desktopSite: Bool = false
private(set) var screenshot: UIImage?
var screenshotUUID: NSUUID?
private var helperManager: HelperManager? = nil
private var configuration: WKWebViewConfiguration? = nil
/// Any time a browser tries to make requests to display a Javascript Alert and we are not the active
/// browser instance, queue it for later until we become foregrounded.
private var alertQueue = [JSAlertInfo]()
init(configuration: WKWebViewConfiguration) {
self.configuration = configuration
}
@available(iOS 9, *)
init(configuration: WKWebViewConfiguration, isPrivate: Bool) {
self.configuration = configuration
super.init()
self.isPrivate = isPrivate
}
class func toTab(browser: Browser) -> RemoteTab? {
if let displayURL = browser.displayURL {
let history = Array(browser.historyList.filter(RemoteTab.shouldIncludeURL).reverse())
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: browser.displayTitle,
history: history,
lastUsed: NSDate.now(),
icon: nil)
} else if let sessionData = browser.sessionData where !sessionData.urls.isEmpty {
let history = Array(sessionData.urls.reverse())
return RemoteTab(clientGUID: nil,
URL: history[0],
title: browser.displayTitle,
history: history,
lastUsed: sessionData.lastUsedTime,
icon: nil)
}
return nil
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
assert(configuration != nil, "Create webview can only be called once")
configuration!.userContentController = WKUserContentController()
configuration!.preferences = WKPreferences()
configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false
let webView = BrowserWebView(frame: CGRectZero, configuration: configuration!)
webView.delegate = self
configuration = nil
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.allowsBackForwardNavigationGestures = true
webView.backgroundColor = UIColor.lightGrayColor()
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
helperManager = HelperManager(webView: webView)
restore(webView)
self.webView = webView
browserDelegate?.browser?(self, didCreateWebView: webView)
// lastTitle is used only when showing zombie tabs after a session restore.
// Since we now have a web view, lastTitle is no longer useful.
lastTitle = nil
}
}
func restore(webView: WKWebView) {
// Pulls restored session data from a previous SavedTab to load into the Browser. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
restoring = true
var updatedURLs = [String]()
for url in sessionData.urls {
let updatedURL = WebServer.sharedInstance.updateLocalURL(url)!.absoluteString
updatedURLs.append(updatedURL)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = updatedURLs
jsonDict["currentPage"] = currentPage
let escapedJSON = JSON.stringify(jsonDict, pretty: false).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let restoreURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)")
lastRequest = NSURLRequest(URL: restoreURL!)
webView.loadRequest(lastRequest!)
} else if let request = lastRequest {
webView.loadRequest(request)
} else {
log.error("creating webview with no lastRequest and no session data: \(self.url)")
}
}
deinit {
if let webView = webView {
browserDelegate?.browser?(self, willDeleteWebView: webView)
}
}
var loading: Bool {
return webView?.loading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList
}
var historyList: [NSURL] {
func listToUrl(item: WKBackForwardListItem) -> NSURL { return item.URL }
var tabs = self.backList?.map(listToUrl) ?? [NSURL]()
tabs.append(self.url!)
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title {
if !title.isEmpty {
return title
}
}
return displayURL?.absoluteString ?? lastTitle ?? ""
}
var currentInitialURL: NSURL? {
get {
let initalURL = self.webView?.backForwardList.currentItem?.initialURL
return initalURL
}
}
var displayFavicon: Favicon? {
var width = 0
var largest: Favicon?
for icon in favicons {
if icon.width > width {
width = icon.width!
largest = icon
}
}
return largest
}
var url: NSURL? {
guard let resolvedURL = webView?.URL ?? lastRequest?.URL else {
guard let sessionData = sessionData else { return nil }
return sessionData.urls.last
}
return resolvedURL
}
var displayURL: NSURL? {
if let url = url {
if ReaderModeUtils.isReaderModeURL(url) {
return ReaderModeUtils.decodeURL(url)
}
if ErrorPageHelper.isErrorPageURL(url) {
let decodedURL = ErrorPageHelper.decodeURL(url)
if !AboutUtils.isAboutURL(decodedURL) {
return decodedURL
} else {
return nil
}
}
if let urlComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) where (urlComponents.user != nil) || (urlComponents.password != nil) {
urlComponents.user = nil
urlComponents.password = nil
return urlComponents.URL
}
if !AboutUtils.isAboutURL(url) {
return url
}
}
return nil
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
webView?.goBack()
}
func goForward() {
webView?.goForward()
}
func goToBackForwardListItem(item: WKBackForwardListItem) {
webView?.goToBackForwardListItem(item)
}
func loadRequest(request: NSURLRequest) -> WKNavigation? {
if let webView = webView {
lastRequest = request
return webView.loadRequest(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
if #available(iOS 9.0, *) {
let userAgent: String? = desktopSite ? UserAgent.desktopUserAgent() : nil
if (userAgent ?? "") != webView?.customUserAgent,
let currentItem = webView?.backForwardList.currentItem
{
webView?.customUserAgent = userAgent
// Reload the initial URL to avoid UA specific redirection
loadRequest(NSURLRequest(URL: currentItem.initialURL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 60))
return
}
}
if let _ = webView?.reloadFromOrigin() {
log.info("reloaded zombified tab from origin")
return
}
if let webView = self.webView {
log.info("restoring webView from scratch")
restore(webView)
}
}
func addHelper(helper: BrowserHelper, name: String) {
helperManager!.addHelper(helper, name: name)
}
func getHelper(name name: String) -> BrowserHelper? {
return helperManager?.getHelper(name: name)
}
func hideContent(animated: Bool = false) {
webView?.userInteractionEnabled = false
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(animated: Bool = false) {
webView?.userInteractionEnabled = true
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(bar: SnackBar) {
bars.append(bar)
browserDelegate?.browser(self, didAddSnackbar: bar)
}
func removeSnackbar(bar: SnackBar) {
if let index = bars.indexOf(bar) {
bars.removeAtIndex(index)
browserDelegate?.browser(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
removeSnackbar(bar)
}
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
if !bar.shouldPersist(self) {
removeSnackbar(bar)
}
}
}
func setScreenshot(screenshot: UIImage?, revUUID: Bool = true) {
self.screenshot = screenshot
if revUUID {
self.screenshotUUID = NSUUID()
}
}
@available(iOS 9, *)
func toggleDesktopSite() {
desktopSite = !desktopSite
reload()
}
func queueJavascriptAlertPrompt(alert: JSAlertInfo) {
alertQueue.append(alert)
}
func dequeueJavascriptAlertPrompt() -> JSAlertInfo? {
guard !alertQueue.isEmpty else {
return nil
}
return alertQueue.removeFirst()
}
func cancelQueuedAlerts() {
alertQueue.forEach { alert in
alert.cancel()
}
}
private func browserWebView(browserWebView: BrowserWebView, didSelectFindInPageForSelection selection: String) {
browserDelegate?.browser(self, didSelectFindInPageForSelection: selection)
}
}
private class HelperManager: NSObject, WKScriptMessageHandler {
private var helpers = [String: BrowserHelper]()
private weak var webView: WKWebView?
init(webView: WKWebView) {
self.webView = webView
}
@objc func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
if scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
}
func addHelper(helper: BrowserHelper, name: String) {
if let _ = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right BrowserHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
webView?.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName)
}
}
func getHelper(name name: String) -> BrowserHelper? {
return helpers[name]
}
}
private protocol BrowserWebViewDelegate: class {
func browserWebView(browserWebView: BrowserWebView, didSelectFindInPageForSelection selection: String)
}
private class BrowserWebView: WKWebView, MenuHelperInterface {
private weak var delegate: BrowserWebViewDelegate?
override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
return action == MenuHelper.SelectorFindInPage
}
@objc func menuHelperFindInPage(sender: NSNotification) {
evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
self.delegate?.browserWebView(self, didSelectFindInPageForSelection: selection)
}
}
private override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
// The find-in-page selection menu only appears if the webview is the first responder.
becomeFirstResponder()
return super.hitTest(point, withEvent: event)
}
}
|
mpl-2.0
|
7171a4be35679e3ea6e683f9590c2f35
| 32.413223 | 167 | 0.619257 | 5.44845 | false | false | false | false |
matthewpurcell/firefox-ios
|
Sync/StorageClient.swift
|
1
|
28364
|
/* 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 Alamofire
import Shared
import Account
import XCGLogger
import Deferred
private let log = Logger.syncLogger
// Not an error that indicates a server problem, but merely an
// error that encloses a StorageResponse.
public class StorageResponseError<T>: MaybeErrorType {
public let response: StorageResponse<T>
public init(_ response: StorageResponse<T>) {
self.response = response
}
public var description: String {
return "Error."
}
}
public class RequestError: MaybeErrorType {
public var description: String {
return "Request error."
}
}
public class BadRequestError<T>: StorageResponseError<T> {
public let request: NSURLRequest?
public init(request: NSURLRequest?, response: StorageResponse<T>) {
self.request = request
super.init(response)
}
override public var description: String {
return "Bad request."
}
}
public class ServerError<T>: StorageResponseError<T> {
override public var description: String {
return "Server error."
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
public class NotFound<T>: StorageResponseError<T> {
override public var description: String {
return "Not found. (\(T.self))"
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
public class RecordParseError: MaybeErrorType {
public var description: String {
return "Failed to parse record."
}
}
public class MalformedMetaGlobalError: MaybeErrorType {
public var description: String {
return "Supplied meta/global for upload did not serialize to valid JSON."
}
}
/**
* Raised when the storage client is refusing to make a request due to a known
* server backoff.
* If you want to bypass this, remove the backoff from the BackoffStorage that
* the storage client is using.
*/
public class ServerInBackoffError: MaybeErrorType {
private let until: Timestamp
public var description: String {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.ShortStyle
formatter.timeStyle = NSDateFormatterStyle.MediumStyle
let s = formatter.stringFromDate(NSDate.fromTimestamp(self.until))
return "Server in backoff until \(s)."
}
public init(until: Timestamp) {
self.until = until
}
}
// Returns milliseconds. Handles decimals.
private func optionalSecondsHeader(input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
if let timestamp = decimalSecondsStringToTimestamp(val) {
return timestamp
}
}
if let seconds: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(seconds * 1000)
}
if let seconds: NSNumber = input as? NSNumber {
// Who knows.
return seconds.unsignedLongLongValue * 1000
}
return nil
}
private func optionalIntegerHeader(input: AnyObject?) -> Int64? {
if input == nil {
return nil
}
if let val = input as? String {
return NSScanner(string: val).scanLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Int64(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.longLongValue
}
return nil
}
private func optionalUIntegerHeader(input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
return NSScanner(string: val).scanUnsignedLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.unsignedLongLongValue
}
return nil
}
public enum SortOption: String {
case NewestFirst = "newest"
case OldestFirst = "oldest"
case Index = "index"
}
public struct ResponseMetadata {
public let status: Int
public let alert: String?
public let nextOffset: String?
public let records: UInt64?
public let quotaRemaining: Int64?
public let timestampMilliseconds: Timestamp // Non-optional. Server timestamp when handling request.
public let lastModifiedMilliseconds: Timestamp? // Included for all success responses. Collection or record timestamp.
public let backoffMilliseconds: UInt64?
public let retryAfterMilliseconds: UInt64?
public init(response: NSHTTPURLResponse) {
self.init(status: response.statusCode, headers: response.allHeaderFields)
}
init(status: Int, headers: [NSObject : AnyObject]) {
self.status = status
alert = headers["X-Weave-Alert"] as? String
nextOffset = headers["X-Weave-Next-Offset"] as? String
records = optionalUIntegerHeader(headers["X-Weave-Records"])
quotaRemaining = optionalIntegerHeader(headers["X-Weave-Quota-Remaining"])
timestampMilliseconds = optionalSecondsHeader(headers["X-Weave-Timestamp"]) ?? 0
lastModifiedMilliseconds = optionalSecondsHeader(headers["X-Last-Modified"])
backoffMilliseconds = optionalSecondsHeader(headers["X-Weave-Backoff"]) ??
optionalSecondsHeader(headers["X-Backoff"])
retryAfterMilliseconds = optionalSecondsHeader(headers["Retry-After"])
}
}
public struct StorageResponse<T> {
public let value: T
public let metadata: ResponseMetadata
init(value: T, metadata: ResponseMetadata) {
self.value = value
self.metadata = metadata
}
init(value: T, response: NSHTTPURLResponse) {
self.value = value
self.metadata = ResponseMetadata(response: response)
}
}
public struct POSTResult {
public let modified: Timestamp
public let success: [GUID]
public let failed: [GUID: [String]]
public static func fromJSON(json: JSON) -> POSTResult? {
if json.isError {
return nil
}
if let mDecimalSeconds = json["modified"].asDouble,
let s = json["success"].asArray,
let f = json["failed"].asDictionary {
var failed = false
let asStringOrFail: JSON -> String = { $0.asString ?? { failed = true; return "" }() }
let asArrOrFail: JSON -> [String] = { $0.asArray?.map(asStringOrFail) ?? { failed = true; return [] }() }
// That's the basic structure. Now let's transform the contents.
let successGUIDs = s.map(asStringOrFail)
if failed {
return nil
}
let failedGUIDs = mapValues(f, f: asArrOrFail)
if failed {
return nil
}
let msec = Timestamp(1000 * mDecimalSeconds)
return POSTResult(modified: msec, success: successGUIDs, failed: failedGUIDs)
}
return nil
}
}
public typealias Authorizer = (NSMutableURLRequest) -> NSMutableURLRequest
public typealias ResponseHandler = (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>) -> Void
// TODO: don't be so naïve. Use a combination of uptime and wall clock time.
public protocol BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp? { get set }
func clearServerBackoff()
func isInBackoff(now: Timestamp) -> Timestamp? // Returns 'until' for convenience.
}
// Don't forget to batch downloads.
public class Sync15StorageClient {
private let authorizer: Authorizer
private let serverURI: NSURL
var backoff: BackoffStorage
let workQueue: dispatch_queue_t
let resultQueue: dispatch_queue_t
public init(token: TokenServerToken, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t, backoff: BackoffStorage) {
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
// This is a potentially dangerous assumption, but failable initializers up the stack are a giant pain.
// We want the serverURI to *not* have a trailing slash: to efficiently wipe a user's storage, we delete
// the user root (like /1.5/1234567) and not an "empty collection" (like /1.5/1234567/); the storage
// server treats the first like a DROP table and the latter like a DELETE *, and the former is more
// efficient than the latter.
self.serverURI = NSURL(string: token.api_endpoint.endsWith("/")
? token.api_endpoint.substringToIndex(token.api_endpoint.endIndex.predecessor())
: token.api_endpoint)!
self.authorizer = {
(r: NSMutableURLRequest) -> NSMutableURLRequest in
let helper = HawkHelper(id: token.id, key: token.key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
r.setValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization")
return r
}
}
public init(serverURI: NSURL, authorizer: Authorizer, workQueue: dispatch_queue_t, resultQueue: dispatch_queue_t, backoff: BackoffStorage) {
self.serverURI = serverURI
self.authorizer = authorizer
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
}
func updateBackoffFromResponse<T>(response: StorageResponse<T>) {
// N.B., we would not have made this request if a backoff were set, so
// we can safely avoid doing the write if there's no backoff in the
// response.
// This logic will have to change if we ever invalidate that assumption.
if let ms = response.metadata.backoffMilliseconds ?? response.metadata.retryAfterMilliseconds {
log.info("Backing off for \(ms)ms.")
self.backoff.serverBackoffUntilLocalTimestamp = ms + NSDate.now()
}
}
func errorWrap<T>(deferred: Deferred<Maybe<T>>, handler: ResponseHandler) -> ResponseHandler {
return { (request, response, result) in
log.verbose("Response is \(response).")
/**
* Returns true if handled.
*/
func failFromResponse(response: NSHTTPURLResponse?) -> Bool {
guard let response = response else {
// TODO: better error.
log.error("No response")
let result = Maybe<T>(failure: RecordParseError())
deferred.fill(result)
return true
}
log.debug("Status code: \(response.statusCode).")
let storageResponse = StorageResponse(value: response, metadata: ResponseMetadata(response: response))
self.updateBackoffFromResponse(storageResponse)
if response.statusCode >= 500 {
log.debug("ServerError.")
let result = Maybe<T>(failure: ServerError(storageResponse))
deferred.fill(result)
return true
}
if response.statusCode == 404 {
log.debug("NotFound<\(T.self)>.")
let result = Maybe<T>(failure: NotFound(storageResponse))
deferred.fill(result)
return true
}
if response.statusCode >= 400 {
log.debug("BadRequestError.")
let result = Maybe<T>(failure: BadRequestError(request: request, response: storageResponse))
deferred.fill(result)
return true
}
return false
}
// Check for an error from the request processor.
if result.isFailure {
log.error("Response: \(response?.statusCode ?? 0). Got error \(result.error).")
// If we got one, we don't want to hit the response nil case above and
// return a RecordParseError, because a RequestError is more fitting.
if let response = response {
if failFromResponse(response) {
log.error("This was a failure response. Filled specific error type.")
return
}
}
log.error("Filling generic RequestError.")
deferred.fill(Maybe<T>(failure: RequestError()))
return
}
if failFromResponse(response) {
return
}
handler(request, response, result)
}
}
lazy private var alamofire: Alamofire.Manager = {
let ua = UserAgent.syncUserAgent
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
return Alamofire.Manager.managerWithUserAgent(ua, configuration: configuration)
}()
func requestGET(url: NSURL) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = Method.GET.rawValue
req.setValue("application/json", forHTTPHeaderField: "Accept")
let authorized: NSMutableURLRequest = self.authorizer(req)
return alamofire.request(authorized)
.validate(contentType: ["application/json"])
}
func requestDELETE(url: NSURL) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = Method.DELETE.rawValue
req.setValue("1", forHTTPHeaderField: "X-Confirm-Delete")
let authorized: NSMutableURLRequest = self.authorizer(req)
return alamofire.request(authorized)
}
func requestWrite(url: NSURL, method: String, body: String, contentType: String, ifUnmodifiedSince: Timestamp?) -> Request {
let req = NSMutableURLRequest(URL: url)
req.HTTPMethod = method
req.setValue(contentType, forHTTPHeaderField: "Content-Type")
let authorized: NSMutableURLRequest = self.authorizer(req)
if let ifUnmodifiedSince = ifUnmodifiedSince {
req.setValue(millisecondsToDecimalSeconds(ifUnmodifiedSince), forHTTPHeaderField: "X-If-Unmodified-Since")
}
req.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)!
return alamofire.request(authorized)
}
func requestPUT(url: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: Method.PUT.rawValue, body: body.toString(false), contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(url: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: Method.POST.rawValue, body: body.toString(false), contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(url: NSURL, body: [JSON], ifUnmodifiedSince: Timestamp?) -> Request {
let body = body.map { $0.toString(false) }.joinWithSeparator("\n")
return self.requestWrite(url, method: Method.POST.rawValue, body: body, contentType: "application/newlines", ifUnmodifiedSince: ifUnmodifiedSince)
}
/**
* Returns true and fills the provided Deferred if our state shows that we're in backoff.
* Returns false otherwise.
*/
private func checkBackoff<T>(deferred: Deferred<Maybe<T>>) -> Bool {
if let until = self.backoff.isInBackoff(NSDate.now()) {
deferred.fill(Maybe<T>(failure: ServerInBackoffError(until: until)))
return true
}
return false
}
private func doOp<T>(op: (NSURL) -> Request, path: String, f: (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
// Special case "": we want /1.5/1234567 and not /1.5/1234567/. See note about trailing slashes above.
let url: NSURL
if path == "" {
url = self.serverURI // No trailing slash.
} else {
url = self.serverURI.URLByAppendingPathComponent(path)
}
let req = op(url)
let handler = self.errorWrap(deferred) { (_, response, result) in
if let json: JSON = result.value as? JSON {
if let v = f(json) {
let storageResponse = StorageResponse<T>(value: v, response: response!)
deferred.fill(Maybe(success: storageResponse))
} else {
deferred.fill(Maybe(failure: RecordParseError()))
}
return
}
deferred.fill(Maybe(failure: RecordParseError()))
}
req.responseParsedJSON(true, completionHandler: handler)
return deferred
}
// Sync storage responds with a plain timestamp to a PUT, not with a JSON body.
private func putResource<T>(path: String, body: JSON, ifUnmodifiedSince: Timestamp?, parser: (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let url = self.serverURI.URLByAppendingPathComponent(path)
return self.putResource(url, body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: parser)
}
private func putResource<T>(URL: NSURL, body: JSON, ifUnmodifiedSince: Timestamp?, parser: (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
let req = self.requestPUT(URL, body: body, ifUnmodifiedSince: ifUnmodifiedSince)
let handler = self.errorWrap(deferred) { (_, response, result) in
if let data = result.value as? String {
if let v = parser(data) {
let storageResponse = StorageResponse<T>(value: v, response: response!)
deferred.fill(Maybe(success: storageResponse))
} else {
deferred.fill(Maybe(failure: RecordParseError()))
}
return
}
deferred.fill(Maybe(failure: RecordParseError()))
}
let stringHandler = { (a: NSURLRequest?, b: NSHTTPURLResponse?, c: Result<String>) in
return handler(a, b, c.isSuccess ? Result.Success(c.value!) : Result.Failure(c.data, c.error!))
}
req.responseString(encoding: nil, completionHandler: stringHandler)
return deferred
}
private func getResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
return doOp(self.requestGET, path: path, f: f)
}
private func deleteResource<T>(path: String, f: (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
return doOp(self.requestDELETE, path: path, f: f)
}
func wipeStorage() -> Deferred<Maybe<StorageResponse<JSON>>> {
// In Sync 1.5 it's preferred that we delete the root, not /storage.
return deleteResource("", f: { $0 })
}
func getInfoCollections() -> Deferred<Maybe<StorageResponse<InfoCollections>>> {
return getResource("info/collections", f: InfoCollections.fromJSON)
}
func getMetaGlobal() -> Deferred<Maybe<StorageResponse<MetaGlobal>>> {
return getResource("storage/meta/global") { json in
// We have an envelope. Parse the meta/global record embedded in the 'payload' string.
let envelope = EnvelopeJSON(json)
if envelope.isValid() {
return MetaGlobal.fromJSON(JSON.parse(envelope.payload))
}
return nil
}
}
func getCryptoKeys(syncKeyBundle: KeyBundle, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Record<KeysPayload>>>> {
let syncKey = Keys(defaultBundle: syncKeyBundle)
let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0 })
let encrypter = syncKey.encrypter("keys", encoder: encoder)
let client = self.clientForCollection("crypto", encrypter: encrypter)
return client.get("keys")
}
func uploadMetaGlobal(metaGlobal: MetaGlobal, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
let payload = metaGlobal.asPayload()
if payload.isError {
return Deferred(value: Maybe(failure: MalformedMetaGlobalError()))
}
let record: JSON = JSON(["payload": payload.toString(), "id": "global"])
return putResource("storage/meta/global", body: record, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
// The crypto/keys record is a special snowflake: it is encrypted with the Sync key bundle. All other records are
// encrypted with the bulk key bundle (including possibly a per-collection bulk key) stored in crypto/keys.
func uploadCryptoKeys(keys: Keys, withSyncKeyBundle syncKeyBundle: KeyBundle, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
let syncKey = Keys(defaultBundle: syncKeyBundle)
let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0 })
let encrypter = syncKey.encrypter("keys", encoder: encoder)
let client = self.clientForCollection("crypto", encrypter: encrypter)
let record = Record(id: "keys", payload: keys.asPayload())
return client.put(record, ifUnmodifiedSince: ifUnmodifiedSince)
}
// It would be convenient to have the storage client manage Keys, but of course we need to use a different set of
// keys to fetch crypto/keys itself. See uploadCryptoKeys.
func clientForCollection<T: CleartextPayloadJSON>(collection: String, encrypter: RecordEncrypter<T>) -> Sync15CollectionClient<T> {
let storage = self.serverURI.URLByAppendingPathComponent("storage", isDirectory: true)
return Sync15CollectionClient(client: self, serverURI: storage, collection: collection, encrypter: encrypter)
}
}
/**
* We'd love to nest this in the overall storage client, but Swift
* forbids the nesting of a generic class inside another class.
*/
public class Sync15CollectionClient<T: CleartextPayloadJSON> {
private let client: Sync15StorageClient
private let encrypter: RecordEncrypter<T>
private let collectionURI: NSURL
private let collectionQueue = dispatch_queue_create("com.mozilla.sync.collectionclient", DISPATCH_QUEUE_SERIAL)
init(client: Sync15StorageClient, serverURI: NSURL, collection: String, encrypter: RecordEncrypter<T>) {
self.client = client
self.encrypter = encrypter
self.collectionURI = serverURI.URLByAppendingPathComponent(collection, isDirectory: false)
}
private func uriForRecord(guid: String) -> NSURL {
return self.collectionURI.URLByAppendingPathComponent(guid)
}
public func post(records: [Record<T>], ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<POSTResult>>> {
let deferred = Deferred<Maybe<StorageResponse<POSTResult>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
// TODO: charset
// TODO: if any of these fail, we should do _something_. Right now we just ignore them.
let json = optFilter(records.map(self.encrypter.serializer))
let req = client.requestPOST(self.collectionURI, body: json, ifUnmodifiedSince: nil)
req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (_, response, result) in
if let json: JSON = result.value as? JSON,
let result = POSTResult.fromJSON(json) {
let storageResponse = StorageResponse(value: result, response: response!)
deferred.fill(Maybe(success: storageResponse))
return
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Maybe(failure: RecordParseError()))
})
return deferred
}
public func put(record: Record<T>, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
if let body = self.encrypter.serializer(record) {
return self.client.putResource(uriForRecord(record.id), body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
return deferMaybe(RecordParseError())
}
public func get(guid: String) -> Deferred<Maybe<StorageResponse<Record<T>>>> {
let deferred = Deferred<Maybe<StorageResponse<Record<T>>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
let req = client.requestGET(uriForRecord(guid))
req.responsePartialParsedJSON(queue:collectionQueue, completionHandler: self.client.errorWrap(deferred) { (_, response, result) in
if let json: JSON = result.value as? JSON {
let envelope = EnvelopeJSON(json)
let record = Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
if let record = record {
let storageResponse = StorageResponse(value: record, response: response!)
deferred.fill(Maybe(success: storageResponse))
return
}
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Maybe(failure: RecordParseError()))
})
return deferred
}
/**
* Unlike every other Sync client, we use the application/json format for fetching
* multiple requests. The others use application/newlines. We don't want to write
* another Serializer, and we're loading everything into memory anyway.
*/
public func getSince(since: Timestamp, sort: SortOption?=nil, limit: Int?=nil, offset: String?=nil) -> Deferred<Maybe<StorageResponse<[Record<T>]>>> {
let deferred = Deferred<Maybe<StorageResponse<[Record<T>]>>>(defaultQueue: client.resultQueue)
// Fills the Deferred for us.
if self.client.checkBackoff(deferred) {
return deferred
}
var params: [NSURLQueryItem] = [
NSURLQueryItem(name: "full", value: "1"),
NSURLQueryItem(name: "newer", value: millisecondsToDecimalSeconds(since)),
]
if let offset = offset {
params.append(NSURLQueryItem(name: "offset", value: offset))
}
if let limit = limit {
params.append(NSURLQueryItem(name: "limit", value: "\(limit)"))
}
if let sort = sort {
params.append(NSURLQueryItem(name: "sort", value: sort.rawValue))
}
log.debug("Issuing GET with newer = \(since).")
let req = client.requestGET(self.collectionURI.withQueryParams(params))
req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (_, response, result) in
log.verbose("Response is \(response).")
guard let json: JSON = result.value as? JSON else {
log.warning("Non-JSON response.")
deferred.fill(Maybe(failure: RecordParseError()))
return
}
guard let arr = json.asArray else {
log.warning("Non-array response.")
deferred.fill(Maybe(failure: RecordParseError()))
return
}
func recordify(json: JSON) -> Record<T>? {
let envelope = EnvelopeJSON(json)
return Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
}
let records = optFilter(arr.map(recordify))
let response = StorageResponse(value: records, response: response!)
deferred.fill(Maybe(success: response))
})
return deferred
}
}
|
mpl-2.0
|
0f64ff4fe27f9cf93d94c9fee36d1594
| 37.906722 | 180 | 0.637062 | 4.845891 | false | false | false | false |
Kushki/kushki-ios
|
Kushki/Classes/Infrastructure/KushkiEnvironment.swift
|
1
|
395
|
public enum KushkiEnvironment: String {
case testing = "https://api-uat.kushkipagos.com"
case production = "https://api.kushkipagos.com"
case testing_regional = "https://regional-uat.kushkipagos.com"
case production_regional = "https://regional.kushkipagos.com"
case testing_ci = "https://api-ci.kushkipagos.com"
case testing_qa = "https://api-qa.kushkipagos.com"
}
|
mit
|
c51ac5111c2dd6b974f3971f93e354a9
| 42.888889 | 66 | 0.701266 | 2.947761 | false | true | false | false |
mohamede1945/quran-ios
|
Quran/AppDelegate.swift
|
1
|
2453
|
//
// AppDelegate.swift
// Quran
//
// Created by Mohamed Afifi on 4/18/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import Crashlytics
import Fabric
import PromiseKit
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let container: Container
override init() {
// initialize craslytics
Fabric.with([Crashlytics.self, Answers.self])
// mandatory to be at the top
Crash.crasher = CrashlyticsCrasher()
DispatchQueue.default = .global()
// create the dependency injection container
container = Container()
super.init()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
#if DEBUG
print("Document path:", FileManager.documentsPath)
#endif
Analytics.shared.logSystemLanguage()
let updater = AppUpdater()
let versionUpdate = updater.updated()
CLog("Version Update:", versionUpdate)
let window = UIWindow(frame: UIScreen.main.bounds)
self.window = window
configureAppAppearance()
window.rootViewController = container.createRootViewController()
window.makeKeyAndVisible()
return true
}
fileprivate func configureAppAppearance() {
window?.tintColor = UIColor.appIdentity()
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().barTintColor = UIColor.appIdentity()
}
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
let downloadManager = container.createDownloadManager()
downloadManager.backgroundSessionCompletionHandler = completionHandler
}
}
|
gpl-3.0
|
aa1a293f59a2716a77e0733222d2b941
| 31.706667 | 149 | 0.700775 | 5.121086 | false | false | false | false |
lulee007/GankMeizi
|
GankMeizi/Utils/LoggerUtil.swift
|
1
|
1824
|
//
// LoggerUtil.swift
// GankMeizi
//
// Created by 卢小辉 on 16/5/19.
// Copyright © 2016年 lulee007. All rights reserved.
//
import Foundation
import CocoaLumberjack
class LoggerUtil {
/**
* 初始化 CocoaLumberjack DDLog <p/>
* 包括 Xcode console 和 File Logger
*/
static func initLogger(){
DDTTYLogger.sharedInstance().logFormatter = LogFormatter()
DDLog.addLogger(DDTTYLogger.sharedInstance()) // TTY = Xcode console
let fileLogger: DDFileLogger = DDFileLogger() // File Logger
fileLogger.rollingFrequency = 60*60*24 // 24 hours
fileLogger.logFileManager.maximumNumberOfLogFiles = 7
DDLog.addLogger(fileLogger)
DDLogDebug("DDLog inited");
}
class LogFormatter : NSObject,DDLogFormatter
{
func formatLogMessage(logMessage: DDLogMessage!) -> String! {
let dateAndTimeFormatter = NSDateFormatter()
dateAndTimeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:SSS"
let dateAndTime = dateAndTimeFormatter.stringFromDate(logMessage.timestamp)
return "[\(dateAndTime) -\(stringForLogLevel(logMessage.flag)) \(logMessage.fileName) \(logMessage.function): \(logMessage.line) ]: \(logMessage.message)"
}
private func stringForLogLevel(logflag:DDLogFlag) -> String {
switch(logflag) {
case DDLogFlag.Error:
return "E"
case DDLogFlag.Warning:
return "W"
case DDLogFlag.Info:
return "I"
case DDLogFlag.Debug:
return "D"
case DDLogFlag.Verbose:
return "V"
default:
break
}
return ""
}
}
}
|
mit
|
bf8847fadf8c45588a3e01563b1e37fa
| 29.576271 | 166 | 0.581253 | 4.732283 | false | false | false | false |
nathawes/swift
|
test/IRGen/prespecialized-metadata/enum-inmodule-2argument-1distinct_use.swift
|
2
|
4252
|
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueOyS2iGWV" = linkonce_odr hidden constant %swift.enum_vwtable {
// CHECK-SAME: i8* bitcast ({{(%swift.opaque\* \(\[[0-9]+ x i8\]\*, \[[0-9]+ x i8\]\*, %swift.type\*\)\* @"\$[a-zA-Z0-9_]+" to i8\*|[^@]+@__swift_memcpy[0-9]+_[0-9]+[^\)]* to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_noop_void_return{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[0-9]+}}_{{[0-9]+}}{{[^)]*}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwet{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwst{{[^)]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwug{{[^)]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwup{{[^)]+}} to i8*),
// CHECK-SAME i8* bitcast ({{[^@]+}}@"$s4main5ValueOyS2iGwui{{[^)]+}} to i8*)
// CHECK-SAME: }, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueOyS2iGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// CHECK-SAME: i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5ValueOyS2iGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: ),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: [[INT]] {{16|8}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
enum Value<First, Second> {
case first(First)
case second(First, Second)
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5ValueOyS2iGMf"
// CHECK-SAME: to %swift.full_type*),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value.second(13, 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE_1]],
// CHECK-SAME: i8* [[ERASED_TYPE_2]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5ValueOMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
|
apache-2.0
|
6bf648ee29601f5644b4df3fe7deb8f9
| 44.234043 | 187 | 0.55127 | 2.851777 | false | false | false | false |
Iiiggs/AsthmaBuddy
|
AsthmaBuddy/Utilities.swift
|
1
|
2825
|
//
// Utilities.swift
// AsthmaBuddy
//
// Created by Igor Kantor on 8/7/17.
// Copyright © 2017 Igorware. All rights reserved.
//
import Foundation
import HealthKit
import UIKit
import MapKit
extension Array {
func group<T>(by criteria: (Element) -> T) -> [T: [Element]] {
var groups = [T: [Element]]()
for element in self {
let key = criteria(element)
if groups.keys.contains(key) == false {
groups[key] = [Element]()
}
groups[key]?.append(element)
}
return groups
}
}
// MARK: - Array<HKQuantitySample> countByDate
extension Array where Iterator.Element == HKQuantitySample {
func sampleValueCountByDate(start:Date, end:Date) -> [Date: Double] {
var currentDate = start
var result = [Date : Double] ()
while(currentDate <= end){
let tomorrow = NSCalendar.current.date(byAdding: .day, value: 1, to: currentDate)!
let tadays_samples = self.filter {
$0.startDate > currentDate && $0.startDate < tomorrow
}
let sum = tadays_samples.reduce(0.0, { (r, sample) -> Double in
let sum : Double = r
let value : Double = sample.quantity.doubleValue(for:HKUnit.count())
return value + sum
})
result[currentDate] = sum
currentDate = tomorrow
}
return result
}
func sampleLocations(start:Date, end:Date) -> [HKQuantitySample] {
return self.filter { (s) -> Bool in s.startDate > start && s.endDate < end && s.metadata?[usageLocationKey] != nil}
}
}
// MARK: - HKQantitySample implements MKAnnotation
extension HKQuantitySample : MKAnnotation {
public var title: String? {
return "\(self.quantityType)"
}
public var coordinate: CLLocationCoordinate2D {
if let location = self.metadata?[usageLocationKey] as? String{
let coordinate = location.components(separatedBy: ",")
return CLLocationCoordinate2D(latitude: Double(coordinate[0])!, longitude: Double(coordinate[1])!)
} else {
return CLLocationCoordinate2D(latitude: 39.570154341901485, longitude: -105.30286789781341)
}
}
// pinTintColor for disciplines: Sculpture, Plaque, Mural, Monument, other
func pinTintColor() -> UIColor {
return UIColor.brown
}
// annotation callout opens this mapItem in Maps app
func mapItem() -> MKMapItem {
let placemark = MKPlacemark(coordinate: coordinate)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = title
return mapItem
}
}
|
mit
|
0ae36014d0aa066722b7f17ac9cd3c7c
| 29.042553 | 123 | 0.577904 | 4.532905 | false | false | false | false |
jakehawken/Concurrency
|
Source/Result+Concurrency.swift
|
1
|
5750
|
// Result.swift
// Concurrency
// Created by Jacob Hawken on 10/7/17.
// Copyright © 2017 CocoaPods. All rights reserved.
import Foundation
//swiftlint:disable line_length
public extension Result {
typealias SuccessBlock = (Success) -> Void
typealias ErrorBlock = (Failure) -> Void
/**
Convenience block for adding functional-style chaining to `Result`.
- Parameter successBlock: The block to be executed on success. Block takes a single argument, which is of the `Success` type of the result. Executes if success case. Does not execute if failure case.
- returns: The future iself, as a `@discardableResult` to allow for chaining.
*/
@discardableResult func onSuccess(_ successBlock: SuccessBlock) -> Result<Success, Failure> {
switch self {
case .success(let value):
successBlock(value)
default:
break
}
return self
}
/**
Convenience block for adding functional-style chaining to `Result`.
- Parameter errorBlock: The block to be executed on failure. Block takes a single argument, which is of the `Error` type of the result. Executes if failure case. Does not execute if success case.
- returns: The future iself, as a `@discardableResult` to allow for chaining.
*/
@discardableResult func onError(_ errorBlock: ErrorBlock) -> Result<Success, Failure> {
switch self {
case .failure(let error):
errorBlock(error)
default:
break
}
return self
}
/**
Maps from one the given result to a new one. The generated result has an informative error type which clearly delineates if the error was in the original result or as a result of mapping. The type of the error is `MapError<T,E,Q>` where Q is the desired mapped value. If the first result is a failure, the error for the mapped result will be `.originalError` with the original error as an associated value. If the the first result is a success but the map block returns `nil`, then the error for the mapped result will be `.mappingError` with the unmappable value as the associated value (e.g. If passing `5` into the mapBlock causes the block to return nil, the error for the new result will be `.mappingError(5)`).
- Parameter mapBlock: The mapping block, which is executed if the first result is a success. The block takes a single argument, which is of the success type `Success` of the original future, and returns an optional: `TargetType?`. TargetType is the desired mapped value.
- returns: A new result where Success type is `TargetType` and the error type is `MapError<Success, Failure, TargetType>`
*/
func flatMap<TargetType>(_ mapBlock: (Success) -> (TargetType?)) -> Result<TargetType, MapError<Success, Failure, TargetType>> {
switch self {
case .success(let value):
if let transformedValue = mapBlock(value) {
return .success(transformedValue)
}
else {
return .failure(.mappingError(value))
}
case .failure(let previousError):
return .failure(.originalError(previousError))
}
}
/// Convenience property for converting the state of result into an optional `Failure`. Returns nil in success case.
var failure: Failure? {
switch self {
case .success:
return nil
case .failure(let value):
return value
}
}
/// Convenience property for converting the state of result into an optional `Success`. Returns nil in failure case.
var success: Success? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
}
/**
MapError is an Error type for encapsulating the mapping of one Success/Error pairing to another. Initially built for Result, but could just as well be used for Future or any other type which involves a Success/Error pair.
The intended use is for capturing both the possible failure state of the original result as well as the possible failed mapping of a success value.
For example, let's say we have a result of type `Result<Int, NSError>`, and wanted to map it to a result of with a Success type of `Bool`. If our first result was `.success(5)` that's not a value that can be mapped to Bool. If failure to map and failure to get the integer had different relevance, this wouuld be a good use case for a `MapError<Int, NSError, Bool>`, on which the `.success(5)` on the first result would map to the MapError state of `.mappingError(5)`
For the original example, look at the usage on `Result.map<TargetType>(_:)`
*/
public enum MapError<SourceType, SourceError, TargetType>: Error, CustomStringConvertible {
case originalError(SourceError)
case mappingError(SourceType)
public var description: String {
switch self {
case .originalError(let error):
return "OriginalError: \(error)"
case .mappingError(let itemToMap):
let typeString = String(describing: TargetType.self)
return "Could not map value: (\(itemToMap)) to output type: \(typeString)."
}
}
}
extension MapError: Equatable where SourceType: Equatable, SourceError: Equatable {
public static func == (lhs: MapError, rhs: MapError) -> Bool {
switch (lhs, rhs) {
case (.originalError(let error1), .originalError(let error2)):
return error1 == error2
case (.mappingError(let value1), .mappingError(let value2)):
return value1 == value2
default:
return false
}
}
}
|
mit
|
535c0039d3fae01dee352f823f18ef6c
| 44.992 | 720 | 0.666899 | 4.693061 | false | false | false | false |
blinksh/blink
|
SSH/Agent.swift
|
1
|
10963
|
//////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2021 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink 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.
//
// Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Combine
import Foundation
import LibSSH
import OpenSSH
public enum SSHAgentRequestType: UInt8 {
case requestIdentities = 11
case requestSignature = 13
}
public enum SSHAgentResponseType: UInt8 {
case failure = 5
case success = 6
case answerIdentities = 12
case responseSignature = 14
}
fileprivate let errorData = Data(bytes: [0x05], count: MemoryLayout<CChar>.size)
public class SSHAgentKey {
let constraints: [SSHAgentConstraint]?
// var expiration: Int
public let signer: Signer
public let name: String
init(_ key: Signer, named: String, constraints: [SSHAgentConstraint]? = nil) {
self.signer = key
self.name = named
self.constraints = constraints
}
}
public class SSHAgent {
public private(set) var ring: [SSHAgentKey] = []
// NOTE Instead of the Agent tracking the constraints, we could have a delegate for that.
// NOTE The Agent name won't be relevant when doing Jumps between hosts, but at least you will know the first originator.
var superAgent: SSHAgent? = nil
var agentForward: Set<AnyCancellable> = []
public init() {}
private var contexts: [AgentCtxt] = []
private class AgentCtxt {
weak var agent: SSHAgent?
weak var client: SSHClient?
init(agent: SSHAgent, client: SSHClient) {
self.agent = agent
self.client = client
}
}
public func linkTo(agent: SSHAgent) {
self.superAgent = agent
}
public func attachTo(client: SSHClient) {
let agentCtxt = AgentCtxt(agent: self, client: client)
contexts.append(agentCtxt)
let ctxt = UnsafeMutableRawPointer(Unmanaged.passUnretained(agentCtxt).toOpaque())
let cb: ssh_agent_callback = { (req, len, reply, userdata) in
// Transform to Swift types and call the request.
let ctxt = Unmanaged<AgentCtxt>.fromOpaque(userdata!).takeUnretainedValue()
var payload = Data(bytesNoCopy: req!, count: Int(len), deallocator: .none)
let typeValue = SSHDecode.uint8(&payload)
var replyData: Data
let replyLength: Int
// Fix types. Cannot be nil as the callback is called by the client
guard let client = ctxt.client else {
return 0
}
if let type = SSHAgentRequestType(rawValue: typeValue) {
replyData = (try? ctxt.agent?.request(payload, context: type, client: client)) ?? errorData
replyLength = replyData.count
} else {
// Return error if type is unknown
replyData = errorData
replyLength = errorData.count
}
_ = replyData.withUnsafeMutableBytes { ptr in
ssh_buffer_add_data(reply, ptr.baseAddress!, UInt32(replyLength))
}
return Int32(replyData.count)
}
ssh_set_agent_callback(client.session, cb, ctxt)
}
public func loadKey(_ key: Signer, aka name: String, constraints: [SSHAgentConstraint]? = nil) -> Bool {
let cKey = SSHAgentKey(key, named: name, constraints: constraints)
// TODO: check constraints
for k in ring {
if cKey.name == k.name {
return false
}
}
ring.append(cKey)
return true
}
public func removeKey(_ name: String) -> Signer? {
if let idx = ring.firstIndex(where: { $0.name == name }) {
let key = ring.remove(at: idx)
return key.signer
} else {
return nil
}
}
func request(_ message: Data, context: SSHAgentRequestType, client: SSHClient) throws -> Data {
switch context {
case .requestIdentities:
let ring = try encodedRing()
var keys: UInt32 = UInt32(ring.count).bigEndian
var respType = SSHAgentResponseType.answerIdentities.rawValue
let preamble = Data(bytes: &respType, count: MemoryLayout<CChar>.size) +
Data(bytes: &keys, count: MemoryLayout<UInt32>.size)
return ring.reduce(preamble) { $0 + $1 }
case .requestSignature:
let signature = try encodedSignature(message, for: client)
var respType = SSHAgentResponseType.responseSignature.rawValue
return Data(bytes: &respType, count: MemoryLayout<CChar>.size)
+ signature
// default:
// throw SSHKeyError.general(title: "Invalid request received")
}
}
func encodedRing() throws -> [Data] {
(try ring.map { (try $0.signer.publicKey.encode()) + SSHEncode.data(from: $0.signer.comment ?? "") }) +
(try superAgent?.encodedRing() ?? [])
}
func encodedSignature(_ message: Data, for client: SSHClient) throws -> Data {
var msg = message
let keyBlob = SSHDecode.bytes(&msg)
let data = SSHDecode.bytes(&msg)
let flags = SSHDecode.uint32(&msg)
do {
guard let key = lookupKey(blob: keyBlob) else {
throw SSHKeyError.general(title: "Could not find proposed key")
}
let algorithm: String? = SigDecodingAlgorithm(rawValue: Int8(flags)).algorithm(for: key.signer)
// Enforce constraints
try key.constraints?.forEach {
if !$0.enforce(useOf: key, by: client) { throw SSHKeyError.general(title: "Denied operation by constraint: \($0.name).") }
}
let signature = try key.signer.sign(data, algorithm: algorithm)
return SSHEncode.data(from: signature)
} catch {
guard let superAgent = self.superAgent else {
throw error
}
return try superAgent.encodedSignature(message, for: client)
}
}
fileprivate func lookupKey(blob: Data) -> SSHAgentKey? {
// Get rid of the blob size from encode before comparing.
ring.first { (try? $0.signer.publicKey.encode()[4...]) == blob }
}
}
extension SSHAgent {
func forward(to stream: Stream) {
// Read, process and write
// Reads up to max - it may read less if the channel closes before.
stream.read(max: 4)
.flatMap { data -> AnyPublisher<DispatchData, Error> in
var payloadSizeData = data as AnyObject as! Data
if data.count < 4 {
return .fail(error: SSHError(title: "Agent Channel closed before read could complete"))
}
let payloadSize = Int(SSHDecode.uint32(&payloadSizeData))
return stream.read(max: payloadSize)
}
.flatMap { data -> AnyPublisher<Int, Error> in
var payload = data as AnyObject as! Data
if data.count < 1 {
return .fail(error: SSHError(title: "Agent Channel closed before read could complete"))
}
let typeValue = SSHDecode.uint8(&payload)
var replyData: Data
if let type = SSHAgentRequestType(rawValue: typeValue) {
replyData = (try? self.request(payload, context: type, client: stream.client)) ?? errorData
} else {
replyData = errorData
}
let reply = SSHEncode.data(from: UInt32(replyData.count)) + replyData
let dd = reply.withUnsafeBytes { DispatchData(bytes: $0) }
return stream.write(dd, max: dd.count)
}.sink(
receiveCompletion: { c in
// Completion. Log errors and escape
if ssh_channel_is_eof(stream.channel) == 0 {
self.forward(to: stream)
} else {
self.agentForward = []
}
}, receiveValue: { _ in }).store(in: &agentForward)
}
}
fileprivate struct SigDecodingAlgorithm: OptionSet {
public let rawValue: Int8
public init(rawValue: Int8) {
self.rawValue = rawValue
}
public static let RsaSha2256 = SigDecodingAlgorithm(rawValue: 1 << 1)
public static let RsaSha2512 = SigDecodingAlgorithm(rawValue: 1 << 2)
func algorithm(for key: Signer) -> String? {
let type = key.sshKeyType
if type == .rsa {
if self.contains(.RsaSha2256) {
return "rsa-sha2-256"
} else if self.contains(.RsaSha2512) {
return "rsa-sha2-512"
}
} else if type == .rsaCert {
if self.contains(.RsaSha2256) {
return "[email protected]"
} else if self.contains(.RsaSha2512) {
return "[email protected]"
}
}
return nil
}
}
public enum SSHEncode {
public static func data(from str: String) -> Data {
self.data(from: UInt32(str.count)) + (str.data(using: .utf8) ?? Data())
}
public static func data(from int: UInt32) -> Data {
var val: UInt32 = UInt32(int).bigEndian
return Data(bytes: &val, count: MemoryLayout<UInt32>.size)
}
public static func data(from bytes: Data) -> Data {
self.data(from: UInt32(bytes.count)) + bytes
}
}
public enum SSHDecode {
static func string(_ bytes: inout Data) -> String? {
let length = SSHDecode.uint32(&bytes)
guard let str = String(data: bytes[0..<length], encoding: .utf8) else {
return nil
}
bytes = bytes.advanced(by: Int(length))
return str
}
static func bytes(_ bytes: inout Data) -> Data {
let length = SSHDecode.uint32(&bytes)
let d = bytes.subdata(in: 0..<Int(length))
bytes = bytes.advanced(by: Int(length))
return d
}
static func uint8(_ bytes: inout Data) -> UInt8 {
let length = MemoryLayout<UInt8>.size
let d = bytes.subdata(in: 0..<length)
let value = UInt8(bigEndian: d.withUnsafeBytes { ptr in
ptr.load(as: UInt8.self)
})
if bytes.count == Int(length) {
bytes = Data()
} else {
bytes = bytes.advanced(by: Int(length))
}
return value
}
static func uint32(_ bytes: inout Data) -> UInt32 {
let length = MemoryLayout<UInt32>.size
let d = bytes.subdata(in: 0..<Int(length))
let value = UInt32(bigEndian: d.withUnsafeBytes { ptr in
ptr.load(as: UInt32.self)
})
if bytes.count == Int(length) {
bytes = Data()
} else {
bytes = bytes.advanced(by: Int(length))
}
return value
}
}
|
gpl-3.0
|
92986bac23207002b21539f979b102a2
| 31.055556 | 130 | 0.636322 | 3.990899 | false | false | false | false |
myfreeweb/freepass
|
ios/Freepass/Freepass/FieldCells.swift
|
1
|
6039
|
import UIKit
import RxSwift
import RxCocoa
import Cartography
class ShowFieldCell: UITableViewCell {
var dbag = DisposeBag()
lazy var name = UITextField()
lazy var content = UITextField()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(name)
addSubview(content)
}
required init?(coder aDecoder: NSCoder) { // REALLY?
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
name.enabled = false
name.textColor = Colors.primaryAccent
name.font = name.font?.fontWithSize(16)
content.enabled = false
content.textColor = Colors.primaryContent
}
func setField(field: FieldViewModel) {
field.field_name.asObservable().bindTo(name.rx_text).addDisposableTo(dbag)
updateConstraints()
}
override func updateConstraints() {
constrain(name, content) { name, content in
for v in [name, content] {
v.centerX == name.superview!.centerX
v.width == name.superview!.width - 20
// v.height == 24
}
name.top == name.superview!.topMargin
content.bottom == name.superview!.bottomMargin
distribute(by: 4, vertically: name, content)
}
super.updateConstraints()
}
}
class ShowPasswordFieldCell: ShowFieldCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) { // WHAT
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
content.secureTextEntry = true
content.text = "************"
}
}
class EditFieldCell: UITableViewCell {
var dbag = DisposeBag()
weak var field: FieldViewModel?
lazy var name_field = UITextField()
lazy var type_selector = UISegmentedControl(items: ["Derived", "Stored"])
lazy var derived_site_name_field = UITextField()
lazy var derived_counter_label = UILabel()
lazy var derived_counter_stepper = UIStepper()
lazy var stored_string_field = UITextField()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(name_field)
addSubview(type_selector)
addSubview(derived_site_name_field)
addSubview(derived_counter_stepper)
addSubview(derived_counter_label)
addSubview(stored_string_field)
}
override func layoutSubviews() {
super.layoutSubviews()
name_field.textColor = Colors.primaryContent
derived_site_name_field.placeholder = "Site name (leave blank to use the entry name)"
derived_site_name_field.textColor = Colors.primaryContent
derived_counter_stepper.maximumValue = Double(UInt32.max)
derived_counter_label.textColor = Colors.primaryContent
stored_string_field.textColor = Colors.primaryContent
updateConstraints()
}
func setField(field: FieldViewModel) {
self.field = field
(name_field.rx_text <-> field.field_name).addDisposableTo(dbag)
transformBind(type_selector.rx_value,
variable: field.field_type,
propToVar: { $0 == 0 ? .Some(.Derived) : .Some(.Stored) },
varToProp: { $0 == .Some(.Derived) ? 0 : 1 }).addDisposableTo(dbag)
field.field_type.asObservable().map { $0 == .Some(.Derived) }.distinctUntilChanged().subscribeNext {
self.derived_site_name_field.hidden = !$0
self.derived_counter_stepper.hidden = !$0
self.derived_counter_label.hidden = !$0
self.stored_string_field.hidden = $0
// I've spent so much time figuring this shit out:
self.tableView?.beginUpdates()
self.updateConstraints()
self.tableView?.endUpdates()
}.addDisposableTo(dbag)
(derived_site_name_field.rx_text <-> field.derived_site_name).addDisposableTo(dbag)
field.derived_counter.asObservable().subscribeNext { self.derived_counter_stepper.value = Double($0 ?? 1) }.addDisposableTo(dbag)
derived_counter_stepper.rx_value.map { UInt32($0) }.bindTo(field.derived_counter).addDisposableTo(dbag)
field.derived_counter.asObservable().map { "Counter: \($0 ?? 1)" }
.bindTo(derived_counter_label.rx_text).addDisposableTo(dbag)
(stored_string_field.rx_text <-> field.stored_data_string).addDisposableTo(dbag)
field.stored_usage.asObservable().subscribeNext {
switch $0 ?? .Text {
case .Password: self.stored_string_field.placeholder = "Password"
case .Text: self.stored_string_field.placeholder = "Text"
}
}.addDisposableTo(dbag)
updateConstraints()
}
let group = ConstraintGroup()
override func updateConstraints() {
constrain([name_field, type_selector, derived_site_name_field, derived_counter_label, derived_counter_stepper, stored_string_field], replace: group) {
let name_field = $0[0], type_selector = $0[1], derived_site_name_field = $0[2], derived_counter_label = $0[3], derived_counter_stepper = $0[4], stored_string_field = $0[5] // FUCK
guard let superview = name_field.superview else { return }
let isDerived = self.field?.field_type.value == .Some(.Derived)
for v in [name_field, type_selector, derived_site_name_field, stored_string_field] {
v.left == superview.left + 50
v.right == superview.right - 10
v.height == 24
}
name_field.top == superview.topMargin
if isDerived {
derived_counter_stepper.bottom == superview.bottomMargin
derived_counter_label.left == superview.left + 50
derived_counter_label.right == derived_counter_stepper.left - 10
derived_counter_label.top == derived_counter_stepper.top
derived_counter_label.bottom == derived_counter_stepper.bottom
derived_counter_stepper.right == superview.right - 10
distribute(by: 10, vertically: name_field, type_selector, derived_site_name_field, derived_counter_stepper)
} else {
stored_string_field.bottom == superview.bottomMargin
distribute(by: 10, vertically: name_field, type_selector, stored_string_field)
}
}
super.updateConstraints()
}
required init?(coder aDecoder: NSCoder) { // SERIOUSLY?
fatalError("init(coder:) has not been implemented")
}
}
|
unlicense
|
0aebba0a978e15db5482fafd92266d0b
| 33.706897 | 183 | 0.726279 | 3.562832 | false | false | false | false |
fiveagency/ios-five-ui-components
|
FiveUIComponents/Classes/Extensions/UIColor+Interpolating.swift
|
1
|
1155
|
//
// UIColor+Interpolating.swift
// FiveUIComponents
//
// Created by Ivan Vranjic on 24/02/17.
// Copyright © 2017 Five Agency. All rights reserved.
//
import UIKit
fileprivate func normalizedComponents(for color: UIColor) -> (CGFloat, CGFloat, CGFloat, CGFloat)? {
guard let components = color.cgColor.components else { return nil }
if color.cgColor.numberOfComponents == 2 {
return (components[0], components[0], components[0], components[1])
}
return (components[0], components[1], components[2], components[3])
}
extension UIColor {
func colorByInterpolatingColor(_ color: UIColor, by factor: CGFloat) -> UIColor? {
guard let start = normalizedComponents(for: self),
let end = normalizedComponents(for: color) else {
return nil
}
let newRed = start.0 + (end.0 - start.0) * factor
let newGreen = start.1 + (end.1 - start.1) * factor
let newBlue = start.2 + (end.2 - start.2) * factor
let newAlpha = (start.3 + end.3)/2
let color = UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: newAlpha)
return color
}
}
|
mit
|
98eb7b5ca15f8a19d61f0201b8421991
| 35.0625 | 100 | 0.641248 | 3.746753 | false | false | false | false |
FindGF/_BiliBili
|
WTBilibili/Other-其他/WTBaseViewController.swift
|
1
|
1717
|
//
// WTBaseViewController.swift
// WTBilibili
//
// Created by 无头骑士 GJ on 16/7/5.
// Copyright © 2016年 无头骑士 GJ. All rights reserved.
//
import UIKit
let BaseHeaderViewH: CGFloat = 54
class WTBaseViewController: UIViewController {
var headerView = UIView()
var footerView = UIView()
var headerViewH: CGFloat = 0
/// 标题Label
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
self.headerView.addSubview(titleLabel)
titleLabel.sizeToFit()
titleLabel.snp_makeConstraints(closure: { (make) in
make.centerX.equalTo(self.headerView)
make.top.equalTo(20)
make.height.equalTo(34)
})
titleLabel.textColor = UIColor.whiteColor()
return titleLabel
}()
// MARK: - 系统回调函数
override func viewDidLoad()
{
super.viewDidLoad()
// 设置View
setupView()
}
}
// MARK: - 自定义函数
extension WTBaseViewController
{
// MARK: 设置View
private func setupView()
{
view.backgroundColor = WTMainColor
// 1、添加子控件
view.addSubview(headerView)
view.addSubview(footerView)
// 2、布局子控件
headerView.backgroundColor = UIColor.clearColor()
headerView.frame = CGRect(x: 0, y: 0, width: WTScreenWidth, height: BaseHeaderViewH)
// 3、子控件属性
headerView.backgroundColor = WTMainColor
footerView.clipsToBounds = true
footerView.layer.cornerRadius = 5
footerView.backgroundColor = UIColor.whiteColor()
}
}
|
apache-2.0
|
76e960b6d2b6b315d314d498eb895f0f
| 21.30137 | 92 | 0.591523 | 4.732558 | false | false | false | false |
sealgair/MusicKit
|
MusicKit/Chroma.swift
|
1
|
3947
|
// Copyright (c) 2015 Ben Guo. All rights reserved.
import Foundation
typealias ChromaNameTuple = (LetterName, Accidental)
/// Pitch quality; also known as pitch class.
public enum Chroma: UInt {
/// C
case C = 0
/// C Sharp
case Cs = 1
/// D
case D = 2
/// D Sharp
case Ds = 3
/// E
case E = 4
/// F
case F = 5
/// F Sharp
case Fs = 6
/// G
case G = 7
/// G Sharp
case Gs = 8
/// A
case A = 9
/// A Sharp
case As = 10
/// B
case B = 11
var names: [ChromaNameTuple] {
switch self.rawValue {
case 0:
return [(.C, .Natural), (.B, .Sharp), (.D, .DoubleFlat)]
case 1:
return [(.C, .Sharp), (.D, .Flat), (.B, .DoubleSharp)]
case 2:
return [(.D, .Natural), (.C, .DoubleSharp), (.E, .DoubleFlat)]
case 3:
return [(.E, .Flat), (.D, .Sharp), (.F, .DoubleFlat)]
case 4:
return [(.E, .Natural), (.F, .Flat), (.D, .DoubleSharp)]
case 5:
return [(.F, .Natural), (.E, .Sharp), (.G, .DoubleFlat)]
case 6:
return [(.F, .Sharp), (.G, .Flat), (.E, .DoubleSharp)]
case 7:
return [(.G, .Natural), (.F, .DoubleSharp), (.A, .DoubleFlat)]
case 8:
return [(.A, .Flat), (.G, .Sharp)]
case 9:
return [(.A, .Natural), (.G, .DoubleSharp), (.B, .DoubleFlat)]
case 10:
return [(.B, .Flat), (.A, .Sharp), (.C, .DoubleFlat)]
case 11:
return [(.B, .Natural), (.C, .Flat), (.A, .DoubleSharp)]
default:
return []
}
}
/// Returns true if the given name tuple is a valid name
func validateName(name: ChromaNameTuple) -> Bool {
return self.names.reduce(false, combine: { (a, r) -> Bool in
a || (r == name)
})
}
}
// MARK: Printable
extension Chroma: CustomStringConvertible {
public var description: String {
let nameTupleOpt: ChromaNameTuple? = self.names.first
if let (letterName, accidental) = nameTupleOpt {
return describe(letterName, accidental: accidental)
}
return ""
}
public var flatDescription : String {
for (letterName, accidental) in self.names {
if accidental == .Natural || accidental == .Flat {
return describe(letterName, accidental: accidental)
}
}
return ""
}
public var sharpDescription : String {
for (letterName, accidental) in self.names {
if accidental == .Natural || accidental == .Sharp {
return describe(letterName, accidental: accidental)
}
}
return ""
}
func describe(letterName: LetterName, accidental: Accidental) -> String {
return "\(letterName.description)\(accidental.description(true))"
}
}
// MARK: Operators
public func == (p1:(LetterName, Accidental), p2:(LetterName, Accidental)) -> Bool
{
return (p1.0 == p2.0) && (p1.1 == p2.1)
}
public func +(lhs: Chroma, rhs: Int) -> Chroma {
var rhs = rhs
while rhs < 0 {
rhs = rhs + 12
}
let newRawValue = (lhs.rawValue + UInt(rhs))%12
return Chroma(rawValue: newRawValue)!
}
public func -(lhs: Chroma, rhs: Int) -> Chroma {
return lhs + (-1*rhs)
}
postfix func --(inout chroma: Chroma) -> Chroma {
chroma = chroma - 1
return chroma
}
postfix func ++(inout chroma: Chroma) -> Chroma {
chroma = chroma + 1
return chroma
}
/// Returns the minimum distance between two chromas
public func -(lhs: Chroma, rhs: Chroma) -> UInt {
let lminusr = abs(Int(lhs.rawValue) - Int(rhs.rawValue))
let rminusl = abs(Int(rhs.rawValue) - Int(lhs.rawValue))
return UInt(min(lminusr, rminusl))
}
public func *(lhs: Chroma, rhs: Int) -> Pitch {
return Pitch(chroma: lhs, octave: UInt(abs(rhs)))
}
|
mit
|
dea2f7336920ff1df22b2b8bc3ad85e6
| 26.409722 | 81 | 0.53509 | 3.658017 | false | false | false | false |
vector-im/riot-ios
|
Riot/Modules/KeyVerification/User/Start/UserVerificationStartViewController.swift
|
2
|
9323
|
// File created from ScreenTemplate
// $ createScreen.sh Start UserVerificationStart
/*
Copyright 2020 New Vector Ltd
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
final class UserVerificationStartViewController: UIViewController {
// MARK: - Constants
private enum Constants {
static let verifyButtonCornerRadius: CGFloat = 8.0
static let informationTextDefaultFont = UIFont.systemFont(ofSize: 15.0)
static let informationTextBoldFont = UIFont.systemFont(ofSize: 15.0, weight: .medium)
}
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var informationLabel: UILabel!
@IBOutlet private weak var startVerificationButton: UIButton!
@IBOutlet private weak var verificationWaitingLabel: UILabel!
@IBOutlet private weak var additionalInformationLabel: UILabel!
// MARK: Private
private var viewModel: UserVerificationStartViewModelType!
private var theme: Theme!
private var errorPresenter: MXKErrorPresentation!
private var activityPresenter: ActivityIndicatorPresenter!
// MARK: - Setup
class func instantiate(with viewModel: UserVerificationStartViewModelType) -> UserVerificationStartViewController {
let viewController = StoryboardScene.UserVerificationStartViewController.initialScene.instantiate()
viewController.viewModel = viewModel
viewController.theme = ThemeService.shared().theme
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = VectorL10n.keyVerificationUserTitle
self.setupViews()
self.activityPresenter = ActivityIndicatorPresenter()
self.errorPresenter = MXKErrorAlertPresentation()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
self.viewModel.viewDelegate = self
self.viewModel.process(viewAction: .loadData)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.startVerificationButton.layer.cornerRadius = Constants.verifyButtonCornerRadius
}
// MARK: - Private
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.headerBackgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
self.informationLabel.textColor = theme.textPrimaryColor
self.startVerificationButton.vc_setBackgroundColor(theme.tintColor, for: .normal)
self.verificationWaitingLabel.textColor = theme.textSecondaryColor
self.additionalInformationLabel.textColor = theme.textSecondaryColor
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
private func setupViews() {
let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in
self?.cancelButtonAction()
}
self.navigationItem.rightBarButtonItem = cancelBarButtonItem
self.startVerificationButton.layer.masksToBounds = true
self.startVerificationButton.setTitle(VectorL10n.userVerificationStartVerifyAction, for: .normal)
self.additionalInformationLabel.text = VectorL10n.userVerificationStartAdditionalInformation
}
private func render(viewState: UserVerificationStartViewState) {
switch viewState {
case .loading:
self.renderLoading()
case .loaded(let viewData):
self.renderLoaded(viewData: viewData)
case .error(let error):
self.render(error: error)
case .verificationPending:
self.renderVerificationPending()
case .cancelled(let reason):
self.renderCancelled(reason: reason)
case .cancelledByMe(let reason):
self.renderCancelledByMe(reason: reason)
}
}
private func renderLoading() {
self.activityPresenter.presentActivityIndicator(on: self.view, animated: true)
}
private func renderLoaded(viewData: UserVerificationStartViewData) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.informationLabel.attributedText = self.buildInformationAttributedText(with: viewData.userId)
self.verificationWaitingLabel.text = self.buildVerificationWaitingText(with: viewData)
}
private func render(error: Error) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil)
}
private func renderVerificationPending() {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.startVerificationButton.isHidden = true
self.verificationWaitingLabel.isHidden = false
}
private func renderCancelled(reason: MXTransactionCancelCode) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.errorPresenter.presentError(from: self, title: "", message: VectorL10n.deviceVerificationCancelled, animated: true) {
self.viewModel.process(viewAction: .cancel)
}
}
private func renderCancelledByMe(reason: MXTransactionCancelCode) {
if reason.value != MXTransactionCancelCode.user().value {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.errorPresenter.presentError(from: self, title: "", message: VectorL10n.deviceVerificationCancelledByMe(reason.humanReadable), animated: true) {
self.viewModel.process(viewAction: .cancel)
}
} else {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
}
}
private func buildInformationAttributedText(with userId: String) -> NSAttributedString {
let informationAttributedText: NSMutableAttributedString = NSMutableAttributedString()
let informationTextDefaultAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: self.theme.textPrimaryColor,
.font: Constants.informationTextDefaultFont]
let informationTextBoldAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: self.theme.textPrimaryColor,
.font: Constants.informationTextBoldFont]
let informationAttributedStringPart1 = NSAttributedString(string: VectorL10n.userVerificationStartInformationPart1, attributes: informationTextDefaultAttributes)
let informationAttributedStringPart2 = NSAttributedString(string: userId, attributes: informationTextBoldAttributes)
let informationAttributedStringPart3 = NSAttributedString(string: VectorL10n.userVerificationStartInformationPart2, attributes: informationTextDefaultAttributes)
informationAttributedText.append(informationAttributedStringPart1)
informationAttributedText.append(informationAttributedStringPart2)
informationAttributedText.append(informationAttributedStringPart3)
return informationAttributedText
}
private func buildVerificationWaitingText(with viewData: UserVerificationStartViewData) -> String {
let userName = viewData.userDisplayName ?? viewData.userId
return VectorL10n.userVerificationStartWaitingPartner(userName)
}
// MARK: - Actions
@IBAction private func startVerificationButtonAction(_ sender: Any) {
self.viewModel.process(viewAction: .startVerification)
}
private func cancelButtonAction() {
self.viewModel.process(viewAction: .cancel)
}
}
// MARK: - UserVerificationStartViewModelViewDelegate
extension UserVerificationStartViewController: UserVerificationStartViewModelViewDelegate {
func userVerificationStartViewModel(_ viewModel: UserVerificationStartViewModelType, didUpdateViewState viewSate: UserVerificationStartViewState) {
self.render(viewState: viewSate)
}
}
|
apache-2.0
|
b5a464a18d53802cc46510aeb15c136a
| 39.534783 | 169 | 0.706425 | 5.960997 | false | false | false | false |
Jnosh/swift
|
test/Constraints/diagnostics.swift
|
2
|
44735
|
// RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i,
i) // expected-error{{extra argument in call}}
// Position mismatch
f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x }
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}}
return (c: 0, i: g())
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}}
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {}
f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup' (aka '(Int, Double) -> (Int, Double)'), 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>(
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
// FIXME: poor diagnostic, to be fixed in 20142462. For now, we just want to
// make sure that it doesn't crash.
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{ambiguous reference to member '..<'}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'String.CharacterView.IndexDistance'}}{{24-26=}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}}
// expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{'Int' is not convertible to 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to nil always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {}
_ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Protocol' is not convertible to 'AnyObject'}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call is unused, but produces 'Int'}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing argument for parameter #1 in call}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self) // expected-error {{missing argument for parameter 'b' in call}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {}
static func overload(b : Int) -> Color {}
static func frob(_ a : Int, b : inout Int) -> Color {}
}
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}}
let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{binary operator '+' cannot be applied to operands of type 'Double' and 'Int'}}
//expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
func test(_ a : B) {
B.f1(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) //expected-error {{nil is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) //expected-error {{missing argument label 'a:' in call}}
a.f2(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions; operands here have types '_' and '([Int]) -> Bool'}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to nil always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}}
// expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error {{value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=?}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=?}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{type 'UnsafeMutableRawPointer' has no subscript members}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'CountableClosedRange<Int>' to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')}}
_ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
_ = a + b // expected-warning {{deprecated}}
a += a + // expected-error {{binary operator '+=' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+=' exist}}
b
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
postfix operator +++
postfix func +++ <T>(_: inout T) -> T { fatalError() }
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
_ = bytes[i+++] // expected-error {{cannot pass immutable value as inout argument: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}}
// FIXME(integers): uncomment these tests once the < is no longer ambiguous
// _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : BinaryInteger>() -> T? {
var buffer : T
let n = withUnsafePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtractInPlace(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}}
// expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found this candidate}}
func value(y: String) -> String {} // expected-note {{found this candidate}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}}
r27212391(y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(1, x: 3, y: 5) // expected-error {{missing argument label 'a' in call}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// SR-2505: "Call arguments did not match up" assertion
// Here we're simulating the busted Swift 3 behavior -- see
// test/Constraints/diagnostics_swift4.swift for the correct
// behavior.
func sr_2505(_ a: Any) {} // expected-note {{}}
sr_2505() // expected-error {{missing argument for parameter #1 in call}}
sr_2505(a: 1) // FIXME: emit a warning saying this becomes an error in Swift 4
sr_2505(1, 2) // expected-error {{extra argument in call}}
sr_2505(a: 1, 2) // expected-error {{extra argument in call}}
struct C_2505 {
init(_ arg: Any) {
}
}
protocol P_2505 {
}
extension C_2505 {
init<T>(from: [T]) where T: P_2505 {
}
}
class C2_2505: P_2505 {
}
// FIXME: emit a warning saying this becomes an error in Swift 4
let c_2505 = C_2505(arg: [C2_2505()])
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
// <rdar://problem/29850459> Swift compiler misreports type error in ternary expression
let r29850459_flag = true
let r29850459_a: Int = 0
let r29850459_b: Int = 1
func r29850459() -> Bool { return false }
let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
// Ambiguous overload inside a trailing closure
func ambiguousCall() -> Int {} // expected-note {{found this candidate}}
func ambiguousCall() -> Float {} // expected-note {{found this candidate}}
func takesClosure(fn: () -> ()) {}
takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}}
// SR-4692: Useless diagnostics calling non-static method
class SR_4692_a {
private static func foo(x: Int, y: Bool) {
self.bar(x: x)
// expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}}
}
private func bar(x: Int) {
}
}
class SR_4692_b {
static func a() {
self.f(x: 3, y: true)
// expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}}
}
private func f(a: Int, b: Bool, c: String) {
self.f(x: a, y: b)
}
private func f(x: Int, y: Bool) {
}
}
// rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful
struct R32101765 { let prop32101765 = 0 }
let _: KeyPath<R32101765, Float> = \.prop32101765
// expected-error@-1 {{KeyPath value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765
// expected-error@-1 {{KeyPath value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
|
apache-2.0
|
a420e0010ceeca31cbdcf066a8599ace
| 44.64898 | 210 | 0.672427 | 3.615534 | false | false | false | false |
weirdindiankid/Tinder-Clone
|
TinderClone/ImageSelectorViewController.swift
|
1
|
13477
|
//
// ImageSelectorViewController.swift
// TinderClone
//
// Created by Dharmesh Tarapore on 19/08/14.
// Copyright (c) 2015 Dharmesh Tarapore. All rights reserved.
//
import UIKit
class ImageSelectorViewController: UIViewController, UIAlertViewDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var profilePicture: UIImageView!
var profilePictureView:FBProfilePictureView = FBProfilePictureView()
var loginScreen:ViewController?
var userName = ""
var password = ""
var emailID = ""
var dateOfBirth = ""
var facebookLogin = false
var selecteProfilePicture = UIImage()
var user: FBGraphUser!
var selectedImage:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view
if (user != nil) {
//profilePictureView.profileID = user.id
/*for view in profilePictureView.subviews {
if let imgView = view as? UIImageView {
let img : UIImage = imgView.image
if (img != nil) {
setProfileImage(img);
break
}
}
else {
// obj is not a String
}
}*/
let str = NSString(format:"https://graph.facebook.com/%@/picture?type=large", user.id)
let url = NSURL.URLWithString(str);
var err: NSError? = NSError()
var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
var bgImage = UIImage(data:imageData)
setProfileImage(bgImage)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setUserName(name:String, password:String, Email email:String, andDateOfBirth dob:String)
{
self.userName = name
self.emailID = email
self.password = password
self.dateOfBirth = dob
println(self.password)
}
@IBAction func signUpTapped(sender: UIButton)
{
if (checkMandatoryFieldsAreSet())
{
var user = PFUser()
user.username = self.userName
user.password = self.password
user.email = self.emailID
user["dobstring"] = self.dateOfBirth
var button1 = self.view.viewWithTag(1) as UIButton
var button2 = self.view.viewWithTag(2) as UIButton
user["gender"] = button1.selected ? "male" : "female"
button1 = self.view.viewWithTag(3) as UIButton
button2 = self.view.viewWithTag(4) as UIButton
user["interestedin"] = button1.selected ? "male" : "female"
var location:CLLocation = CLLocation()
location = GlobalVariableSharedInstance.currentLocation() as CLLocation
let geoPoint = PFGeoPoint(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) as PFGeoPoint
user["location"] = geoPoint
if (facebookLogin == true)
{
user["fbID"] = self.user.id
}
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if !(error != nil)
{
let imageName = self.userName + ".jpg" as String
let userPhoto = PFObject(className: "UserPhoto")
let imageData = UIImagePNGRepresentation(self.selecteProfilePicture)
let imageFile = PFFile(name:imageName, data:imageData)
userPhoto["imageFile"] = imageName
userPhoto["imageData"] = imageFile
userPhoto["user"] = user
userPhoto.saveInBackgroundWithBlock{
(succeeded:Bool!, error:NSError!) -> Void in
MBProgressHUD.hideHUDForView(self.view, animated:false)
if !(error != nil)
{
var alert:UIAlertView = UIAlertView(title: "Welcome!", message: "Successfully Signed Up. Please login using your Email address and Password.", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}
else
{
if let errorString = error.userInfo?["error"] as? NSString
{
println(errorString)
var alert:UIAlertView = UIAlertView(title: "Welcome!", message: errorString, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
else {
var alert:UIAlertView = UIAlertView(title: "Welcome!", message: "Unable to signup.", delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
}
}
else
{
if let errorString = error.userInfo?["error"] as? NSString
{
println(errorString)
var alert:UIAlertView = UIAlertView(title: "Welcome!", message: errorString, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
else {
var alert:UIAlertView = UIAlertView(title: "Welcome!", message: "Unable to signup.", delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
}
}
}
@IBAction func selectGender(sender: UIButton)
{
if (sender.tag == 1)
{
sender.selected = true
let female = self.view.viewWithTag(2) as UIButton
female.selected = false
}
else if (sender.tag == 2)
{
sender.selected = true
let male = self.view.viewWithTag(1) as UIButton
male.selected = false
}
}
@IBAction func interestedIn(sender: UIButton)
{
if (sender.tag == 3)
{
sender.selected = true
let female = self.view.viewWithTag(4) as UIButton
female.selected = false
}
else if (sender.tag == 4)
{
sender.selected = true
let male = self.view.viewWithTag(3) as UIButton
male.selected = false
}
}
@IBAction func chooseProfilePicture(sender: UIButton)
{
let myActionSheet = UIActionSheet()
myActionSheet.delegate = self
myActionSheet.addButtonWithTitle("Camera")
myActionSheet.addButtonWithTitle("Photo Library")
myActionSheet.addButtonWithTitle("Cancel")
myActionSheet.cancelButtonIndex = 2
myActionSheet.showInView(self.view)
}
func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int)
{
var sourceType:UIImagePickerControllerSourceType = UIImagePickerControllerSourceType.Camera
if (buttonIndex == 0)
{
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) //Camera not available
{
sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}
self.displayImagepicker(sourceType)
}
else if (buttonIndex == 1)
{
sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.displayImagepicker(sourceType)
}
}
func displayImagepicker(sourceType:UIImagePickerControllerSourceType)
{
var imagePicker:UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceType
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!)
{
self.dismissViewControllerAnimated(true, completion: {
var mediatype:NSString = info[UIImagePickerControllerMediaType]! as NSString
if (mediatype == "public.image")
{
let originalImage = info[UIImagePickerControllerOriginalImage] as UIImage
print("%@",originalImage.size)
self.setProfileImage(originalImage);
}
})
}
func setProfileImage(originalImage: UIImage) {
self.profilePicture.image = self.resizeImage(originalImage, toSize: CGSizeMake(134.0, 144.0))
self.selecteProfilePicture = self.resizeImage(originalImage, toSize: CGSizeMake(320.0, 480.0))
self.selectedImage = true
}
func imagePickerControllerDidCancel(picker: UIImagePickerController!)
{
picker.dismissViewControllerAnimated(true, completion: nil)
self.selectedImage = false
}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int)
{
var username = self.userName
var pwd = self.password
PFUser.logInWithUsernameInBackground(username , password:pwd){
(user: PFUser!, error: NSError!) -> Void in
if (user != nil)
{
if (self.facebookLogin == true)
{
self.navigationController!.popToRootViewControllerAnimated(true)
//self.dismissViewControllerAnimated(false, completion: nil)
}
else
{
let loginScreen = self.navigationController!.viewControllers![0] as ViewController
loginScreen.facebookLogin = true
self.navigationController!.popToRootViewControllerAnimated(true)
}
}
else
{
if let errorString = error.userInfo?["error"] as? NSString
{
var alert:UIAlertView = UIAlertView(title: "Error", message: errorString, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
}
}
func checkMandatoryFieldsAreSet() -> Bool
{
var allFieldsAreSet = true
var message = ""
var button1 = self.view.viewWithTag(1) as UIButton
var button2 = self.view.viewWithTag(2) as UIButton
if (!button1.selected && !button2.selected)
{
message = "Please select your gender"
}
button1 = self.view.viewWithTag(3) as UIButton
button2 = self.view.viewWithTag(4) as UIButton
if (!button1.selected && !button2.selected)
{
message = "Please select whether you are interested in girls or boys"
}
if (self.selectedImage == false)
{
message = "Please select your profile picture"
}
if (message.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) != 0)
{
var alert:UIAlertView = UIAlertView(title: "Message", message: message, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
allFieldsAreSet = false
}
return allFieldsAreSet
}
func resizeImage(original : UIImage, toSize size:CGSize) -> UIImage
{
var imageSize:CGSize = CGSizeZero
if (original.size.width < original.size.height)
{
imageSize.height = size.width * original.size.height / original.size.width
imageSize.width = size.width
}
else
{
imageSize.height = size.height
imageSize.width = size.height * original.size.width / original.size.height
}
UIGraphicsBeginImageContext(imageSize)
original.drawInRect(CGRectMake(0,0,imageSize.width,imageSize.height))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
return resizedImage
}
}
|
mit
|
65d5e7dc0b9d633678b7537a9aabd70c
| 34.005195 | 211 | 0.527714 | 5.981802 | false | false | false | false |
robrix/Madness
|
Madness/String.swift
|
1
|
2296
|
//
// String.swift
// Madness
//
// Created by Josh Vera on 10/19/15.
// Copyright © 2015 Rob Rix. All rights reserved.
//
import Foundation
public typealias CharacterParser = Parser<String.CharacterView, Character>.Function
public typealias CharacterArrayParser = Parser<String.CharacterView, [Character]>.Function
public typealias StringParser = Parser<String.CharacterView, String>.Function
public typealias DoubleParser = Parser<String.CharacterView, Double>.Function
public typealias IntParser = Parser<String.CharacterView, Int>.Function
private func maybePrepend<T>(_ value: T?) -> ([T]) -> [T] {
return { value != nil ? [value!] + $0 : $0 }
}
private func concat<T>(_ value: [T]) -> ([T]) -> [T] {
return { value + $0 }
}
private func concat2<T>(_ value: [T]) -> ([T]) -> ([T]) -> [T] {
return { value2 in { value + value2 + $0 } }
}
private let someDigits: CharacterArrayParser = some(digit)
// Parses integers as an array of characters
public let int: CharacterArrayParser = {
let minus: Parser<String.CharacterView, Character?>.Function = char("-")|?
return maybePrepend <^> minus <*> someDigits
}()
private let decimal: CharacterArrayParser = prepend <^> %"." <*> someDigits
private let exp: StringParser = %"e+" <|> %"e-" <|> %"e" <|> %"E+" <|> %"E-" <|> %"E"
private let exponent: CharacterArrayParser = { s in { s.characters + $0 } } <^> exp <*> someDigits
// Parses floating point numbers as doubles
public let number: DoubleParser = { characters in Double(String(characters))! } <^>
((concat2 <^> int <*> decimal <*> exponent)
<|> (concat <^> int <*> decimal)
<|> (concat <^> int <*> exponent)
<|> int)
public let digit: CharacterParser = oneOf("0123456789")
public let space: CharacterParser = char(" ")
public let newline: CharacterParser = char("\n")
public let cr = char("\r")
public let crlf: CharacterParser = char("\r\n")
public let endOfLine: CharacterParser = newline <|> crlf
public let tab: CharacterParser = char("\t")
public func oneOf(_ input: String) -> CharacterParser {
return satisfy { input.characters.contains($0) }
}
public func noneOf(_ input: String) -> CharacterParser {
return satisfy { !input.characters.contains($0) }
}
public func char(_ input: Character) -> CharacterParser {
return satisfy { $0 == input }
}
|
mit
|
1634c65675cb49c4b24ee6d4d93be183
| 29.197368 | 98 | 0.675381 | 3.660287 | false | false | false | false |
thelukester92/swift-engine
|
swift-engine/Engine/Systems/LGAnimationSystem.swift
|
1
|
1853
|
//
// LGAnimationSystem.swift
// swift-engine
//
// Created by Luke Godfrey on 8/8/14.
// Copyright (c) 2014 Luke Godfrey. See LICENSE.
//
public final class LGAnimationSystem: LGSystem
{
public enum Event: String
{
case AnimationEnd = "animationEnd"
}
var sprites = [LGSprite]()
var animatables = [LGAnimatable]()
var animations = [LGAnimation?]()
public override init() {}
override public func accepts(entity: LGEntity) -> Bool
{
return entity.has(LGSprite) && entity.has(LGAnimatable)
}
override public func add(entity: LGEntity)
{
super.add(entity)
let sprite = entity.get(LGSprite)!
let animatable = entity.get(LGAnimatable)!
sprites.append(sprite)
animatables.append(animatable)
animations.append(nil)
}
override public func remove(index: Int)
{
super.remove(index)
sprites.removeAtIndex(index)
animatables.removeAtIndex(index)
animations.removeAtIndex(index)
}
override public func update()
{
for id in 0 ..< entities.count
{
let sprite = sprites[id]
let animatable = animatables[id]
if let animation = animatable.currentAnimation
{
if animations[id] == nil || animations[id]! != animation
{
animations[id] = animation
sprite.frame = animation.start
animatable.counter = 0
}
if animation.end > animation.start
{
if ++animatable.counter > animation.ticksPerFrame
{
animatable.counter = 0
if ++sprite.frame > animation.end
{
if animation.loops
{
sprite.frame = animation.start
}
else
{
sprite.frame = animation.end
}
if let scriptable = entities[id].get(LGScriptable)
{
scriptable.events.append(LGScriptable.Event(name: Event.AnimationEnd.rawValue))
}
}
}
}
}
}
}
}
|
mit
|
ae0cf0dedc5610783c6f751cd9ac7f58
| 19.362637 | 87 | 0.636805 | 3.338739 | false | false | false | false |
ochan1/OC-PublicCode
|
Makestagram/Makestagram/Controllers/CreateUsernameViewController.swift
|
1
|
2942
|
//
// CreateUsernameViewController.swift
// Makestagram
//
// Created by Oscar Chan on 7/2/17.
// Copyright © 2017 Oscar Chan. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseDatabase
class CreateUsernameViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var nextButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
nextButton.layer.cornerRadius = 6
}
@IBAction func nextButtonTapped(_ sender: UIButton) {
/*
// 1
guard let firUser = Auth.auth().currentUser,
let username = usernameTextField.text,
!username.isEmpty else { return }
// 2
let userAttrs = ["username": username]
// 3
let ref = Database.database().reference().child("users").child(firUser.uid)
// 4
ref.setValue(userAttrs) { (error, ref) in
if let error = error {
assertionFailure(error.localizedDescription)
return
}
// 5
ref.observeSingleEvent(of: .value, with: { (snapshot) in
let user = User(snapshot: snapshot)
// handle newly created user here
})
}
*/
guard let firUser = Auth.auth().currentUser,
let username = usernameTextField.text,
!username.isEmpty else { return }
UserService.create(firUser, username: username) { (user) in
/*
guard let user = user else { return }
print("Created new user: \(user.username)")
*/
/*
guard let _ = user else {
return
}
let storyboard = UIStoryboard(name: "Main", bundle: .main)
if let initialViewController = storyboard.instantiateInitialViewController() {
self.view.window?.rootViewController = initialViewController
self.view.window?.makeKeyAndVisible()
}
*/
guard let user = user else {
// handle error
return
}
User.setCurrent(user, writeToUserDefaults: true)
/*
let storyboard = UIStoryboard(name: "Main", bundle: .main)
if let initialViewController = storyboard.instantiateInitialViewController() {
self.view.window?.rootViewController = initialViewController
self.view.window?.makeKeyAndVisible()
}
*/
let initialViewController = UIStoryboard.initialViewController(for: .main)
self.view.window?.rootViewController = initialViewController
self.view.window?.makeKeyAndVisible()
}
}
}
|
mit
|
129971056d3fb40f9cc2f383d212a12d
| 30.623656 | 90 | 0.540972 | 5.612595 | false | false | false | false |
mitchtreece/Bulletin
|
Example/Pods/Espresso/Espresso/Classes/Core/UIKit/UITransition/Transitions/UIPushBackTransition.swift
|
1
|
5060
|
//
// UIPushBackTransition.swift
// Espresso
//
// Created by Mitch Treece on 6/26/18.
//
import UIKit
/**
A push-back view controller transition.
*/
public class UIPushBackTransition: UITransition {
/**
The covered view controller's scale; _defaults to 0.8_.
*/
public var pushBackScale: CGFloat
/**
The covered view controller's alpha; _defaults to 0.3_.
*/
public var pushBackAlpha: CGFloat
/**
The covered view controller's corner radius; _defaults to 20_.
*/
public var roundedCornerRadius: CGFloat
/**
Initializes the transition with parameters.
- Parameter pushBackScale: The covered view controller's scale; _defaults to 0.8_.
- Parameter pushBackAlpha: The covered view controller's alpha; _defaults to 0.3_.
- Parameter roundedCornerRadius: The covered view controller's corner radius; _defaults to 20_.
*/
public init(pushBackScale: CGFloat = 0.8, pushBackAlpha: CGFloat = 0.3, roundedCornerRadius: CGFloat = 20) {
self.pushBackScale = pushBackScale
self.pushBackAlpha = pushBackAlpha
self.roundedCornerRadius = roundedCornerRadius
super.init()
self.presentation.direction = .up
self.dismissal.direction = .down
}
override public func transitionController(for transitionType: TransitionType, info: Info) -> UITransitionController {
let isPresentation = (transitionType == .presentation)
let settings = self.settings(for: transitionType)
return isPresentation ? _present(with: info, settings: settings) : _dismiss(with: info, settings: settings)
}
private func _present(with info: Info, settings: Settings) -> UITransitionController {
let sourceVC = info.sourceViewController
let destinationVC = info.destinationViewController
let container = info.transitionContainerView
let context = info.context
let previousClipsToBound = sourceVC.view.clipsToBounds
let previousCornerRadius = sourceVC.view.layer.cornerRadius
return UITransitionController(setup: {
destinationVC.view.frame = context.finalFrame(for: destinationVC)
container.addSubview(destinationVC.view)
destinationVC.view.transform = self.boundsTransform(in: container, direction: settings.direction.reversed())
sourceVC.view.clipsToBounds = true
}, animations: {
UIAnimation(.spring(damping: 0.9, velocity: CGVector(dx: 0.25, dy: 0)), {
sourceVC.view.layer.cornerRadius = self.roundedCornerRadius
sourceVC.view.transform = CGAffineTransform(scaleX: self.pushBackScale, y: self.pushBackScale)
sourceVC.view.alpha = self.pushBackAlpha
destinationVC.view.transform = .identity
})
}, completion: {
sourceVC.view.clipsToBounds = previousClipsToBound
sourceVC.view.layer.cornerRadius = previousCornerRadius
sourceVC.view.transform = .identity
sourceVC.view.alpha = 1
context.completeTransition(!context.transitionWasCancelled)
})
}
private func _dismiss(with info: Info, settings: Settings) -> UITransitionController {
let sourceVC = info.sourceViewController
let destinationVC = info.destinationViewController
let container = info.transitionContainerView
let context = info.context
let previousClipsToBound = destinationVC.view.clipsToBounds
let previousCornerRadius = destinationVC.view.layer.cornerRadius
return UITransitionController(setup: {
destinationVC.view.alpha = self.pushBackAlpha
destinationVC.view.frame = context.finalFrame(for: destinationVC)
container.insertSubview(destinationVC.view, belowSubview: sourceVC.view)
destinationVC.view.transform = CGAffineTransform(scaleX: self.pushBackScale, y: self.pushBackScale)
destinationVC.view.layer.cornerRadius = self.roundedCornerRadius
destinationVC.view.clipsToBounds = true
}, animations: {
UIAnimation(.spring(damping: 0.9, velocity: CGVector(dx: 0.25, dy: 0)), {
sourceVC.view.transform = self.boundsTransform(in: container, direction: settings.direction)
destinationVC.view.layer.cornerRadius = previousCornerRadius
destinationVC.view.transform = .identity
destinationVC.view.alpha = 1
})
}, completion: {
destinationVC.view.clipsToBounds = previousClipsToBound
context.completeTransition(!context.transitionWasCancelled)
})
}
}
|
mit
|
75f39009ab871a64fc128d5470140260
| 36.481481 | 121 | 0.629644 | 5.44086 | false | false | false | false |
movabletype/smartphone-app
|
MT_iOS/MT_iOS/Classes/ViewController/EntryTextEditorViewController.swift
|
1
|
4299
|
//
// EntryTextEditorViewController.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/05.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
class EntryTextEditorViewController: BaseViewController, UITextViewDelegate {
var textView: UITextView!
var object: EntryTextItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.textView = UITextView(frame: self.view.bounds)
self.textView.autocapitalizationType = UITextAutocapitalizationType.None
self.textView.autocorrectionType = UITextAutocorrectionType.No
self.textView.font = UIFont.systemFontOfSize(13.0)
self.textView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
self.textView.autoresizesSubviews = true
self.textView.delegate = self
self.view.addSubview(self.textView)
self.title = object.label
self.textView.text = object.text
self.textView.selectedRange = NSRange()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "saveButtonPushed:")
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_arw"), left: true, target: self, action: "backButtonPushed:")
self.textView.becomeFirstResponder()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func keyboardWillShow(notification: NSNotification) {
var info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
var insets = self.textView.contentInset
insets.bottom = keyboardFrame.size.height
UIView.animateWithDuration(duration, animations:
{_ in
self.textView.contentInset = insets;
}
)
}
func keyboardWillHide(notification: NSNotification) {
var info = notification.userInfo!
// var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
var insets = self.textView.contentInset
insets.bottom = 0
UIView.animateWithDuration(duration, animations:
{_ in
self.textView.contentInset = insets;
}
)
}
@IBAction func saveButtonPushed(sender: UIBarButtonItem) {
object.text = textView.text
object.isDirty = true
self.navigationController?.popViewControllerAnimated(true)
}
@IBAction func backButtonPushed(sender: UIBarButtonItem) {
if self.textView.text == object.text {
self.navigationController?.popViewControllerAnimated(true)
return
}
Utils.confrimSave(self)
}
}
|
mit
|
85f34526604aa628ac012f72f487fd44
| 37.711712 | 156 | 0.686991 | 5.566062 | false | false | false | false |
avenwu/jk-address-book
|
ios/Pods/Kanna/Source/libxml/libxmlParserOption.swift
|
2
|
6041
|
/**@file libxmlParserOption.swift
Kanna
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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.
*/
/*
Libxml2HTMLParserOptions
*/
public struct Libxml2HTMLParserOptions : OptionSetType {
public typealias RawValue = UInt
private var value: UInt = 0
init(_ value: UInt) { self.value = value }
private init(_ opt: htmlParserOption) { self.value = UInt(opt.rawValue) }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: Libxml2HTMLParserOptions { return self.init(0) }
static func fromMask(raw: UInt) -> Libxml2HTMLParserOptions { return self.init(raw) }
public var rawValue: UInt { return self.value }
static var STRICT: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(0) }
static var RECOVER: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_RECOVER) }
static var NODEFDTD: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NODEFDTD) }
static var NOERROR: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOERROR) }
static var NOWARNING: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOWARNING) }
static var PEDANTIC: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_PEDANTIC) }
static var NOBLANKS: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOBLANKS) }
static var NONET: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NONET) }
static var NOIMPLIED: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_NOIMPLIED) }
static var COMPACT: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_COMPACT) }
static var IGNORE_ENC: Libxml2HTMLParserOptions { return Libxml2HTMLParserOptions(HTML_PARSE_IGNORE_ENC) }
}
/*
Libxml2XMLParserOptions
*/
public struct Libxml2XMLParserOptions: OptionSetType {
public typealias RawValue = UInt
private var value: UInt = 0
init(_ value: UInt) { self.value = value }
private init(_ opt: xmlParserOption) { self.value = UInt(opt.rawValue) }
public init(rawValue value: UInt) { self.value = value }
public init(nilLiteral: ()) { self.value = 0 }
public static var allZeros: Libxml2XMLParserOptions { return self.init(0) }
static func fromMask(raw: UInt) -> Libxml2XMLParserOptions { return self.init(raw) }
public var rawValue: UInt { return self.value }
static var STRICT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(0) }
static var RECOVER: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_RECOVER) }
static var NOENT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOENT) }
static var DTDLOAD: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_DTDLOAD) }
static var DTDATTR: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_DTDATTR) }
static var DTDVALID: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_DTDVALID) }
static var NOERROR: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOERROR) }
static var NOWARNING: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOWARNING) }
static var PEDANTIC: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_PEDANTIC) }
static var NOBLANKS: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOBLANKS) }
static var SAX1: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_SAX1) }
static var XINCLUDE: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_XINCLUDE) }
static var NONET: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NONET) }
static var NODICT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NODICT) }
static var NSCLEAN: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NSCLEAN) }
static var NOCDATA: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOCDATA) }
static var NOXINCNODE: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOXINCNODE) }
static var COMPACT: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_COMPACT) }
static var OLD10: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_OLD10) }
static var NOBASEFIX: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_NOBASEFIX) }
static var HUGE: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_HUGE) }
static var OLDSAX: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_OLDSAX) }
static var IGNORE_ENC: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_IGNORE_ENC) }
static var BIG_LINES: Libxml2XMLParserOptions { return Libxml2XMLParserOptions(XML_PARSE_BIG_LINES) }
}
|
apache-2.0
|
4b31ae1a1e27f49085136bc4b12287a9
| 65.384615 | 110 | 0.774044 | 3.808953 | false | false | false | false |
mohonish/MCPushUpPopupTransition
|
Pod/Classes/BlurPresentAnimationController.swift
|
1
|
2165
|
//
// BlurPresentAnimationController.swift
// Pods
//
// Created by Mohonish Chakraborty on 29/03/16.
//
//
import Foundation
import UIKit
public class BlurPresentAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
let duration: NSTimeInterval!
let alphaValue: CGFloat!
public init(duration: NSTimeInterval, alphaValue: CGFloat) {
self.duration = duration
self.alphaValue = alphaValue
}
// MARK: - UIViewControllerAnimatedTransitioning Protocol
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return self.duration
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let finalFrameForVC = transitionContext.finalFrameForViewController(toViewController!)
let containerView = transitionContext.containerView()
let bounds = UIScreen.mainScreen().bounds
toViewController!.view.frame = CGRectOffset(finalFrameForVC, 0, bounds.size.height)
// Blur Effect
let blurEffect = UIBlurEffect(style: .Light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = fromViewController!.view.bounds
blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
blurEffectView.tag = 151
blurEffectView.alpha = 0
fromViewController!.view.addSubview(blurEffectView)
containerView?.addSubview((toViewController?.view)!)
UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
blurEffectView.alpha = self.alphaValue
toViewController!.view.frame = finalFrameForVC
}, completion: {
finished in
transitionContext.completeTransition(true)
})
}
}
|
mit
|
de54b116bfafaf5eab3cfb8377e1d5f6
| 35.083333 | 113 | 0.700693 | 6.60061 | false | false | false | false |
selfzhou/Swift3
|
Playground/Swift3-III.playground/Pages/Enumerations.xcplaygroundpage/Contents.swift
|
1
|
1967
|
//: [Previous](@previous)
import Foundation
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
// productBarcode = .qrCode("ABCDEFG")
switch productBarcode {
case let .upc(numberSystem, manufactureer, product, check):
print(numberSystem, manufactureer, product, check)
case let .qrCode(productBarcode):
print(productBarcode)
}
/** 原始值
对于一个特点的枚举成员,它的原始值始终保持不变。关联值时创建一个基于枚举成员的常量或变量时才设置的值,枚举成员的关联值时可以变化的。
*/
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
enum CompassPoint: String {
case north, south, east, west
}
let earthsOther = Planet.earth.rawValue
let sunsetDirection = CompassPoint.west.rawValue
if let possiblePlant = Planet(rawValue: 7) {
print(possiblePlant)
switch possiblePlant {
case .earth:
print("earth")
default:
print("not earth")
}
}
// 递归枚举 `indirect`
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case let .number(value):
return value
case let .addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right)
}
}
evaluate(product)
|
mit
|
f0d24316309f4d2ce775cc1ffb558914
| 24.305556 | 86 | 0.715541 | 3.841772 | false | false | false | false |
MaartenBrijker/project
|
project/External/AudioKit-master/AudioKit/OSX/AudioKit/AudioKit for OSX.playground/Pages/Plucked String.xcplaygroundpage/Contents.swift
|
2
|
995
|
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Plucked String
//: ### Experimenting with a physical model of a string
import AudioKit
import XCPlayground
let playRate = 2.0
let pluckedString = AKPluckedString(frequency: 22050)
var delay = AKDelay(pluckedString)
delay.time = 1.5 / playRate
delay.dryWetMix = 0.3
delay.feedback = 0.2
let reverb = AKReverb(delay)
AudioKit.output = reverb
AudioKit.start()
let scale = [0, 2, 4, 5, 7, 9, 11, 12]
AKPlaygroundLoop(frequency: playRate) {
var note = scale.randomElement()
let octave = randomInt(2...5) * 12
if random(0, 10) < 1.0 { note++ }
if !scale.contains(note % 12) { print("ACCIDENT!") }
let frequency = (note+octave).midiNoteToFrequency()
if random(0, 6) > 1.0 {
pluckedString.trigger(frequency: frequency)
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
|
apache-2.0
|
12521446703687df624cc67e84f72d9e
| 25.184211 | 72 | 0.666332 | 3.305648 | false | false | false | false |
imjerrybao/PureLayout
|
PureLayout/Example-iOS/Demos/iOSDemo5ViewController.swift
|
20
|
2376
|
//
// iOSDemo5ViewController.swift
// PureLayout Example-iOS
//
// Copyright (c) 2015 Tyler Fox
// https://github.com/PureLayout/PureLayout
//
import UIKit
import PureLayout
@objc(iOSDemo5ViewController)
class iOSDemo5ViewController: UIViewController {
let blueView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .blueColor()
view.layer.borderColor = UIColor.lightGrayColor().CGColor
view.layer.borderWidth = 0.5
return view
}()
let redView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .redColor()
return view
}()
let purpleLabel: UILabel = {
let label = UILabel.newAutoLayoutView()
label.backgroundColor = UIColor(red: 1.0, green: 0, blue: 1.0, alpha: 0.3) // semi-transparent purple
label.textColor = .whiteColor()
label.text = "The quick brown fox jumps over the lazy dog"
return label
}()
var didSetupConstraints = false
override func loadView() {
view = UIView()
view.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
view.addSubview(blueView)
view.addSubview(redView)
view.addSubview(purpleLabel)
view.setNeedsUpdateConstraints() // bootstrap Auto Layout
}
override func updateViewConstraints() {
if (!didSetupConstraints) {
blueView.autoCenterInSuperview()
blueView.autoSetDimensionsToSize(CGSize(width: 150.0, height: 150.0))
// Use a cross-attribute constraint to constrain an ALAxis (Horizontal) to an ALEdge (Bottom)
redView.autoConstrainAttribute(.Horizontal, toAttribute: .Bottom, ofView: blueView)
redView.autoAlignAxis(.Vertical, toSameAxisOfView: blueView)
redView.autoSetDimensionsToSize(CGSize(width: 50.0, height: 50.0))
// Use another cross-attribute constraint to place the purpleLabel's baseline on the blueView's top edge
purpleLabel.autoConstrainAttribute(.Baseline, toAttribute: .Top, ofView: blueView)
purpleLabel.autoAlignAxis(.Vertical, toSameAxisOfView: blueView)
didSetupConstraints = true
}
super.updateViewConstraints()
}
}
|
mit
|
bf1478b07bd3c7d4d19d703cde3ae37a
| 33.434783 | 116 | 0.631313 | 4.981132 | false | false | false | false |
material-components/material-components-ios
|
components/NavigationRail/examples/NavigationRailViewTypicalUse.swift
|
2
|
2615
|
// Copyright 2022-present the Material Components for iOS authors. 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 Foundation
import UIKit
import MaterialComponents.MaterialNavigationRail
@available(iOS 13.0, *)
class NavigationRailViewTypicalUse: UIViewController, NavigationRailViewDelegate {
var navigationRail: NavigationRailView = NavigationRailView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
let items = [
UITabBarItem(title: "Item 1", image: UIImage(systemName: "heart"), tag: 100),
UITabBarItem(title: "Item 2", image: UIImage(systemName: "heart"), tag: 100),
UITabBarItem(title: "Item 3", image: UIImage(systemName: "heart"), tag: 100),
UITabBarItem(title: "Item 4", image: UIImage(systemName: "heart"), tag: 100),
]
items[0].badgeValue = "1"
items[1].badgeValue = "1"
navigationRail.items = items
view.addSubview(navigationRail)
navigationRail.selectedItem = items[0]
navigationRail.translatesAutoresizingMaskIntoConstraints = false
navigationRail.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
navigationRail.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
navigationRail.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
navigationRail.widthAnchor.constraint(equalToConstant: 80).isActive = true
navigationRail.delegate = self
}
func navigationRail(_ navigationRail: NavigationRailView, didSelect item: UITabBarItem) {
if let value = item.badgeValue, let num = Int(value) {
item.badgeValue = "\(num+1)"
} else {
item.badgeValue = "1"
}
}
}
@available(iOS 13.0, *)
extension NavigationRailViewTypicalUse {
@objc class func catalogMetadata() -> [String: Any] {
return [
"breadcrumbs": ["Navigation Rail", "View Typical Use"],
"description": "Navigation Rail",
"primaryDemo": false,
"presentable": true,
"debug": false,
]
}
@objc func catalogShouldHideNavigation() -> Bool {
return true
}
}
|
apache-2.0
|
51536c09d085b0ad6ca2dd5bb4db8ac9
| 35.830986 | 91 | 0.719312 | 4.33665 | false | false | false | false |
carsonmcdonald/PlaygroundExplorer
|
PlaygroundExplorer/BrowseTableViewController.swift
|
1
|
4962
|
import Cocoa
class BrowseTableViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var browseTableView : NSTableView!
private var playgroundDataFiles: [String] = []
private var playgroundRepoData: [String:[PlaygroundEntryRepoData]]?
override func viewDidAppear() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
StatusNotification.broadcastStatus("Updating metadata")
Utils.cloneOrUpdatePlaygroundData()
self.playgroundRepoData = Utils.getRepoInformationFromPlaygroundData()
self.loadAndParsePlaygroundData()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.browseTableView.reloadData()
StatusNotification.broadcastStatus("Metadata update complete")
})
})
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 75
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let cell = tableView.makeViewWithIdentifier("BrowseTableCellView", owner: self) as? BrowseTableCellView {
if let playgroundData = self.parseJSONData(self.playgroundDataFiles[row]) {
cell.playgroundData = playgroundData
return cell
}
}
return nil
}
func tableViewSelectionDidChange(notification: NSNotification) {
if self.browseTableView.selectedRow >= 0 && self.playgroundDataFiles.count > self.browseTableView.selectedRow {
let playgroundDataFile = self.playgroundDataFiles[self.browseTableView.selectedRow]
if let playgroundData = self.parseJSONData(playgroundDataFile) {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.BrowsePlaygroundSelected, object: self, userInfo: ["playgroundData":playgroundData])
}
} else {
NSNotificationCenter.defaultCenter().postNotificationName(Config.Notification.BrowsePlaygroundSelected, object: self, userInfo: nil)
}
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return self.playgroundDataFiles.count
}
private func loadAndParsePlaygroundData() {
self.playgroundDataFiles.removeAll(keepCapacity: true)
let playgroundRepo = Utils.getPlaygroundRepoDirectory()
let files = NSFileManager.defaultManager().contentsOfDirectoryAtPath(playgroundRepo!, error: nil)
if files != nil {
for file in files! {
let filename = file as! String
if let range = filename.rangeOfString(".json") {
if range.endIndex == filename.endIndex {
if let jsonFile = playgroundRepo?.stringByAppendingPathComponent(filename) {
if NSFileManager.defaultManager().fileExistsAtPath(jsonFile) {
self.playgroundDataFiles.append(jsonFile)
}
}
}
}
}
}
}
private func parseJSONData(jsonFile:String) -> PlaygroundEntryData? {
if let jsonData = NSData(contentsOfFile: jsonFile) {
var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments, error:&parseError)
if parseError != nil {
Utils.showErrorAlert("Error parsing json in \(jsonFile): \(parseError)")
} else {
if let playgroundDataDictionary = parsedObject as? NSDictionary {
if let playgroundData = PlaygroundEntryData(jsonData: playgroundDataDictionary) {
if self.playgroundRepoData != nil {
playgroundData.repoDataList = self.playgroundRepoData![jsonFile.lastPathComponent]
}
return playgroundData
} else {
Utils.showErrorAlert("Playground data format incorrect \(jsonFile)")
}
} else {
Utils.showErrorAlert("Root is not a dictionary \(jsonFile)")
}
}
} else {
Utils.showErrorAlert("Couldn't read file \(jsonFile)")
}
return nil
}
}
|
mit
|
b95412019100950bbb79a65cab6bb07f
| 38.070866 | 178 | 0.566505 | 6.321019 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio
|
uoregon-cis-399/finalProject/TotalTime/Source/Controller/DoneViewController.swift
|
1
|
6089
|
//
// DoneViewController.swift
// TotalTime
//
// Created by Dylan Secreast on 3/17/17.
// Copyright © 2017 Dylan Secreast. All rights reserved.
//
import Foundation
import CoreData
import UIKit
import Contacts
import MessageUI
class DoneViewController : UIViewController, NSFetchedResultsControllerDelegate, MFMailComposeViewControllerDelegate {
@IBOutlet weak var currentJobLabel: UILabel!
@IBOutlet weak var TotalTimeWorkedLabel: UILabel!
@IBOutlet weak var hourlyRateLabel: UILabel!
@IBOutlet weak var invoiceTotalLabel: UILabel!
@IBOutlet weak var clientEmailLabel: UILabel!
private var jobFetchedResultsController: NSFetchedResultsController<Job>!
private var clientFetchedResultsController: NSFetchedResultsController<Client>!
var jobs: [Job] = []
var clients: [Client] = []
func fetchData() {
jobFetchedResultsController = TimeService.shared.jobData()
clientFetchedResultsController = TimeService.shared.clientData()
jobFetchedResultsController.delegate = self
clientFetchedResultsController.delegate = self
jobs = jobFetchedResultsController.fetchedObjects!
clients = clientFetchedResultsController.fetchedObjects!
currentJobLabel.text = jobs.last?.title
if (jobs.count == 0) {
hourlyRateLabel.text = "$XX.XX"
}
else {
hourlyRateLabel.text = "$" + (jobs.last?.hourlyRate.description)!
}
if (clients.count == 0) {
clientEmailLabel.text = ""
}
else {
// clientEmailLabel.text = clients[0].email
}
}
private func checkContactAuthorizationStatus(_ contactOperation: @escaping () -> Void) {
switch CNContactStore.authorizationStatus(for: .contacts) {
case .authorized:
contactOperation()
case .notDetermined:
let contactStore = CNContactStore()
contactStore.requestAccess(for: .contacts, completionHandler: { (granted: Bool, error: Error?) -> Void in
if granted {
contactOperation()
}
else {
let alertController = UIAlertController(title: "Contacts Error", message: "Contacts access is required, please check your privacy settings and try again.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
})
default:
let alertController = UIAlertController(title: "Contacts Error", message: "Contacts access is required, please check your privacy settings and try again.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
dismiss(animated: true, completion: nil)
}
private func presentMailCompositionView(withRecipient recipient: String) {
if MFMailComposeViewController.canSendMail() {
let mailComposeViewController = MFMailComposeViewController()
mailComposeViewController.mailComposeDelegate = self
mailComposeViewController.setToRecipients([recipient])
mailComposeViewController.setSubject("Completed Job")
mailComposeViewController.setMessageBody("Finished job", isHTML: false)
present(mailComposeViewController, animated: true, completion: nil)
}
else {
let alertController = UIAlertController(title: "Cannot Send Email", message: "Please go to your Settings app and configure an email account", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
}
@IBAction func sendInvoice(_ sender: Any) {
checkContactAuthorizationStatus() {
var success = false
let fetchRequest = CNContactFetchRequest(keysToFetch: [CNContactEmailAddressesKey as CNKeyDescriptor])
fetchRequest.predicate = CNContact.predicateForContacts(withIdentifiers: [self.clientEmailLabel.text!])
let contactStore = CNContactStore()
var clientContact: CNContact? = nil
do {
try contactStore.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in
clientContact = contact
stop.pointee = true
})
if let someClientContact = clientContact, let emailAddress = someClientContact.emailAddresses.first?.value as? String {
success = true
self.presentMailCompositionView(withRecipient: emailAddress)
}
else {
print("Contact not found or contact has no email address")
}
}
catch let error {
print("Error trying to enumerate contacts: \(error as NSError)")
}
if !success {
let alertController = UIAlertController(title: "No Client Found", message: "Could not send email to \(self.clientEmailLabel.text)", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
gpl-3.0
|
a5d9961f195889417ec0428f941dfe2c
| 40.986207 | 199 | 0.629599 | 5.74882 | false | false | false | false |
DylanSecreast/uoregon-cis-portfolio
|
uoregon-cis-399/examples/W5Example_W17/W5Example/Source/Controller/FruitsViewController.swift
|
1
|
3681
|
//
// FruitsViewController.swift
// W5Example
//
// Created by Charles Augustine on 1/30/17.
// Copyright © 2017 Charles. All rights reserved.
//
import CoreData
import UIKit
class FruitsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
// MARK: UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
// In the case that we encounter a nil value, we provide a default value of 0
return fruitFetchedResultsController.sections?.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// In the case that we encounter a nil value, we provide a default value of 0
return fruitFetchedResultsController.sections?[section].numberOfObjects ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Ask the table view for a cell and configure it with the object that the fetched results controller returns
// for the indexPath. Make sure to use the version of the dequeueReusableCell method that accepts the indexPath
// parameter. The other version will not work in the same way.
let cell = tableView.dequeueReusableCell(withIdentifier: "FruitCell", for: indexPath)
let fruit = fruitFetchedResultsController.object(at: indexPath)
cell.textLabel?.text = fruit.name
cell.detailTextLabel?.text = "Row \(indexPath.row)"
return cell
}
// MARK: UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// This implementation is trivial, so it would be equivalent to setup the segue directly in the storyboard. You
// should not do both, as this will cause a double segue and potentially a crash depending on how your prepare
// for segue method is implemented.
performSegue(withIdentifier: "DetailSegue", sender: self)
}
// MARK: NSFetchedResultsControllerDelegate
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
// There are additional methods in this delegate protocol that can be used for more detailed updates, for this
// simple app we can just reload the entire table for any content change.
fruitsTableView.reloadData()
}
// MARK: View Management
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DetailSegue" {
// Configure the destination view controller with information about what was selected so it can show
// appropriate details.
let fruitDetailViewController = segue.destination as! FruitDetailViewController
let indexPath = fruitsTableView.indexPathForSelectedRow!
fruitsTableView.selectRow(at: nil, animated: true, scrollPosition: .none)
fruitDetailViewController.selectedFruit = fruitFetchedResultsController?.object(at: indexPath)
}
else {
// If the segue has an identifier that is unknown to this view controller, pass it to super.
super.prepare(for: segue, sender: sender)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Retrieve the fetched results controller from the fruit service to prevent unnecessary creation of multiple
// fetches
fruitFetchedResultsController = FruitService.shared.fruits()
// Set the delegate to self so that we can respond to updates in the data
fruitFetchedResultsController.delegate = self
}
// MARK: Properties (Private)
// We use an implicitly unwrapped optional type because the value is not set until the view loads
private var fruitFetchedResultsController: NSFetchedResultsController<Fruit>!
// MARK: Properties (IBOutlet)
@IBOutlet private weak var fruitsTableView: UITableView!
}
|
gpl-3.0
|
c511edc53f6eab656140f09bba2b9eda
| 40.818182 | 126 | 0.772826 | 4.664132 | false | false | false | false |
mojidabckuu/activerecord
|
ActiveRecord/AR/Validation/Validator.swift
|
1
|
1285
|
//
// Validator.swift
// SQLite
//
// Created by Vlad Gorbenko on 5/12/16.
//
//
public protocol Validator {
func validate(record: ActiveRecord, attribute: String, value: Any?, inout errors: Errors) -> Bool
}
extension Validator {
public func validate(record: ActiveRecord, attribute: String, value: Any?, inout errors: Errors) -> Bool {
return false
}
}
public struct LengthValidator: Validator {
public var min = Int.min
public var max = Int.max
// TOOD: Add implementation for strict. Make type independent
public func validate(record: ActiveRecord, attribute: String, value: Any?, inout errors: Errors) -> Bool {
if let countable = value as? [Any] {
return countable.count >= self.min && countable.count <= self.max
} else if let countable = value as? Dictionary<String, Any> {
return countable.count >= self.min && countable.count <= self.max
} else if let string = value as? String {
return string.characters.count >= self.min && string.characters.count <= self.max
}
return false
}
}
public struct RangeValidator {
var from: Any
var to: Any
// TOOD: Add implementation
}
public struct PresentValidator {
// TOOD: Add implementation
}
|
mit
|
04a3d533dab4a7eae91e8e253abd92fc
| 28.227273 | 110 | 0.649027 | 4.11859 | false | false | false | false |
tbkka/swift-protobuf
|
Tests/SwiftProtobufTests/Test_Struct.swift
|
3
|
17122
|
// Tests/SwiftProtobufTests/Test_Struct.swift - Verify Struct well-known type
//
// Copyright (c) 2014 - 2019 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Struct, Value, ListValue are standard PRoto3 message types that support
/// general ad hoc JSON parsing and serialization.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
import SwiftProtobuf
class Test_Struct: XCTestCase, PBTestHelpers {
typealias MessageTestType = Google_Protobuf_Struct
func testStruct_pbencode() {
assertEncode([10, 12, 10, 3, 102, 111, 111, 18, 5, 26, 3, 98, 97, 114]) {(o: inout MessageTestType) in
var v = Google_Protobuf_Value()
v.stringValue = "bar"
o.fields["foo"] = v
}
}
func testStruct_pbdecode() {
assertDecodeSucceeds([10, 7, 10, 1, 97, 18, 2, 32, 1, 10, 7, 10, 1, 98, 18, 2, 8, 0]) { (m) in
let vTrue = Google_Protobuf_Value(boolValue: true)
let vNull: Google_Protobuf_Value = nil
var same = Google_Protobuf_Struct()
same.fields = ["a": vTrue, "b": vNull]
var different = Google_Protobuf_Struct()
different.fields = ["a": vTrue, "b": vNull, "c": vNull]
return (m.fields.count == 2
&& m.fields["a"] == vTrue
&& m.fields["a"] != vNull
&& m.fields["b"] == vNull
&& m.fields["b"] != vTrue
&& m == same
&& m != different)
}
}
func test_JSON() {
assertJSONDecodeSucceeds("{}") {$0.fields == [:]}
assertJSONDecodeFails("null")
assertJSONDecodeFails("false")
assertJSONDecodeFails("true")
assertJSONDecodeFails("[]")
assertJSONDecodeFails("{")
assertJSONDecodeFails("}")
assertJSONDecodeFails("{}}")
assertJSONDecodeFails("{]")
assertJSONDecodeFails("1")
assertJSONDecodeFails("\"1\"")
}
func test_JSON_field() throws {
// "null" as a field value indicates the field is missing
// (Except for Value, where "null" indicates NullValue)
do {
let c1 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString:"{\"optionalStruct\":null}")
// null here decodes to an empty field.
// See github.com/protocolbuffers/protobuf Issue #1327
XCTAssertEqual(try c1.jsonString(), "{}")
} catch let e {
XCTFail("Didn't decode c1: \(e)")
}
do {
let c2 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString:"{\"optionalStruct\":{}}")
XCTAssertNotNil(c2.optionalStruct)
XCTAssertEqual(c2.optionalStruct.fields, [:])
} catch let e {
XCTFail("Didn't decode c2: \(e)")
}
}
func test_equality() throws {
let a1decoded: Google_Protobuf_Struct
do {
a1decoded = try Google_Protobuf_Struct(jsonString: "{\"a\":1}")
} catch {
XCTFail("Decode failed for {\"a\":1}")
return
}
let a2decoded = try Google_Protobuf_Struct(jsonString: "{\"a\":2}")
var a1literal = Google_Protobuf_Struct()
a1literal.fields["a"] = Google_Protobuf_Value(numberValue: 1)
XCTAssertEqual(a1literal, a1decoded)
XCTAssertEqual(a1literal.hashValue, a1decoded.hashValue)
XCTAssertNotEqual(a1decoded, a2decoded)
// Hash inequality is not guaranteed, but a collision here would be suspicious
let a1literalHash = a1literal.hashValue
let a2decodedHash = a2decoded.hashValue
XCTAssertNotEqual(a1literalHash, a2decodedHash)
}
}
class Test_JSON_ListValue: XCTestCase, PBTestHelpers {
typealias MessageTestType = Google_Protobuf_ListValue
// Since ProtobufJSONList is handbuilt rather than generated,
// we need to verify all the basic functionality, including
// serialization, equality, hash, etc.
func testProtobuf() {
assertEncode([10, 9, 17, 0, 0, 0, 0, 0, 0, 240, 63, 10, 5, 26, 3, 97, 98, 99, 10, 2, 32, 1]) { (o: inout MessageTestType) in
o.values.append(Google_Protobuf_Value(numberValue: 1))
o.values.append(Google_Protobuf_Value(stringValue: "abc"))
o.values.append(Google_Protobuf_Value(boolValue: true))
}
}
func testJSON() {
assertJSONEncode("[1.0,\"abc\",true]") { (o: inout MessageTestType) in
o.values.append(Google_Protobuf_Value(numberValue: 1))
o.values.append(Google_Protobuf_Value(stringValue: "abc"))
o.values.append(Google_Protobuf_Value(boolValue: true))
}
assertJSONEncode("[1.0,\"abc\",true,[1.0,null],[]]") { (o: inout MessageTestType) in
o.values.append(Google_Protobuf_Value(numberValue: 1))
o.values.append(Google_Protobuf_Value(stringValue: "abc"))
o.values.append(Google_Protobuf_Value(boolValue: true))
o.values.append(Google_Protobuf_Value(listValue: [1, nil]))
o.values.append(Google_Protobuf_Value(listValue: []))
}
assertJSONDecodeSucceeds("[]") {$0.values == []}
assertJSONDecodeFails("")
assertJSONDecodeFails("true")
assertJSONDecodeFails("false")
assertJSONDecodeFails("{}")
assertJSONDecodeFails("1.0")
assertJSONDecodeFails("\"a\"")
assertJSONDecodeFails("[}")
assertJSONDecodeFails("[,]")
assertJSONDecodeFails("[true,]")
assertJSONDecodeSucceeds("[true]") {$0.values == [Google_Protobuf_Value(boolValue: true)]}
}
func test_equality() throws {
let a1decoded = try Google_Protobuf_ListValue(jsonString: "[1]")
let a2decoded = try Google_Protobuf_ListValue(jsonString: "[2]")
var a1literal = Google_Protobuf_ListValue()
a1literal.values.append(Google_Protobuf_Value(numberValue: 1))
XCTAssertEqual(a1literal, a1decoded)
XCTAssertEqual(a1literal.hashValue, a1decoded.hashValue)
XCTAssertNotEqual(a1decoded, a2decoded)
// Hash inequality is not guaranteed, but a collision here would be suspicious
XCTAssertNotEqual(a1literal.hashValue, a2decoded.hashValue)
XCTAssertNotEqual(a1literal, a2decoded)
}
}
class Test_Value: XCTestCase, PBTestHelpers {
typealias MessageTestType = Google_Protobuf_Value
func testValue_empty() throws {
let empty = Google_Protobuf_Value()
// Serializing an empty value (kind not set) in binary or text is ok;
// it is only an error in JSON.
XCTAssertEqual(try empty.serializedBytes(), [])
XCTAssertEqual(empty.textFormatString(), "")
// Make sure an empty value is not equal to a nullValue value.
let null: Google_Protobuf_Value = nil
XCTAssertNotEqual(empty, null)
}
}
// TODO: Should have convenience initializers on Google_Protobuf_Value
class Test_JSON_Value: XCTestCase, PBTestHelpers {
typealias MessageTestType = Google_Protobuf_Value
func testValue_emptyShouldThrow() throws {
let empty = Google_Protobuf_Value()
do {
_ = try empty.jsonString()
XCTFail("Encoding should have thrown .missingValue, but it succeeded")
} catch JSONEncodingError.missingValue {
// Nothing to do here; this is the expected error.
} catch {
XCTFail("Encoding should have thrown .missingValue, but instead it threw: \(error)")
}
}
func testValue_null() throws {
let nullFromLiteral: Google_Protobuf_Value = nil
let null: Google_Protobuf_Value = nil
XCTAssertEqual("null", try null.jsonString())
XCTAssertEqual([8, 0], try null.serializedBytes())
XCTAssertEqual(nullFromLiteral, null)
XCTAssertNotEqual(nullFromLiteral, Google_Protobuf_Value(numberValue: 1))
assertJSONDecodeSucceeds("null") {$0.nullValue == .nullValue}
assertJSONDecodeSucceeds(" null ") {$0.nullValue == .nullValue}
assertJSONDecodeFails("numb")
do {
let m1 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalValue\": null}")
XCTAssertEqual(try m1.jsonString(), "{\"optionalValue\":null}")
XCTAssertEqual(try m1.serializedBytes(), [146, 19, 2, 8, 0])
} catch {
XCTFail()
}
XCTAssertEqual(null.debugDescription, "SwiftProtobuf.Google_Protobuf_Value:\nnull_value: NULL_VALUE\n")
}
func testValue_number() throws {
let oneFromIntegerLiteral: Google_Protobuf_Value = 1
let oneFromFloatLiteral: Google_Protobuf_Value = 1.0
let twoFromFloatLiteral: Google_Protobuf_Value = 2.0
XCTAssertEqual(oneFromIntegerLiteral, oneFromFloatLiteral)
XCTAssertNotEqual(oneFromIntegerLiteral, twoFromFloatLiteral)
XCTAssertEqual("1.0", try oneFromIntegerLiteral.jsonString())
XCTAssertEqual([17, 0, 0, 0, 0, 0, 0, 240, 63], try oneFromIntegerLiteral.serializedBytes())
assertJSONEncode("3.25") {(o: inout MessageTestType) in
o.numberValue = 3.25
}
assertJSONDecodeSucceeds("3.25") {$0.numberValue == 3.25}
assertJSONDecodeSucceeds(" 3.25 ") {$0.numberValue == 3.25}
assertJSONDecodeFails("3.2.5")
XCTAssertEqual(oneFromIntegerLiteral.debugDescription, "SwiftProtobuf.Google_Protobuf_Value:\nnumber_value: 1.0\n")
}
func testValue_string() throws {
// Literals and equality testing
let fromStringLiteral: Google_Protobuf_Value = "abcd"
XCTAssertEqual(fromStringLiteral, Google_Protobuf_Value(stringValue: "abcd"))
XCTAssertNotEqual(fromStringLiteral, Google_Protobuf_Value(stringValue: "abc"))
XCTAssertNotEqual(fromStringLiteral, Google_Protobuf_Value())
// JSON serialization
assertJSONEncode("\"abcd\"") {(o: inout MessageTestType) in
o.stringValue = "abcd"
}
assertJSONEncode("\"\"") {(o: inout MessageTestType) in
o.stringValue = ""
}
assertJSONDecodeSucceeds("\"abcd\"") {$0.stringValue == "abcd"}
assertJSONDecodeSucceeds(" \"abcd\" ") {$0.stringValue == "abcd"}
assertJSONDecodeFails("\"abcd\" XXX")
assertJSONDecodeFails("\"abcd")
// JSON serializing special characters
XCTAssertEqual("\"a\\\"b\"", try Google_Protobuf_Value(stringValue: "a\"b").jsonString())
let valueWithEscapes = Google_Protobuf_Value(stringValue: "a\u{0008}\u{0009}\u{000a}\u{000c}\u{000d}b")
let serializedValueWithEscapes = try valueWithEscapes.jsonString()
XCTAssertEqual("\"a\\b\\t\\n\\f\\rb\"", serializedValueWithEscapes)
do {
let parsedValueWithEscapes = try Google_Protobuf_Value(jsonString: serializedValueWithEscapes)
XCTAssertEqual(valueWithEscapes.stringValue, parsedValueWithEscapes.stringValue)
} catch {
XCTFail("Failed to decode \(serializedValueWithEscapes)")
}
// PB serialization
XCTAssertEqual([26, 3, 97, 34, 98], try Google_Protobuf_Value(stringValue: "a\"b").serializedBytes())
XCTAssertEqual(fromStringLiteral.debugDescription, "SwiftProtobuf.Google_Protobuf_Value:\nstring_value: \"abcd\"\n")
}
func testValue_bool() {
let trueFromLiteral: Google_Protobuf_Value = true
let falseFromLiteral: Google_Protobuf_Value = false
XCTAssertEqual(trueFromLiteral, Google_Protobuf_Value(boolValue: true))
XCTAssertEqual(falseFromLiteral, Google_Protobuf_Value(boolValue: false))
XCTAssertNotEqual(falseFromLiteral, trueFromLiteral)
assertJSONEncode("true") {(o: inout MessageTestType) in
o.boolValue = true
}
assertJSONEncode("false") {(o: inout MessageTestType) in
o.boolValue = false
}
assertJSONDecodeSucceeds("true") {$0.boolValue == true}
assertJSONDecodeSucceeds(" false ") {$0.boolValue == false}
assertJSONDecodeFails("yes")
assertJSONDecodeFails(" true false ")
XCTAssertEqual(trueFromLiteral.debugDescription, "SwiftProtobuf.Google_Protobuf_Value:\nbool_value: true\n")
}
func testValue_struct() throws {
assertJSONEncode("{\"a\":1.0}") {(o: inout MessageTestType) in
o.structValue = Google_Protobuf_Struct(fields:["a": Google_Protobuf_Value(numberValue: 1)])
}
let structValue = try Google_Protobuf_Value(jsonString: "{\"a\":1.0}")
let d = structValue.debugDescription
XCTAssertEqual(d, "SwiftProtobuf.Google_Protobuf_Value:\nstruct_value {\n fields {\n key: \"a\"\n value {\n number_value: 1.0\n }\n }\n}\n")
}
func testValue_list() throws {
let listValue = try Google_Protobuf_Value(jsonString: "[1, true, \"abc\"]")
let d = listValue.debugDescription
XCTAssertEqual(d, "SwiftProtobuf.Google_Protobuf_Value:\nlist_value {\n values {\n number_value: 1.0\n }\n values {\n bool_value: true\n }\n values {\n string_value: \"abc\"\n }\n}\n")
}
func testValue_complex() {
assertJSONDecodeSucceeds("{\"a\": {\"b\": 1.0}, \"c\": [ 7, true, null, {\"d\": false}]}") {
let outer = $0.structValue.fields
let a = outer["a"]?.structValue.fields
let c = outer["c"]?.listValue.values
return (a?["b"]?.numberValue == 1.0
&& c?.count == 4
&& c?[0].numberValue == 7
&& c?[1].boolValue == true
&& c?[2].nullValue == Google_Protobuf_NullValue()
&& c?[3].structValue.fields["d"]?.boolValue == false)
}
}
func testStruct_conformance() throws {
let json = ("{\n"
+ " \"optionalStruct\": {\n"
+ " \"nullValue\": null,\n"
+ " \"intValue\": 1234,\n"
+ " \"boolValue\": true,\n"
+ " \"doubleValue\": 1234.5678,\n"
+ " \"stringValue\": \"Hello world!\",\n"
+ " \"listValue\": [1234, \"5678\"],\n"
+ " \"objectValue\": {\n"
+ " \"value\": 0\n"
+ " }\n"
+ " }\n"
+ "}\n")
let m: ProtobufTestMessages_Proto3_TestAllTypesProto3
do {
m = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json)
} catch {
XCTFail("Decoding failed: \(json)")
return
}
XCTAssertNotNil(m.optionalStruct)
let s = m.optionalStruct
XCTAssertNotNil(s.fields["nullValue"])
if let nv = s.fields["nullValue"] {
XCTAssertEqual(nv.nullValue, Google_Protobuf_NullValue())
}
XCTAssertNotNil(s.fields["intValue"])
if let iv = s.fields["intValue"] {
XCTAssertEqual(iv, Google_Protobuf_Value(numberValue: 1234))
XCTAssertEqual(iv.numberValue, 1234)
}
XCTAssertNotNil(s.fields["boolValue"])
if let bv = s.fields["boolValue"] {
XCTAssertEqual(bv, Google_Protobuf_Value(boolValue: true))
XCTAssertEqual(bv.boolValue, true)
}
XCTAssertNotNil(s.fields["doubleValue"])
if let dv = s.fields["doubleValue"] {
XCTAssertEqual(dv, Google_Protobuf_Value(numberValue: 1234.5678))
XCTAssertEqual(dv.numberValue, 1234.5678)
}
XCTAssertNotNil(s.fields["stringValue"])
if let sv = s.fields["stringValue"] {
XCTAssertEqual(sv, Google_Protobuf_Value(stringValue: "Hello world!"))
XCTAssertEqual(sv.stringValue, "Hello world!")
}
XCTAssertNotNil(s.fields["listValue"])
if let lv = s.fields["listValue"] {
XCTAssertEqual(lv.listValue,
[Google_Protobuf_Value(numberValue: 1234),
Google_Protobuf_Value(stringValue: "5678")])
}
XCTAssertNotNil(s.fields["objectValue"])
if let ov = s.fields["objectValue"] {
XCTAssertNotNil(ov.structValue.fields["value"])
if let inner = s.fields["objectValue"]?.structValue.fields["value"] {
XCTAssertEqual(inner, Google_Protobuf_Value(numberValue: 0))
XCTAssertEqual(inner.numberValue, 0)
}
}
}
func testStruct_null() throws {
let json = ("{\n"
+ " \"optionalStruct\": null\n"
+ "}\n")
do {
let decoded = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json)
let recoded = try decoded.jsonString()
XCTAssertEqual(recoded, "{}")
} catch {
XCTFail("Should have decoded")
}
}
}
|
apache-2.0
|
eec5c4b3a25b03ce3387cd8bf3c3d7e3
| 42.020101 | 207 | 0.602324 | 4.52963 | false | true | false | false |
4np/UitzendingGemist
|
NPOKit/NPOKit/NPOManager+Token.swift
|
1
|
920
|
//
// NPOManager+Token.swift
// NPOKit
//
// Created by Jeroen Wesbeek on 14/07/16.
// Copyright © 2016 Jeroen Wesbeek. All rights reserved.
//
import Foundation
import Alamofire
import CocoaLumberjack
extension NPOManager {
internal func getToken(withCompletion completed: @escaping (_ token: String?, _ error: NPOError?) -> Void = { token, error in }) {
// use cached token?
if let token = self.token, !token.hasExpired {
//DDLogDebug("Use cached token: \(token), age: \(token.age)")
completed(token.token, nil)
return
}
// refresh token
let url = "https://ida.omroep.nl/app.php/auth"
_ = fetchModel(ofType: NPOToken.self, fromURL: url) { [weak self] token, error in
//DDLogDebug("Refreshed token: \(token)")
self?.token = token
completed(token?.token, error)
}
}
}
|
apache-2.0
|
8a48e934fda52cb0ad351632028d193c
| 29.633333 | 134 | 0.594124 | 4.0131 | false | false | false | false |
airbnb/lottie-ios
|
Sources/Private/MainThread/NodeRenderSystem/Nodes/PathNodes/StarNode.swift
|
3
|
7656
|
//
// StarNode.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/21/19.
//
import Foundation
import QuartzCore
// MARK: - StarNodeProperties
final class StarNodeProperties: NodePropertyMap, KeypathSearchable {
// MARK: Lifecycle
init(star: Star) {
keypathName = star.name
direction = star.direction
position = NodeProperty(provider: KeyframeInterpolator(keyframes: star.position.keyframes))
outerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRadius.keyframes))
outerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: star.outerRoundness.keyframes))
if let innerRadiusKeyframes = star.innerRadius?.keyframes {
innerRadius = NodeProperty(provider: KeyframeInterpolator(keyframes: innerRadiusKeyframes))
} else {
innerRadius = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
}
if let innderRoundedness = star.innerRoundness?.keyframes {
innerRoundedness = NodeProperty(provider: KeyframeInterpolator(keyframes: innderRoundedness))
} else {
innerRoundedness = NodeProperty(provider: SingleValueProvider(LottieVector1D(0)))
}
rotation = NodeProperty(provider: KeyframeInterpolator(keyframes: star.rotation.keyframes))
points = NodeProperty(provider: KeyframeInterpolator(keyframes: star.points.keyframes))
keypathProperties = [
"Position" : position,
"Outer Radius" : outerRadius,
"Outer Roundedness" : outerRoundedness,
"Inner Radius" : innerRadius,
"Inner Roundedness" : innerRoundedness,
"Rotation" : rotation,
"Points" : points,
]
properties = Array(keypathProperties.values)
}
// MARK: Internal
var keypathName: String
let keypathProperties: [String: AnyNodeProperty]
let properties: [AnyNodeProperty]
let direction: PathDirection
let position: NodeProperty<LottieVector3D>
let outerRadius: NodeProperty<LottieVector1D>
let outerRoundedness: NodeProperty<LottieVector1D>
let innerRadius: NodeProperty<LottieVector1D>
let innerRoundedness: NodeProperty<LottieVector1D>
let rotation: NodeProperty<LottieVector1D>
let points: NodeProperty<LottieVector1D>
}
// MARK: - StarNode
final class StarNode: AnimatorNode, PathNode {
// MARK: Lifecycle
init(parentNode: AnimatorNode?, star: Star) {
pathOutput = PathOutputNode(parent: parentNode?.outputNode)
properties = StarNodeProperties(star: star)
self.parentNode = parentNode
}
// MARK: Internal
/// Magic number needed for building path data
static let PolystarConstant: CGFloat = 0.47829
let properties: StarNodeProperties
let pathOutput: PathOutputNode
let parentNode: AnimatorNode?
var hasLocalUpdates = false
var hasUpstreamUpdates = false
var lastUpdateFrame: CGFloat? = nil
// MARK: Animator Node
var propertyMap: NodePropertyMap & KeypathSearchable {
properties
}
var isEnabled = true {
didSet {
pathOutput.isEnabled = isEnabled
}
}
func rebuildOutputs(frame: CGFloat) {
let path = BezierPath.star(
position: properties.position.value.pointValue,
outerRadius: properties.outerRadius.value.cgFloatValue,
innerRadius: properties.innerRadius.value.cgFloatValue,
outerRoundedness: properties.outerRoundedness.value.cgFloatValue,
innerRoundedness: properties.innerRoundedness.value.cgFloatValue,
numberOfPoints: properties.points.value.cgFloatValue,
rotation: properties.rotation.value.cgFloatValue,
direction: properties.direction)
pathOutput.setPath(path, updateFrame: frame)
}
}
extension BezierPath {
/// Constructs a `BezierPath` in the shape of a star
static func star(
position: CGPoint,
outerRadius: CGFloat,
innerRadius: CGFloat,
outerRoundedness inoutOuterRoundedness: CGFloat,
innerRoundedness inputInnerRoundedness: CGFloat,
numberOfPoints: CGFloat,
rotation: CGFloat,
direction: PathDirection)
-> BezierPath
{
var currentAngle = (rotation - 90).toRadians()
let anglePerPoint = (2 * CGFloat.pi) / numberOfPoints
let halfAnglePerPoint = anglePerPoint / 2.0
let partialPointAmount = numberOfPoints - floor(numberOfPoints)
let outerRoundedness = inoutOuterRoundedness * 0.01
let innerRoundedness = inputInnerRoundedness * 0.01
var point: CGPoint = .zero
var partialPointRadius: CGFloat = 0
if partialPointAmount != 0 {
currentAngle += halfAnglePerPoint * (1 - partialPointAmount)
partialPointRadius = innerRadius + partialPointAmount * (outerRadius - innerRadius)
point.x = (partialPointRadius * cos(currentAngle))
point.y = (partialPointRadius * sin(currentAngle))
currentAngle += anglePerPoint * partialPointAmount / 2
} else {
point.x = (outerRadius * cos(currentAngle))
point.y = (outerRadius * sin(currentAngle))
currentAngle += halfAnglePerPoint
}
var vertices = [CurveVertex]()
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
var previousPoint = point
var longSegment = false
let numPoints = Int(ceil(numberOfPoints) * 2)
for i in 0..<numPoints {
var radius = longSegment ? outerRadius : innerRadius
var dTheta = halfAnglePerPoint
if partialPointRadius != 0, i == numPoints - 2 {
dTheta = anglePerPoint * partialPointAmount / 2
}
if partialPointRadius != 0, i == numPoints - 1 {
radius = partialPointRadius
}
previousPoint = point
point.x = (radius * cos(currentAngle))
point.y = (radius * sin(currentAngle))
if innerRoundedness == 0, outerRoundedness == 0 {
vertices.append(CurveVertex(point: point + position, inTangentRelative: .zero, outTangentRelative: .zero))
} else {
let cp1Theta = (atan2(previousPoint.y, previousPoint.x) - CGFloat.pi / 2)
let cp1Dx = cos(cp1Theta)
let cp1Dy = sin(cp1Theta)
let cp2Theta = (atan2(point.y, point.x) - CGFloat.pi / 2)
let cp2Dx = cos(cp2Theta)
let cp2Dy = sin(cp2Theta)
let cp1Roundedness = longSegment ? innerRoundedness : outerRoundedness
let cp2Roundedness = longSegment ? outerRoundedness : innerRoundedness
let cp1Radius = longSegment ? innerRadius : outerRadius
let cp2Radius = longSegment ? outerRadius : innerRadius
var cp1 = CGPoint(
x: cp1Radius * cp1Roundedness * StarNode.PolystarConstant * cp1Dx,
y: cp1Radius * cp1Roundedness * StarNode.PolystarConstant * cp1Dy)
var cp2 = CGPoint(
x: cp2Radius * cp2Roundedness * StarNode.PolystarConstant * cp2Dx,
y: cp2Radius * cp2Roundedness * StarNode.PolystarConstant * cp2Dy)
if partialPointAmount != 0 {
if i == 0 {
cp1 = cp1 * partialPointAmount
} else if i == numPoints - 1 {
cp2 = cp2 * partialPointAmount
}
}
let previousVertex = vertices[vertices.endIndex - 1]
vertices[vertices.endIndex - 1] = CurveVertex(
previousVertex.inTangent,
previousVertex.point,
previousVertex.point - cp1)
vertices.append(CurveVertex(point: point + position, inTangentRelative: cp2, outTangentRelative: .zero))
}
currentAngle += dTheta
longSegment = !longSegment
}
let reverse = direction == .counterClockwise
if reverse {
vertices = vertices.reversed()
}
var path = BezierPath()
for vertex in vertices {
path.addVertex(reverse ? vertex.reversed() : vertex)
}
path.close()
return path
}
}
|
apache-2.0
|
53263e90ff5efca10ac46d5c849e28bd
| 33.486486 | 114 | 0.698929 | 4.359909 | false | false | false | false |
MichaelPatrickEllard/RateMe
|
RateMe/ViewController.swift
|
1
|
1893
|
//
// ViewController.swift
// RateMe
//
// Created by Rescue Mission Software on 9/27/14.
// Copyright (c) 2014 Rescue Mission Software. All rights reserved.
//
import UIKit
// TODO: The URL for a sample rules file. Replace this with the address of the rules file that you'll be using.
let rateRulesURL = "http://www.rescuemissionsoftware.com/XXXX0000/SampleRateMeRules.json"
// TODO: The app ID for the Meetup app. Replace this with the app ID for your app.
let appID = "375990038"
class ViewController: UIViewController, RateMeDelegate {
@IBOutlet var rateButton: UIButton!
let rateMeVC = RateMeViewController(rulesURL: rateRulesURL, appID: appID)
override func viewDidLoad() {
super.viewDidLoad()
rateButton.alpha = 0
rateMeVC.delegate = self
rateMeVC.checkRules()
}
@IBAction func rateButtonPressed(sender: AnyObject) {
presentViewController(rateMeVC, animated: true, completion: nil)
}
// Mark: RateMeDelegate Methods.
// All of these methods are optional. You don't have to implement any of them if you don't want to.
func rulesRetrieved() {
NSLog("RateMe View Controller has retrieved valid rules")
if rateMeVC.shouldRate {
UIView.animateWithDuration(2.0) {
self.rateButton.alpha = 1
}
}
}
func rulesRequestFailed(error : NSError!) {
NSLog("The request for RateMe rules failed with the following error: %@", error)
}
func rated() {
NSLog("User chose to rate the app.")
}
func askLater() {
NSLog("User said to ask later")
}
func stopAsking() {
NSLog("User said to stop asking")
}
}
|
mit
|
06ae7567dcd5fda229eb7ce29f522c99
| 23.584416 | 112 | 0.594823 | 4.507143 | false | false | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift
|
4
|
16469
|
//
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
extension KingfisherWrapper where Base: ImageView {
// MARK: Setting Image
/// Sets an image to the image view with a `Source`.
///
/// - Parameters:
/// - source: The `Source` object defines data information from network or a data provider.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
/// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
///
/// ```
/// // Set image from a network source.
/// let url = URL(string: "https://example.com/image.png")!
/// imageView.kf.setImage(with: .network(url))
///
/// // Or set image from a data provider.
/// let provider = LocalFileImageDataProvider(fileURL: fileURL)
/// imageView.kf.setImage(with: .provider(provider))
/// ```
///
/// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code
/// above is equivalent to:
///
/// ```
/// imageView.kf.setImage(with: url)
/// imageView.kf.setImage(with: provider)
/// ```
///
/// Internally, this method will use `KingfisherManager` to get the source.
/// Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with source: Source?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
mutatingSelf.placeholder = placeholder
mutatingSelf.taskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil
if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet {
// Always set placeholder while there is no image/placeholder yet.
mutatingSelf.placeholder = placeholder
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.taskIdentifier = issuedIdentifier
if base.shouldPreloadAllAnimation() {
options.preloadAllAnimationData = true
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
progressBlock: { receivedSize, totalSize in
guard issuedIdentifier == self.taskIdentifier else { return }
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
maybeIndicator?.stopAnimatingView()
guard issuedIdentifier == self.taskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.imageTask = nil
switch result {
case .success(let value):
guard self.needsTransition(options: options, cacheType: value.cacheType) else {
mutatingSelf.placeholder = nil
self.base.image = value.image
completionHandler?(result)
return
}
self.makeTransition(image: value.image, transition: options.transition) {
completionHandler?(result)
}
case .failure:
if let image = options.onFailureImage {
self.base.image = image
}
completionHandler?(result)
}
}
})
mutatingSelf.imageTask = task
return task
}
/// Sets an image to the image view with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the resource.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
/// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters
/// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
///
/// ```
/// let url = URL(string: "https://example.com/image.png")!
/// imageView.kf.setImage(with: url)
/// ```
///
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with resource: Resource?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: resource.map { .network($0) },
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
/// Sets an image to the image view with a data provider.
///
/// - Parameters:
/// - provider: The `ImageDataProvider` object contains information about the data.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// Internally, this method will use `KingfisherManager` to get the image data, from either cache
/// or the data provider. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with provider: ImageDataProvider?,
placeholder: Placeholder? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: provider.map { .provider($0) },
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
// MARK: Cancelling Downloading Task
/// Cancels the image download task of the image view if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelDownloadTask() {
imageTask?.cancel()
}
private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool {
switch options.transition {
case .none:
return false
#if !os(macOS)
default:
if options.forceTransition { return true }
if cacheType == .none { return true }
return false
#endif
}
}
private func makeTransition(image: Image, transition: ImageTransition, done: @escaping () -> Void) {
#if !os(macOS)
// Force hiding the indicator without transition first.
UIView.transition(
with: self.base,
duration: 0.0,
options: [],
animations: { self.indicator?.stopAnimatingView() },
completion: { _ in
var mutatingSelf = self
mutatingSelf.placeholder = nil
UIView.transition(
with: self.base,
duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: { transition.animations?(self.base, image) },
completion: { finished in
transition.completion?(finished)
done()
}
)
}
)
#else
done()
#endif
}
}
// MARK: - Associated Object
private var taskIdentifierKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var placeholderKey: Void?
private var imageTaskKey: Void?
extension KingfisherWrapper where Base: ImageView {
// MARK: Properties
public private(set) var taskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &taskIdentifierKey, box)
}
}
/// Holds which indicator type is going to be used.
/// Default is `.none`, means no indicator will be shown while downloading.
public var indicatorType: IndicatorType {
get {
return getAssociatedObject(base, &indicatorTypeKey) ?? .none
}
set {
switch newValue {
case .none: indicator = nil
case .activity: indicator = ActivityIndicator()
case .image(let data): indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator): indicator = anIndicator
}
setRetainedAssociatedObject(base, &indicatorTypeKey, newValue)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
public private(set) var indicator: Indicator? {
get {
let box: Box<Indicator>? = getAssociatedObject(base, &indicatorKey)
return box?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if let newIndicator = newValue {
// Set default indicator layout
let view = newIndicator.view
base.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.centerXAnchor.constraint(
equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true
view.centerYAnchor.constraint(
equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true
newIndicator.view.isHidden = true
}
// Save in associated object
// Wrap newValue with Box to workaround an issue that Swift does not recognize
// and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init))
}
}
private var imageTask: DownloadTask? {
get { return getAssociatedObject(base, &imageTaskKey) }
set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
}
/// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while
/// it is downloading an image.
public private(set) var placeholder: Placeholder? {
get { return getAssociatedObject(base, &placeholderKey) }
set {
if let previousPlaceholder = placeholder {
previousPlaceholder.remove(from: base)
}
if let newPlaceholder = newValue {
newPlaceholder.add(to: base)
} else {
base.image = nil
}
setRetainedAssociatedObject(base, &placeholderKey, newValue)
}
}
}
@objc extension ImageView {
func shouldPreloadAllAnimation() -> Bool { return true }
}
extension KingfisherWrapper where Base: ImageView {
/// Gets the image URL bound to this image view.
@available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.")
public private(set) var webURL: URL? {
get { return nil }
set { }
}
}
|
mit
|
652b928a3fd5dca9813f29115fd0736d
| 40.799492 | 120 | 0.610298 | 5.373246 | false | false | false | false |
kamleshgk/iOSStarterTemplate
|
MessagesExtension/HomeViewController.swift
|
1
|
4621
|
//
// HomeViewController.swift
// foodcolors
//
// Created by kamyFCMacBook on 1/18/17.
// Copyright © 2017 foodcolors. All rights reserved.
//
import UIKit
protocol HomeViewControllerDelegate {
func cellDidTapYes(event: FCEvent, image:UIImage)
}
class HomeViewController: UIViewController, HQPagerViewControllerDataSource, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var tabTitle: String! = ""
var tabColori: UIColor!
var tabNormalIconImage: UIImage!
var tabHighlightedIconImage: UIImage!
@IBOutlet var collectionView: UICollectionView?
var eventsArray: Array<FCEvent> = []
var delegate: HomeViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
view.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true
// Do any additional setup after loading the view.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 90, height: 90)
self.collectionView!.dataSource = self
self.collectionView!.delegate = self
self.collectionView!.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true
//self.collectionView!.register(HomeCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
self.collectionView!.backgroundColor = UIColor.white
let dataManager = FCDataManager()
dataManager.getAllEvents({ (array, error) in
let castArray = array as? Array<FCEvent>
self.eventsArray = castArray!
self.collectionView! .reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - HQPagerMenuViewItemProvider
func menuViewItemOf(inPager pagerViewController: HQPagerViewController) -> HQPagerMenuViewItemProvider {
let item = HQPagerMenuViewItemProvider(title: tabTitle, normalImage: tabNormalIconImage, selectedImage: tabHighlightedIconImage, selectedBackgroundColor: tabColori)
return item
}
// MARK: - UICollectionViewCell
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return eventsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell",
for: indexPath) as! HomeCell
let eventObject = eventsArray[indexPath.row]
//2
//let flickrPhoto = photoForIndexPath(indexPath: indexPath)
cell.backgroundColor = UIColor.white
//3
let image1 = UIImage(named:"sorrento.jpg")
let image2 = UIImage(named:"florence.jpg")
if (indexPath.row % 2 == 0)
{
cell.thumbNail.image = image1
}
else
{
cell.thumbNail.image = image2
}
cell.caption.text = eventObject.event! + " " + eventObject.place!
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let eventObject = eventsArray[indexPath.row] as FCEvent!
let image:UIImage
if (indexPath.row % 2 == 0)
{
image = UIImage(named:"sorrento.jpg")!
}
else
{
image = UIImage(named:"florence.jpg")!
}
delegate?.cellDidTapYes(event: eventObject!, image: image)
}
// MARK: - UICollection Flow
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let bounds = UIScreen.main.bounds
let screenWidth = bounds.size.width
//var height = bounds.size.height
//2 columns per screen
let cellWidth = screenWidth / 2.1; //Replace the divisor with the column count requirement. Make sure to have it in float.
let size = CGSize(width: (cellWidth - 20), height: (cellWidth - 20))
return size;
}
}
|
mit
|
ac298eb280b4f5107b3035f6fdf437f8
| 33.477612 | 172 | 0.645887 | 5.220339 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.