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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ripventura/VCUIKit | VCUIKit/Classes/VCTheme/VCDrawableView.swift | 1 | 1133 | //
// VCDrawableView.swift
// VCUIKit
//
// Created by Vitor Cesco on 23/10/17.
// Copyright © 2017 Vitor Cesco. All rights reserved.
//
import UIKit
open class VCDrawableView: VCView {
@IBInspectable open var drawFillColor: UIColor = .black {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable open var drawBackgroundColor: UIColor = .clear {
didSet {
self.setNeedsDisplay()
}
}
open var drawer: VCDrawerProtocol? {
didSet {
self.setNeedsDisplay()
}
}
public convenience init(fillColor: UIColor, backgroundColor: UIColor, drawer: VCDrawerProtocol? = nil, frame: CGRect) {
self.init(frame: frame)
self.drawFillColor = fillColor
self.drawBackgroundColor = backgroundColor
self.drawer = drawer
}
override open func draw(_ rect: CGRect) {
drawer?.draw(rect: rect, fillColor: self.drawFillColor, backgroundColor: self.drawBackgroundColor)
}
}
public protocol VCDrawerProtocol {
func draw(rect: CGRect, fillColor: UIColor, backgroundColor: UIColor)
}
| mit | 42ebc3d1b4f4a2f761d301b920e5f602 | 25.325581 | 123 | 0.639576 | 4.271698 | false | false | false | false |
exshin/PokePuzzler | PokePuzzler/GameViewController.swift | 1 | 14041 | //
// GameViewController.swift
// PokePuzzler
//
// Created by Eugene Chinveeraphan on 13/04/16.
// Copyright (c) 2016 Eugene Chinveeraphan. All rights reserved.
//
import UIKit
import SpriteKit
import AVFoundation
import CoreData
class GameViewController: UIViewController {
// MARK: Properties
// The scene draws the tiles and cookie sprites, and handles swipes.
var scene: GameScene!
// The level contains the tiles, the cookies, and most of the gameplay logic.
// Needs to be ! because it's not set in init() but in viewDidLoad().
var level: Level!
var currentLevelNum = 1
var movesLeft = 0
var myCurrentHP: Float = 0.0
var opponentCurrentHP: Float = 0.0
var myPokemon: Pokemon!
var opponentPokemon: Pokemon!
let skillDictionary = Dictionary<String, AnyObject>.loadJSONFromBundle(filename: "skills")
let typingDictionary = Dictionary<String, AnyObject>.loadJSONFromBundle(filename: "typing")
var myTurn: Bool = true
var opponentMoves: Array<Dictionary<String, Any>> = []
var opponentMoveCount: Int = 0
var myStatusEffects: Array<Dictionary<String, Any>> = []
var myStatusSprites: Dictionary<String, SKSpriteNode> = [:]
var opponentStatusEffects: Array<Dictionary<String, Any>> = []
var opponentStatusSprites: Dictionary<String, SKSpriteNode> = [:]
// Elements
var elements: [String:Int] = [:]
var opponentEnergy: [String:Int] = [:]
// Data
var tapGestureRecognizer: UITapGestureRecognizer!
lazy var backgroundMusic: AVAudioPlayer? = {
guard let url = Bundle.main.url(forResource: "Mining by Moonlight", withExtension: "mp3") else {
return nil
}
do {
let player = try AVAudioPlayer(contentsOf: url)
player.numberOfLoops = -1
return player
} catch {
return nil
}
}()
// MARK: IBOutlets
@IBOutlet weak var gameOverPanel: UIImageView!
@IBOutlet weak var movesLeftLabel: UILabel!
@IBOutlet weak var currentHPLabel: UILabel!
@IBOutlet weak var currentOpponentHPLabel: UILabel!
@IBOutlet weak var myPokemonName: UILabel!
@IBOutlet weak var opponentPokemonName: UILabel!
// MARK: IBActions
// MARK: View Controller Functions
override var prefersStatusBarHidden: Bool {
return true
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return [.portrait, .portraitUpsideDown]
}
override func viewDidLoad() {
super.viewDidLoad()
// Setup view with level 1
setupLevel(currentLevelNum)
// Start the background music.
// backgroundMusic?.play()
}
// MARK: Game functions
func setupLevel(_ levelNum: Int) {
let skView = view as! SKView
skView.isMultipleTouchEnabled = false
// Create and configure the scene.
scene = GameScene(size: skView.bounds.size)
scene.scaleMode = .aspectFill
// Setup the level.
level = Level(filename: "Level_\(levelNum)")
scene.level = level
// scene.addTiles()
scene.swipeHandler = handleSwipe
// Setup the Pokemon.
var pokemonSet = Set<Pokemon>()
pokemonSet.insert(myPokemon)
pokemonSet.insert(opponentPokemon)
scene.addPokemonSprites(for: pokemonSet)
scene.addPokemonInfo(for: pokemonSet)
// Update Pokemon Names.
myPokemonName.text = myPokemon.name
opponentPokemonName.text = opponentPokemon.name
myCurrentHP = myPokemon.stats["hp"]!
opponentCurrentHP = opponentPokemon.stats["hp"]!
// Setup moves left
movesLeft = Int(myPokemon.stats["turns"]!)
// Setup skills buttons
scene.addPokemonMoveset(pokemon: myPokemon, view: skView)
self.addPokemonSkillButtons()
gameOverPanel.isHidden = true
// Present the scene.
skView.presentScene(scene)
// Start the game.
beginGame()
}
func beginGame() {
myTurn = true
for skill in self.myPokemon.moveset {
elements[skill["type"] as! String] = 0
}
for skill in self.opponentPokemon.moveset {
opponentEnergy[skill["type"] as! String] = 0
}
updateLabels()
scene.animateBeginGame() {
}
shuffle()
}
func shuffle() {
scene.removeAllCookieSprites()
// Fill up the level with new cookies, and create sprites for them.
var energySet: Set<String>
if level.energySet.count == 0 {
energySet = Set(Array(self.elements.keys) + Array(self.opponentEnergy.keys))
repeat {
energySet.insert(CookieType.random().description)
} while energySet.count < 7
} else {
energySet = Set(level.energySet)
}
let newCookies = level.shuffle(energySet: Array(energySet))
scene.addSprites(for: newCookies) {}
}
// This is the swipe handler. MyScene invokes this function whenever it
// detects that the player performs a swipe.
func handleSwipe(_ swap: Swap) {
// While cookies are being matched and new cookies fall down to fill up
// the holes, we don't want the player to tap on anything.
view.isUserInteractionEnabled = false
if level.isPossibleSwap(swap) {
level.performSwap(swap)
scene.animate(swap: swap) {
self.handleMatches() { }
}
// Decrement number of user moves this turn
decrementMoves()
} else {
scene.animateInvalidSwap(swap) {
self.view.isUserInteractionEnabled = true
}
}
}
func beginNextTurn() {
level.detectPossibleSwaps()
if level.possibleSwaps.count == 0 {
shuffle()
}
healthCheck()
view.isUserInteractionEnabled = true
}
// This is the main loop that removes any matching cookies and fills up the
// holes with new cookies. While this happens, the user cannot interact with
// the app.
func handleMatches(completion: @escaping() -> ()) {
// Detect if there are any matches left.
let chains = level.removeMatches()
// If there are no more matches, then the player gets to move again.
if chains.count == 0 {
if self.myTurn == false {
// We don't want to trigger beginNextTurn on the opponents turn
self.runAISkills()
} else {
// Else we begin the next player move
// Check if there are 0 moves left so we can swtich to AI Turn
turnCheck()
completion()
}
} else {
// First, remove any matches...
scene.animateMatchedCookies(for: chains) {
var dmg: Float = 0.0
// Add the new scores to the total.
// Add elements scores to total.
if self.myTurn == true {
for chain in chains {
let elementType = chain.cookieType
if self.elements[elementType] != nil {
self.elements[elementType]! += chain.score
}
// If the chain is a match-5 then gain back 1 move this turn
let chainType: String = chain.chainType.description
if chainType == "LShape" || chainType == "TShape" || chain.score > 4 {
self.movesLeft += 1
// Animate a match-5 banner with info that the user got an extra turn
self.scene.animateExtraMoveGain(chain: chain) {}
}
// Minor Damage for each Match
dmg = Float(chain.score) - Float(2)
self.opponentCurrentHP += -dmg
if self.opponentCurrentHP <= 0 {
self.opponentCurrentHP = 0
}
self.scene.animateDamage(pokemon: self.opponentPokemon, damageValue: Int(dmg)) {
self.updateHPValue(currentHP: self.opponentCurrentHP, maxHP: self.opponentPokemon.stats["hp"]!, target: "opponentPokemon")
}
}
// Update energy values
for elementType in self.elements.keys {
if self.elements[elementType] != nil && self.elements[elementType]! > 0 {
for skill in self.myPokemon.moveset {
if skill["type"]! as! String == elementType {
let cost = skill["cost"]! as! Float
let currentElementValue = Float(self.elements[elementType]!)
let skillBarName = skill["name"]! as! String + "CostBar"
self.updateCostBarValue(energyCurrent: currentElementValue, energyCost: cost, skillBarName: skillBarName)
}
}
}
}
} else {
for chain in chains {
let elementType = chain.cookieType
if self.opponentEnergy[elementType] != nil {
self.opponentEnergy[elementType]! += chain.score
}
// Minor Damage for each Match
dmg = Float(chain.score) - Float(2)
self.myCurrentHP += -dmg
if self.myCurrentHP <= 0 {
self.myCurrentHP = 0
}
self.scene.animateDamage(pokemon: self.myPokemon, damageValue: Int(dmg)) {
}
self.updateHPValue(currentHP: self.myCurrentHP, maxHP: self.myPokemon.stats["hp"]!, target: "myPokemon")
}
}
self.updateLabels()
// ...then shift down any cookies that have a hole below them...
let columns = self.level.fillHoles()
self.scene.animateFallingCookiesFor(columns: columns) {
// ...and finally, add new cookies at the top.
let columns = self.level.topUpCookies()
self.scene.animateNewCookies(columns) {
// Keep repeating this cycle until there are no more matches.
self.handleMatches() {
completion()
}
}
}
}
}
}
func updateLabels() {
movesLeftLabel.text = String(format: "%ld", movesLeft)
currentHPLabel.text = String(format: "%ld", Int(myCurrentHP))
currentOpponentHPLabel.text = String(format: "%ld", Int(opponentCurrentHP))
}
func updateHPValue(currentHP: Float, maxHP: Float, target: String) {
// target is either opponentPokemon or myPokemon
let healthBar = scene.pokemonLayer.childNode(withName: target)!
let maxCGValue: Float = 102.0
let oldCGValue: Float = Float(healthBar.frame.size.width)
let hpPercent: Float = currentHP / maxHP
let newHPValue = hpPercent * maxCGValue
let cgDiff = newHPValue - oldCGValue
let reduceHealth = SKAction.resize(byWidth: CGFloat(cgDiff), height: 0, duration: 0.5)
healthBar.run(reduceHealth)
updateLabels()
}
func updateCostBarValue(energyCurrent: Float, energyCost: Float, skillBarName: String) {
let energyBar = scene.pokemonLayer.childNode(withName: skillBarName)!
let maxCGValue: Float = 70
var energyPercent: Float = energyCurrent / energyCost
if energyPercent > 1.0 {
energyPercent = 1.0
// Enough Energy to use skill
// Add border and shadow to button
// Make the button press animate
} else {
// Remove border and shadow to button
// Remove the button press animate
}
let energyValue = energyPercent * maxCGValue
let previousCGValue = Float(energyBar.frame.size.width)
let cgDiff = energyValue - previousCGValue
let updateEnergyBar = SKAction.resize(byWidth: CGFloat(cgDiff), height: 0, duration: 0.5)
energyBar.run(updateEnergyBar)
}
func decrementMoves() {
movesLeft -= 1
updateLabels()
}
func healthCheck() {
if opponentCurrentHP <= 0 {
// currentLevelNum = currentLevelNum < NumLevels ? currentLevelNum+1 : 1
showGameOver(status: "win")
} else if myCurrentHP <= 0 {
showGameOver(status: "lose")
}
}
func turnCheck() {
if movesLeft == 0 {
// Apply end of my turn status effects
if myStatusEffects.count > 0 {
self.healthCheck()
let statusEffect = myStatusEffects[0]
self.runStatus(statuses: myStatusEffects, status: statusEffect, target: myPokemon, count: 1) {
// Check health and end game if necessary
self.healthCheck()
// Set myTurn to false and switch to opponent's turn
self.myTurn = false
self.scene.animateSwitchTurns(myTurn: self.myTurn) {
self.AIMoves()
}
}
} else {
// Check health and end game if necessary
healthCheck()
// Set myTurn to false and switch to opponent's turn
self.myTurn = false
self.scene.animateSwitchTurns(myTurn: self.myTurn) {
self.AIMoves()
}
}
} else {
beginNextTurn()
}
}
func showGameOver(status: String) {
let endScene = storyboard?.instantiateViewController(withIdentifier: "BattleEndViewController") as! BattleEndViewController
if status == "win" {
endScene.coinsEarned = Int(opponentPokemon.stats["hp"]! * 3) - Int(myPokemon.stats["hp"]!) + 100
endScene.expEarned = Int(opponentPokemon.stats["hp"]! * 2)
endScene.battleSuccess = true
} else {
endScene.coinsEarned = 0
endScene.expEarned = 0
endScene.battleSuccess = false
}
self.present(endScene, animated: true) { }
//gameOverPanel.isHidden = false
//scene.isUserInteractionEnabled = false
// scene.animateGameOver() {
// self.tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideGameOver))
// self.view.addGestureRecognizer(self.tapGestureRecognizer)
// }
}
func hideGameOver() {
view.removeGestureRecognizer(tapGestureRecognizer)
tapGestureRecognizer = nil
gameOverPanel.isHidden = true
scene.isUserInteractionEnabled = true
let selectScene = storyboard?.instantiateViewController(withIdentifier: "BattleSelectViewController") as! BattleSelectViewController
self.present(selectScene, animated: true) { }
}
}
| apache-2.0 | ade063aca786427a48a421f90f67a8cf | 30.202222 | 136 | 0.627235 | 4.42097 | false | false | false | false |
inacioferrarini/York | Classes/ViewComponents/Input/TextFieldNavigationToolBar.swift | 1 | 6252 | // The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
open class TextFieldNavigationToolBar: NSObject {
// MARK: - Properties
open var previousButtonLabel: String? {
didSet {
guard let previousButton = self.previousButton else { return }
previousButton.title = previousButtonLabel
}
}
open var nextButtonLabel: String? {
didSet {
guard let nextButton = self.previousButton else { return }
nextButton.title = nextButtonLabel
}
}
open var doneButtonLabel: String? {
didSet {
guard let doneButton = self.previousButton else { return }
doneButton.title = doneButtonLabel
}
}
open var toolbar: UIToolbar?
open var textFields: [UITextField]? {
didSet {
self.updateAccessoryViews()
self.updateToolbar()
}
}
open var relatedFields: [UITextField : AnyObject]?
open var selectedTextField: UITextField? {
didSet {
self.updateToolbar()
}
}
fileprivate var previousButton: UIBarButtonItem?
fileprivate var nextButton: UIBarButtonItem?
fileprivate var doneButton: UIBarButtonItem?
// MARK: - Initialization
public required init(withTextFields textFields: [UITextField]?, usingRelatedFields relatedFields: [UITextField : AnyObject]?) {
self.textFields = textFields
self.relatedFields = relatedFields
super.init()
self.createToolbar()
}
// MARK: - Helper Methods
func createToolbar() {
if nil == self.toolbar {
let toolbar = UIToolbar()
toolbar.barStyle = .default
toolbar.sizeToFit()
self.toolbar = toolbar
}
guard let toolbar = self.toolbar else { return }
let flexibleSpaceLeft = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let previousButtonImage = UIImage(named: "LeftArrow", in: self.getBundle(), compatibleWith: nil)
let previousButton = UIBarButtonItem(image: previousButtonImage, style: .plain, target: self, action: #selector(previousButtonClicked))
self.previousButton = previousButton
let buttonSpacing = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
buttonSpacing.width = 12
let nextButtonImage = UIImage(named: "RightArrow", in: self.getBundle(), compatibleWith: nil)
let nextButton = UIBarButtonItem(image: nextButtonImage, style: .plain, target: self, action: #selector(nextButtonClicked))
self.nextButton = nextButton
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonClicked))
self.doneButton = doneButton
toolbar.items = [previousButton, buttonSpacing, nextButton, flexibleSpaceLeft, doneButton]
self.updateAccessoryViews()
self.updateToolbar()
}
func updateAccessoryViews() {
if let textFields = self.textFields {
for textField in textFields {
textField.inputAccessoryView = self.toolbar
}
// self.selectedTextField = textFields.first
}
}
func getBundle() -> Bundle {
return Bundle(for: TextFieldNavigationToolBar.self)
}
func indexOfSelectedTextField() -> NSInteger {
guard let selectedTextField = self.selectedTextField else { return 0 }
guard let textFields = self.textFields else { return 0 }
guard let selectedIndex = textFields.index(where: {$0 == selectedTextField}) else { return 0 }
return selectedIndex
}
func updateToolbar() {
guard let previousButton = self.previousButton else { return }
guard let nextButton = self.nextButton else { return }
guard let textFields = self.textFields else { return }
let selectedIndex = self.indexOfSelectedTextField()
previousButton.isEnabled = textFields.count > 0 && selectedIndex > 0
nextButton.isEnabled = textFields.count > 0 && selectedIndex < textFields.count - 1
}
func previousButtonClicked() {
guard let textFields = self.textFields else { return }
let selectedIndex = self.indexOfSelectedTextField()
if selectedIndex > 0 {
let selectedTextField = textFields[selectedIndex - 1]
self.selectedTextField = selectedTextField
selectedTextField.becomeFirstResponder()
}
}
func nextButtonClicked() {
guard let textFields = self.textFields else { return }
let selectedIndex = self.indexOfSelectedTextField()
if selectedIndex < textFields.count - 1 {
let selectedTextField = textFields[selectedIndex + 1]
self.selectedTextField = selectedTextField
selectedTextField.becomeFirstResponder()
}
}
func doneButtonClicked() {
guard let selectedTextField = self.selectedTextField else { return }
selectedTextField.resignFirstResponder()
}
}
| mit | 3ef7d5054d79561959590c00d0ea7189 | 36.431138 | 143 | 0.665334 | 5.200499 | false | false | false | false |
MainasuK/Bangumi-M | Percolator/Percolator/Rating.swift | 1 | 918 | //
// Rating.swift
// Percolator
//
// Created by Cirno MainasuK on 2016-7-12.
// Copyright © 2016年 Cirno MainasuK. All rights reserved.
//
import Foundation
import SwiftyJSON
// New item added to API in 2016 Summer
struct Rating {
let count: [String : Int]
let score: Double
let total: Int
init(json: [String : JSON]) {
var tempCount = [String : Int]()
if let countDict = json[BangumiKey.count]?.dictionaryValue {
for (index, subJSON) in countDict {
tempCount[index] = subJSON.intValue
}
}
count = tempCount
score = json[BangumiKey.score]?.doubleValue ?? 0.0
total = json[BangumiKey.total]?.intValue ?? 0
}
init(from cdRating: CDRating?) {
count = cdRating?.count as? [String : Int] ?? [:]
score = cdRating?.score ?? 0
total = Int(cdRating?.total ?? 0)
}
}
| mit | 9fb3f53f6b3a33aa4deb27bb908900db | 24.416667 | 68 | 0.580328 | 3.780992 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/Core/Operations/MMOperationQueue.swift | 1 | 1269 | //
// MMOperationQueue.swift
//
// Created by Andrey Kadochnikov on 16/02/2017.
//
//
import UIKit
class MMOperationQueue: OperationQueue, NamedLogger {
func addOperationExclusively(_ operation: Foundation.Operation) -> Bool {
guard operations.contains(where: { type(of: $0) == type(of: operation) && ($0.isFinished || $0.isCancelled) }) == false else
{
logDebug("\(type(of: operation)) was not queued because a queue is already taken with the same kind of operation.")
return false
}
addOperation(operation)
return true
}
override init() {
super.init()
self.name = self.queueName
}
init(name: String) {
super.init()
self.name = name
}
var queueName: String {
return "com.mobile-messaging.default-queue"
}
static func newSerialQueue(underlyingQueue: DispatchQueue?) -> MMOperationQueue {
let newQ = MMOperationQueue()
newQ.maxConcurrentOperationCount = 1
newQ.underlyingQueue = underlyingQueue
return newQ
}
static func userInitiatedQueue(underlyingQueue: DispatchQueue?) -> MMOperationQueue {
let newQ = MMOperationQueue()
newQ.qualityOfService = .userInitiated
newQ.maxConcurrentOperationCount = 1
newQ.underlyingQueue = underlyingQueue
return newQ
}
}
| apache-2.0 | 630ca201869560b74faaac1c95161cc2 | 24.897959 | 132 | 0.698976 | 3.965625 | false | false | false | false |
SweetzpotAS/TCXZpot-Swift | TCXZpot-Swift/Position.swift | 1 | 1421 | //
// Position.swift
// TCXZpot
//
// Created by Tomás Ruiz López on 22/5/17.
// Copyright 2017 SweetZpot AS
// 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
public struct Position {
fileprivate let latitude : Double
fileprivate let longitude : Double
public init?(latitude : Double, longitude : Double) {
guard latitude >= -90 && latitude <= 90 && longitude >= -180 && longitude <= 180 else {
return nil
}
self.latitude = latitude
self.longitude = longitude
}
}
extension Position : TCXSerializable {
public func serialize(to serializer: Serializer) {
serializer.print(line: "<Position>")
serializer.print(line: "<LatitudeDegrees>\(latitude)</LatitudeDegrees>")
serializer.print(line: "<LongitudeDegrees>\(longitude)</LongitudeDegrees>")
serializer.print(line: "</Position>")
}
}
| apache-2.0 | cbc8e490e82938b3f1df74700e668393 | 32.785714 | 95 | 0.68358 | 4.352761 | false | false | false | false |
PeteShearer/SwiftNinja | 030-Unwinding Segues/MasterDetail/MasterDetail/EpisodeRepository.swift | 4 | 4235 | //
// EpisodeRepository.swift
// MasterDetail
//
// Created by Peter Shearer on 12/12/16.
// Copyright © 2016 Peter Shearer. All rights reserved.
//
class EpisodeRepository {
class func getEpisodeList() -> [Episode] {
var episodes = [Episode]()
let girl = Episode(
episodeTitle: "The Girl in the Fireplace",
writerName: "Steven Moffat",
doctorName: "10th Doctor, David Tennant",
episodeNumber: "Series 2 Episode 4",
synopsis: "For their first trip with Mickey, the Tenth Doctor and Rose end up on a space ship in the future that contains several portals to pre-Revolutionary France. When he steps through one of these portals, shaped like a fireplace, the Doctor discovers the even greater mystery of actual, romantic love.")
episodes.append(girl)
let vince = Episode(
episodeTitle: "Vincent and the Doctor",
writerName: "Richard Curtis",
doctorName: "11th Doctor, Matt Smith",
episodeNumber: "Series 5 Episode 10",
synopsis: "While taking Amy to several peaceful locations, the Eleventh Doctor's trip to a museum takes turn for the worse: his interest is caught by a painting of a church by Vincent van Gogh. What troubles the Doctor is that there's a face in the church's window; it's not a nice face, it's a curious, shadowed, creepy face with a beak and nasty eyes. The Doctor knows evil when he sees it and this face is definitely evil; it may pose a threat to the one who painted this face into the church. Only one thing will calm the Doctor's nerves: a trip in the TARDIS to 1890 so the Doctor can find out from the artist himself.")
episodes.append(vince)
let dalek = Episode(
episodeTitle: "Dalek",
writerName: "Robert Shearman",
doctorName: "9th Doctor, Christopher Eccleston",
episodeNumber: "Series 1 Episode 6",
synopsis: "The Ninth Doctor and Rose Tyler arrive in 2012 to answer a distress signal and meet a collector of alien artefacts who has one living specimen. However, the Doctor is horrified to find out that the creature is a member of a race he thought was destroyed: a Dalek.")
episodes.append(dalek)
let midnight = Episode(
episodeTitle: "Midnight",
writerName: "Russell T Davies",
doctorName: "10th Doctor, David Tennant",
episodeNumber: "Series 4 Episode 10",
synopsis: "The Tenth Doctor and Donna Noble go to the leisure planet of Midnight for a simple, relaxing vacation. However, life with the Doctor can never be that simple, and things go horribly wrong for the Doctor when he decides to go off on a bus trip to see the Sapphire Waterfall, starting with the bus shutting down. When a mysterious entity infiltrates the shuttle bus, no one is to be trusted. Not even the Doctor himself...")
episodes.append(midnight)
let blink = Episode(
episodeTitle: "Blink",
writerName: "Steven Moffat",
doctorName: "10th Doctor, David Tennant",
episodeNumber: "Series 3 Episode 10",
synopsis: "In an abandoned house, the Weeping Angels wait. The only hope to stop them is a young woman named Sally Sparrow and her friend Larry Nightingale. The only catch: The Weeping Angels can move in the blink of an eye. To defeat the ruthless enemy — with only a half of a conversation from the Tenth Doctor as help — the one rule is this: don't turn your back, don't look away and don't blink!")
episodes.append(blink)
let wife = Episode(
episodeTitle: "The Doctor's Wife",
writerName: "Neil Gaiman",
doctorName: "11th Doctor, Matt Smith",
episodeNumber: "Series 6 Episode 4",
synopsis: "The Eleventh Doctor receives a message from an old Time Lord friend. The message brings him, Rory Williams and Amy Pond to another universe where they meet an alien who eats TARDISes.")
episodes.append(wife)
return episodes
}
}
| bsd-2-clause | 1eda5f22cfb364a053271935c800ebac | 59.428571 | 637 | 0.661702 | 4.378882 | false | false | false | false |
ahoppen/swift | test/SILGen/switch.swift | 5 | 53327 | // RUN: %target-swift-emit-silgen -module-name switch %s | %FileCheck %s
//////////////////
// Declarations //
//////////////////
func markUsed<T>(_ t: T) {}
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
func a(_ k: Klass) {}
func b(_ k: Klass) {}
func c(_ k: Klass) {}
func d(_ k: Klass) {}
func e(_ k: Klass) {}
func f(_ k: Klass) {}
func g(_ k: Klass) {}
class Klass {
var isTrue: Bool { return true }
var isFalse: Bool { return false }
}
enum TrivialSingleCaseEnum {
case a
}
enum NonTrivialSingleCaseEnum {
case a(Klass)
}
enum MultipleNonTrivialCaseEnum {
case a(Klass)
case b(Klass)
case c(Klass)
}
enum MultipleAddressOnlyCaseEnum<T : BinaryInteger> {
case a(T)
case b(T)
case c(T)
}
///////////
// Tests //
///////////
// CHECK-LABEL: sil hidden [ossa] @$s6switch5test1yyF
func test1() {
switch foo() {
// CHECK: function_ref @$s6switch3fooSiyF
case _:
// CHECK: function_ref @$s6switch1ayyF
a()
}
// CHECK: function_ref @$s6switch1byyF
b()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch5test2yyF
func test2() {
switch foo() {
// CHECK: function_ref @$s6switch3fooSiyF
case _:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
case _: // The second case is unreachable.
b()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1cyyF
c()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch5test3yyF
func test3() {
switch foo() {
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: function_ref @$s6switch6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[CASE2:bb[0-9]+]]
case _ where runced():
// CHECK: [[CASE1]]:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
case _:
// CHECK: [[CASE2]]:
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1cyyF
c()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch5test4yyF
func test4() {
switch (foo(), bar()) {
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: function_ref @$s6switch3barSiyF
case _:
// CHECK: function_ref @$s6switch1ayyF
a()
}
// CHECK: function_ref @$s6switch1byyF
b()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch5test5yyF
func test5() {
switch (foo(), bar()) {
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: function_ref @$s6switch3barSiyF
// CHECK: function_ref @$s6switch6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
case _ where runced():
// CHECK: [[CASE1]]:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NOT_CASE1]]:
// CHECK: function_ref @$s6switch6fungedSbyF
// CHECK: cond_br {{%.*}}, [[YES_CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]]
// CHECK: [[YES_CASE2]]:
case (_, _) where funged():
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
case _:
// CHECK: [[NOT_CASE2]]:
// CHECK: function_ref @$s6switch1cyyF
c()
}
// CHECK: function_ref @$s6switch1dyyF
d()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch5test6yyF
func test6() {
switch (foo(), bar()) {
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: function_ref @$s6switch3barSiyF
case (_, _):
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
case (_, _): // The second case is unreachable.
b()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1cyyF
c()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch5test7yyF
func test7() {
switch (foo(), bar()) {
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: function_ref @$s6switch3barSiyF
// CHECK: function_ref @$s6switch6runcedSbyF
// CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
// CHECK: [[YES_CASE1]]:
case (_, _) where runced():
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
case (_, _):
// CHECK: [[NOT_CASE1]]:
// CHECK: function_ref @$s6switch1byyF
b()
}
c()
// CHECK: function_ref @$s6switch1cyyF
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch5test8yyF
func test8() {
switch (foo(), bar()) {
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: function_ref @$s6switch3barSiyF
// CHECK: function_ref @$s6switch6foobarSi_SityF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
case foobar():
// CHECK: [[CASE1]]:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NOT_CASE1]]:
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]]
case (foo(), _):
// CHECK: [[CASE2]]:
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
// CHECK: [[NOT_CASE2]]:
// CHECK: function_ref @$s6switch3barSiyF
// CHECK: cond_br {{%.*}}, [[CASE3_GUARD:bb[0-9]+]], [[NOT_CASE3:bb[0-9]+]]
// CHECK: [[CASE3_GUARD]]:
// CHECK: function_ref @$s6switch6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NOT_CASE3_GUARD:bb[0-9]+]]
case (_, bar()) where runced():
// CHECK: [[CASE3]]:
// CHECK: function_ref @$s6switch1cyyF
// CHECK: br [[CONT]]
c()
// CHECK: [[NOT_CASE3_GUARD]]:
// CHECK: [[NOT_CASE3]]:
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: cond_br {{%.*}}, [[CASE4_GUARD_1:bb[0-9]+]], [[NOT_CASE4_1:bb[0-9]+]]
// CHECK: [[CASE4_GUARD_1]]:
// CHECK: function_ref @$s6switch3barSiyF
// CHECK: cond_br {{%.*}}, [[CASE4_GUARD_2:bb[0-9]+]], [[NOT_CASE4_2:bb[0-9]+]]
// CHECK: [[CASE4_GUARD_2]]:
// CHECK: function_ref @$s6switch6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE4:bb[0-9]+]], [[NOT_CASE4_3:bb[0-9]+]]
case (foo(), bar()) where funged():
// CHECK: [[CASE4]]:
// CHECK: function_ref @$s6switch1dyyF
// CHECK: br [[CONT]]
d()
// CHECK: [[NOT_CASE4_3]]:
// CHECK: [[NOT_CASE4_2]]:
// CHECK: [[NOT_CASE4_1]]:
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: cond_br {{%.*}}, [[CASE5_GUARD_1:bb[0-9]+]], [[NOT_CASE5:bb[0-9]+]]
// CHECK: [[CASE5_GUARD_1]]:
// CHECK: function_ref @$s6switch3barSiyF
// CHECK: cond_br {{%.*}}, [[YES_CASE5:bb[0-9]+]], [[NOT_CASE5:bb[0-9]+]]
// CHECK: [[YES_CASE5]]:
case (foo(), bar()):
// CHECK: function_ref @$s6switch1eyyF
// CHECK: br [[CONT]]
e()
// CHECK: [[NOT_CASE5]]:
// CHECK: br [[CASE6:bb[0-9]+]]
case _:
// CHECK: [[CASE6]]:
// CHECK: function_ref @$s6switch1fyyF
// CHECK: br [[CONT]]
f()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1gyyF
g()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch5test9yyF
func test9() {
switch (foo(), bar()) {
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: function_ref @$s6switch3barSiyF
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
// CHECK: [[YES_CASE1]]:
case (foo(), _):
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NOT_CASE1]]:
// CHECK: function_ref @$s6switch6foobarSi_SityF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]]
case foobar():
// CHECK: [[CASE2]]:
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
case _:
// CHECK: [[NOT_CASE2]]:
// CHECK: function_ref @$s6switch1cyyF
c()
}
// CHECK: function_ref @$s6switch1dyyF
d()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch6test10yyF
func test10() {
switch (foo(), bar()) {
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: function_ref @$s6switch3barSiyF
// CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
// CHECK: [[YES_CASE1]]:
case (foo()...bar(), _):
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
case _:
// CHECK: [[NOT_CASE1]]:
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1cyyF
c()
}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// CHECK-LABEL: sil hidden [ossa] @$s6switch10test_isa_11pyAA1P_p_tF
func test_isa_1(p: P) {
// CHECK: [[PTMPBUF:%[0-9]+]] = alloc_stack $P
// CHECK-NEXT: copy_addr %0 to [initialization] [[PTMPBUF]] : $*P
switch p {
// CHECK: [[TMPBUF:%[0-9]+]] = alloc_stack $X
// CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in [[TMPBUF]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
case is X:
// CHECK: [[IS_X]]:
// CHECK-NEXT: load [trivial] [[TMPBUF]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FUNC:%.*]] = function_ref @$s6switch1ayyF
// CHECK-NEXT: apply [[FUNC]]()
// CHECK-NEXT: dealloc_stack [[TMPBUF]]
// CHECK-NEXT: destroy_addr [[PTMPBUF]]
// CHECK-NEXT: dealloc_stack [[PTMPBUF]]
a()
// CHECK: br [[CONT:bb[0-9]+]]
// CHECK: [[IS_NOT_X]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
case is Y:
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[Y_CONT:bb[0-9]+]]
b()
// CHECK: [[IS_NOT_Y]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Z in {{%.*}} : $*Z, [[IS_Z:bb[0-9]+]], [[IS_NOT_Z:bb[0-9]+]]
// CHECK: [[IS_Z]]:
case is Z:
// CHECK: function_ref @$s6switch1cyyF
// CHECK: br [[Z_CONT:bb[0-9]+]]
c()
// CHECK: [[IS_NOT_Z]]:
case _:
// CHECK: function_ref @$s6switch1dyyF
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1eyyF
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch10test_isa_21pyAA1P_p_tF
func test_isa_2(p: P) {
switch (p, foo()) {
// CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in {{%.*}} : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
// CHECK: [[IS_X]]:
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]]
case (is X, foo()):
// CHECK: [[CASE1]]:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_NOT_X]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: function_ref @$s6switch3fooSiyF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]]
case (is Y, foo()):
// CHECK: [[CASE2]]:
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
// CHECK: [[NOT_CASE2]]:
// CHECK: [[IS_NOT_Y]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in {{%.*}} : $*X, [[CASE3:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
case (is X, _):
// CHECK: [[CASE3]]:
// CHECK: function_ref @$s6switch1cyyF
// CHECK: br [[CONT]]
c()
// -- case (is Y, foo()):
// CHECK: [[IS_NOT_X]]:
// CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: function_ref @$s6switch3barSiyF
// CHECK: cond_br {{%.*}}, [[CASE4:bb[0-9]+]], [[NOT_CASE4:bb[0-9]+]]
case (is Y, bar()):
// CHECK: [[CASE4]]:
// CHECK: function_ref @$s6switch1dyyF
// CHECK: br [[CONT]]
d()
// CHECK: [[NOT_CASE4]]:
// CHECK: br [[CASE5:bb[0-9]+]]
// CHECK: [[IS_NOT_Y]]:
// CHECK: br [[CASE5]]
case _:
// CHECK: [[CASE5]]:
// CHECK: function_ref @$s6switch1eyyF
// CHECK: br [[CONT]]
e()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1fyyF
f()
}
class B {}
class C : B {}
class D1 : C {}
class D2 : D1 {}
class E : C {}
// CHECK-LABEL: sil hidden [ossa] @$s6switch16test_isa_class_11xyAA1BC_tF : $@convention(thin) (@guaranteed B) -> () {
func test_isa_class_1(x: B) {
// CHECK: bb0([[X:%.*]] : @guaranteed $B):
// CHECK: checked_cast_br [[X]] : $B to D1, [[IS_D1:bb[0-9]+]], [[IS_NOT_D1:bb[0-9]+]]
switch x {
// CHECK: [[IS_D1]]([[CAST_D1:%.*]] : @guaranteed $D1):
// CHECK: [[CAST_D1_COPY:%.*]] = copy_value [[CAST_D1]]
// CHECK: function_ref @$s6switch6runcedSbyF : $@convention(thin) () -> Bool
// CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// CHECK: [[YES_CASE1]]:
case is D1 where runced():
// CHECK: function_ref @$s6switch1ayyF
// CHECK: destroy_value [[CAST_D1_COPY]]
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE1]]:
// CHECK-NEXT: destroy_value [[CAST_D1_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[IS_NOT_D1]]([[CASTFAIL_D1:%.*]] : @guaranteed $B):
// CHECK-NEXT: br [[NEXT_CASE]]
// CHECK: [[NEXT_CASE]]:
// CHECK: checked_cast_br [[X]] : $B to D2, [[IS_D2:bb[0-9]+]], [[IS_NOT_D2:bb[0-9]+]]
case is D2:
// CHECK: [[IS_D2]]([[CAST_D2:%.*]] : @guaranteed $D2):
// CHECK: [[CAST_D2_COPY:%.*]] = copy_value [[CAST_D2]]
// CHECK: function_ref @$s6switch1byyF
// CHECK: destroy_value [[CAST_D2_COPY]]
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_NOT_D2]]([[CASTFAIL_D2:%.*]] : @guaranteed $B):
// CHECK: checked_cast_br [[X]] : $B to E, [[IS_E:bb[0-9]+]], [[IS_NOT_E:bb[0-9]+]]
case is E where funged():
// CHECK: [[IS_E]]([[CAST_E:%.*]] : @guaranteed $E):
// CHECK: [[CAST_E_COPY:%.*]] = copy_value [[CAST_E]]
// CHECK: function_ref @$s6switch6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// CHECK: [[CASE3]]:
// CHECK: function_ref @$s6switch1cyyF
// CHECK: destroy_value [[CAST_E_COPY]]
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK-NEXT: destroy_value [[CAST_E_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[IS_NOT_E]]([[NOTCAST_E:%.*]] : @guaranteed $B):
// CHECK: br [[NEXT_CASE]]
// CHECK: [[NEXT_CASE]]:
// CHECK: checked_cast_br [[X]] : $B to C, [[IS_C:bb[0-9]+]], [[IS_NOT_C:bb[0-9]+]]
case is C:
// CHECK: [[IS_C]]([[CAST_C:%.*]] : @guaranteed $C):
// CHECK: [[CAST_C_COPY:%.*]] = copy_value [[CAST_C]]
// CHECK: function_ref @$s6switch1dyyF
// CHECK-NEXT: apply
// CHECK: destroy_value [[CAST_C_COPY]]
// CHECK: br [[CONT]]
d()
// CHECK: [[IS_NOT_C]]([[NOCAST_C:%.*]] : @guaranteed $B):
default:
// CHECK: function_ref @$s6switch1eyyF
// CHECK: br [[CONT]]
e()
}
// CHECK: [[CONT]]:
// CHECK: [[F_FUNC:%.*]] = function_ref @$s6switch1fyyF : $@convention(thin) () -> ()
// CHECK: apply [[F_FUNC]]()
f()
}
// CHECK: } // end sil function '$s6switch16test_isa_class_11xyAA1BC_tF'
// CHECK-LABEL: sil hidden [ossa] @$s6switch16test_isa_class_21xyXlAA1BC_tF : $@convention(thin)
func test_isa_class_2(x: B) -> AnyObject {
// CHECK: bb0([[X:%.*]] : @guaranteed $B):
switch x {
// CHECK: checked_cast_br [[X]] : $B to D1, [[IS_D1:bb[0-9]+]], [[IS_NOT_D1:bb[0-9]+]]
case let y as D1 where runced():
// CHECK: [[IS_D1]]([[CAST_D1:%.*]] : @guaranteed $D1):
// CHECK: [[CAST_D1_COPY:%.*]] = copy_value [[CAST_D1]]
// CHECK: [[BORROWED_CAST_D1_COPY:%.*]] = begin_borrow [lexical] [[CAST_D1_COPY]]
// CHECK: function_ref @$s6switch6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// CHECK: [[CASE1]]:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: [[CAST_D1_COPY_COPY:%.*]] = copy_value [[BORROWED_CAST_D1_COPY]]
// CHECK: [[RET:%.*]] = init_existential_ref [[CAST_D1_COPY_COPY]]
// CHECK: end_borrow [[BORROWED_CAST_D1_COPY]]
// CHECK: destroy_value [[CAST_D1_COPY]]
// CHECK: br [[CONT:bb[0-9]+]]([[RET]] : $AnyObject)
a()
return y
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[CAST_D1_COPY]]
// CHECK: br [[NEXT_CASE:bb5]]
// CHECK: [[IS_NOT_D1]]([[NOCAST_D1:%.*]] : @guaranteed $B):
// CHECK: br [[NEXT_CASE]]
// CHECK: [[NEXT_CASE]]:
// CHECK: checked_cast_br [[X]] : $B to D2, [[CASE2:bb[0-9]+]], [[IS_NOT_D2:bb[0-9]+]]
case let y as D2:
// CHECK: [[CASE2]]([[CAST_D2:%.*]] : @guaranteed $D2):
// CHECK: [[CAST_D2_COPY:%.*]] = copy_value [[CAST_D2]]
// CHECK: [[BORROWED_CAST_D2_COPY:%.*]] = begin_borrow [lexical] [[CAST_D2_COPY]]
// CHECK: function_ref @$s6switch1byyF
// CHECK: [[CAST_D2_COPY_COPY:%.*]] = copy_value [[BORROWED_CAST_D2_COPY]]
// CHECK: [[RET:%.*]] = init_existential_ref [[CAST_D2_COPY_COPY]]
// CHECK: end_borrow [[BORROWED_CAST_D2_COPY]]
// CHECK: destroy_value [[CAST_D2_COPY]]
// CHECK: br [[CONT]]([[RET]] : $AnyObject)
b()
return y
// CHECK: [[IS_NOT_D2]]([[NOCAST_D2:%.*]] : @guaranteed $B):
// CHECK: checked_cast_br [[X]] : $B to E, [[IS_E:bb[0-9]+]], [[IS_NOT_E:bb[0-9]+]]
case let y as E where funged():
// CHECK: [[IS_E]]([[CAST_E:%.*]] : @guaranteed $E):
// CHECK: [[CAST_E_COPY:%.*]] = copy_value [[CAST_E]]
// CHECK: [[BORROWED_CAST_E_COPY:%.*]] = begin_borrow [lexical] [[CAST_E_COPY]]
// CHECK: function_ref @$s6switch6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// CHECK: [[CASE3]]:
// CHECK: function_ref @$s6switch1cyyF
// CHECK: [[CAST_E_COPY_COPY:%.*]] = copy_value [[BORROWED_CAST_E_COPY]]
// CHECK: [[RET:%.*]] = init_existential_ref [[CAST_E_COPY_COPY]]
// CHECK: end_borrow [[BORROWED_CAST_E_COPY]]
// CHECK: destroy_value [[CAST_E_COPY]]
// CHECK: br [[CONT]]([[RET]] : $AnyObject)
c()
return y
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[CAST_E_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[IS_NOT_E]]([[NOCAST_E:%.*]] : @guaranteed $B):
// CHECK: br [[NEXT_CASE]]
// CHECK: [[NEXT_CASE]]
// CHECK: checked_cast_br [[X]] : $B to C, [[CASE4:bb[0-9]+]], [[IS_NOT_C:bb[0-9]+]]
case let y as C:
// CHECK: [[CASE4]]([[CAST_C:%.*]] : @guaranteed $C):
// CHECK: [[CAST_C_COPY:%.*]] = copy_value [[CAST_C]]
// CHECK: [[BORROWED_CAST_C_COPY:%.*]] = begin_borrow [lexical] [[CAST_C_COPY]]
// CHECK: function_ref @$s6switch1dyyF
// CHECK: [[CAST_C_COPY_COPY:%.*]] = copy_value [[BORROWED_CAST_C_COPY]]
// CHECK: [[RET:%.*]] = init_existential_ref [[CAST_C_COPY_COPY]]
// CHECK: end_borrow [[BORROWED_CAST_C_COPY]]
// CHECK: destroy_value [[CAST_C_COPY]]
// CHECK: br [[CONT]]([[RET]] : $AnyObject)
d()
return y
// CHECK: [[IS_NOT_C]]([[NOCAST_C:%.*]] : @guaranteed $B):
default:
// CHECK: function_ref @$s6switch1eyyF
// CHECK: [[X_COPY_2:%.*]] = copy_value [[X]]
// CHECK: [[RET:%.*]] = init_existential_ref [[X_COPY_2]]
// CHECK: br [[CONT]]([[RET]] : $AnyObject)
e()
return x
}
// CHECK: [[CONT]]([[T0:%.*]] : @owned $AnyObject):
// CHECK: return [[T0]]
}
// CHECK: } // end sil function '$s6switch16test_isa_class_21xyXlAA1BC_tF'
enum MaybePair {
case Neither
case Left(Int)
case Right(String)
case Both(Int, String)
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch12test_union_11uyAA9MaybePairO_tF
func test_union_1(u: MaybePair) {
switch u {
// CHECK: switch_enum [[SUBJECT:%.*]] : $MaybePair,
// CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybePair.Left!enumelt: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybePair.Right!enumelt: [[IS_RIGHT:bb[0-9]+]],
// CHECK: case #MaybePair.Both!enumelt: [[IS_BOTH:bb[0-9]+]]
// CHECK: [[IS_NEITHER]]:
// CHECK-NOT: destroy_value
case .Neither:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]({{%.*}}):
// CHECK-NOT: destroy_value
case (.Left):
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]([[STR:%.*]] : @guaranteed $String):
case var .Right:
// CHECK: function_ref @$s6switch1cyyF
// CHECK: br [[CONT]]
c()
// CHECK: [[IS_BOTH]]([[TUP:%.*]] : @guaranteed $(Int, String)):
case .Both:
// CHECK: ({{%.*}}, [[TUP_STR:%.*]]) = destructure_tuple [[TUP]]
// CHECK: function_ref @$s6switch1dyyF
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK-NOT: switch_enum [[SUBJECT]]
// CHECK: function_ref @$s6switch1eyyF
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch12test_union_31uyAA9MaybePairO_tF : $@convention(thin) (@guaranteed MaybePair) -> () {
func test_union_3(u: MaybePair) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $MaybePair):
// CHECK: switch_enum [[ARG]] : $MaybePair,
// CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybePair.Left!enumelt: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybePair.Right!enumelt: [[IS_RIGHT:bb[0-9]+]],
// CHECK: default [[DEFAULT:bb[0-9]+]]
switch u {
// CHECK: [[IS_NEITHER]]:
case .Neither:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]({{%.*}}):
case .Left:
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]([[STR:%.*]] : @guaranteed $String):
case .Right:
// CHECK: function_ref @$s6switch1cyyF
// CHECK: br [[CONT]]
c()
// CHECK: [[DEFAULT]](
// -- Ensure the fully-opaque value is destroyed in the default case.
// CHECK: function_ref @$s6switch1dyyF
// CHECK: br [[CONT]]
default:
d()
}
// CHECK: [[CONT]]:
// CHECK-NOT: switch_enum [[ARG]]
// CHECK: function_ref @$s6switch1eyyF
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch12test_union_41uyAA9MaybePairO_tF
func test_union_4(u: MaybePair) {
switch u {
// CHECK: switch_enum {{%.*}} : $MaybePair,
// CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybePair.Left!enumelt: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybePair.Right!enumelt: [[IS_RIGHT:bb[0-9]+]],
// CHECK: case #MaybePair.Both!enumelt: [[IS_BOTH:bb[0-9]+]]
// CHECK: [[IS_NEITHER]]:
case .Neither:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]({{%.*}}):
case .Left(_):
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]({{%.*}}):
case .Right(_):
// CHECK: function_ref @$s6switch1cyyF
// CHECK: br [[CONT]]
c()
// CHECK: [[IS_BOTH]]({{%.*}}):
case .Both(_):
// CHECK: function_ref @$s6switch1dyyF
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1eyyF
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch12test_union_51uyAA9MaybePairO_tF
func test_union_5(u: MaybePair) {
switch u {
// CHECK: switch_enum {{%.*}} : $MaybePair,
// CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybePair.Left!enumelt: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybePair.Right!enumelt: [[IS_RIGHT:bb[0-9]+]],
// CHECK: case #MaybePair.Both!enumelt: [[IS_BOTH:bb[0-9]+]]
// CHECK: [[IS_NEITHER]]:
case .Neither:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]({{%.*}}):
case .Left(_):
// CHECK: function_ref @$s6switch1byyF
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]({{%.*}}):
case .Right(_):
// CHECK: function_ref @$s6switch1cyyF
// CHECK: br [[CONT]]
c()
// CHECK: [[IS_BOTH]]({{%.*}}):
case .Both(_, _):
// CHECK: function_ref @$s6switch1dyyF
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1eyyF
e()
}
enum MaybeAddressOnlyPair {
case Neither
case Left(P)
case Right(String)
case Both(P, String)
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch22test_union_addr_only_11uyAA20MaybeAddressOnlyPairO_tF
func test_union_addr_only_1(u: MaybeAddressOnlyPair) {
switch u {
// CHECK: switch_enum_addr [[ENUM_ADDR:%.*]] : $*MaybeAddressOnlyPair,
// CHECK: case #MaybeAddressOnlyPair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]],
// CHECK: case #MaybeAddressOnlyPair.Left!enumelt: [[IS_LEFT:bb[0-9]+]],
// CHECK: case #MaybeAddressOnlyPair.Right!enumelt: [[IS_RIGHT:bb[0-9]+]],
// CHECK: case #MaybeAddressOnlyPair.Both!enumelt: [[IS_BOTH:bb[0-9]+]]
// CHECK: [[IS_NEITHER]]:
case .Neither:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[IS_LEFT]]:
// CHECK: [[P:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Left!enumelt
case .Left(_):
// CHECK: [[FUNC:%.*]] = function_ref @$s6switch1byyF
// CHECK-NEXT: apply [[FUNC]](
// CHECK: destroy_addr [[P]]
// CHECK: br [[CONT]]
b()
// CHECK: [[IS_RIGHT]]:
// CHECK: [[STR_ADDR:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Right!enumelt
// CHECK: [[STR:%.*]] = load [take] [[STR_ADDR]]
case .Right(_):
// CHECK: [[FUNC:%.*]] = function_ref @$s6switch1cyyF
// CHECK: apply [[FUNC]](
// CHECK: destroy_value [[STR]] : $String
// CHECK: br [[CONT]]
c()
// CHECK: [[IS_BOTH]]:
// CHECK: [[P_STR_TUPLE:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Both!enumelt
case .Both(_):
// CHECK: [[FUNC:%.*]] = function_ref @$s6switch1dyyF
// CHECK-NEXT: apply [[FUNC]](
// CHECK: destroy_addr [[P_STR_TUPLE]]
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s6switch1eyyF
e()
}
enum Generic<T, U> {
case Foo(T)
case Bar(U)
}
// Check that switching over a generic instance generates verified SIL.
func test_union_generic_instance(u: Generic<Int, String>) {
switch u {
case .Foo(var x):
a()
case .Bar(var y):
b()
}
c()
}
enum Foo { case A, B }
// CHECK-LABEL: sil hidden [ossa] @$s6switch05test_A11_two_unions1x1yyAA3FooO_AFtF
func test_switch_two_unions(x: Foo, y: Foo) {
// CHECK: [[T0:%.*]] = tuple (%0 : $Foo, %1 : $Foo)
// CHECK: ([[X:%.*]], [[Y:%.*]]) = destructure_tuple [[T0]]
// CHECK: switch_enum [[Y]] : $Foo, case #Foo.A!enumelt: [[IS_CASE1:bb[0-9]+]], default [[IS_NOT_CASE1:bb[0-9]+]]
switch (x, y) {
// CHECK: [[IS_CASE1]]:
case (_, Foo.A):
// CHECK: function_ref @$s6switch1ayyF
a()
// CHECK: [[IS_NOT_CASE1]]:
// CHECK: switch_enum [[X]] : $Foo, case #Foo.B!enumelt: [[IS_CASE2:bb[0-9]+]], default [[IS_NOT_CASE2:bb[0-9]+]]
// CHECK: [[IS_CASE2]]:
case (Foo.B, _):
// CHECK: function_ref @$s6switch1byyF
b()
// CHECK: [[IS_NOT_CASE2]]:
// CHECK: switch_enum [[Y]] : $Foo, case #Foo.B!enumelt: [[IS_CASE3:bb[0-9]+]], default [[UNREACHABLE:bb[0-9]+]]
// CHECK: [[IS_CASE3]]:
case (_, Foo.B):
// CHECK: function_ref @$s6switch1cyyF
c()
// CHECK: [[UNREACHABLE]]:
// CHECK: unreachable
}
}
// <rdar://problem/14826416>
func rdar14826416<T, U>(t: T, u: U) {
switch t {
case is Int: markUsed("Int")
case is U: markUsed("U")
case _: markUsed("other")
}
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch12rdar14826416{{[_0-9a-zA-Z]*}}F
// CHECK: checked_cast_addr_br copy_on_success T in {{%.*}} : $*T to Int in {{%.*}} : $*Int, [[IS_INT:bb[0-9]+]], [[ISNT_INT:bb[0-9]+]]
// CHECK: [[ISNT_INT]]:
// CHECK: checked_cast_addr_br copy_on_success T in {{%.*}} : $*T to U in {{%.*}} : $*U, [[ISNT_INT_IS_U:bb[0-9]+]], [[ISNT_INT_ISNT_U:bb[0-9]+]]
// <rdar://problem/14835992>
class Rdar14835992 {}
class SubRdar14835992 : Rdar14835992 {}
// CHECK-LABEL: sil hidden [ossa] @$s6switch12rdar14835992{{[_0-9a-zA-Z]*}}F
func rdar14835992<T, U>(t: Rdar14835992, tt: T, uu: U) {
switch t {
case is SubRdar14835992: markUsed("Sub")
case is T: markUsed("T")
case is U: markUsed("U")
case _: markUsed("other")
}
}
// <rdar://problem/17272985>
enum ABC { case A, B, C }
// CHECK-LABEL: sil hidden [ossa] @$s6switch18testTupleWildcardsyyAA3ABCO_ADtF
// CHECK: ([[X:%.*]], [[Y:%.*]]) = destructure_tuple {{%.*}} : $(ABC, ABC)
// CHECK: switch_enum [[X]] : $ABC, case #ABC.A!enumelt: [[X_A:bb[0-9]+]], default [[X_NOT_A:bb[0-9]+]]
// CHECK: [[X_A]]:
// CHECK: function_ref @$s6switch1ayyF
// CHECK: [[X_NOT_A]](
// CHECK: switch_enum [[Y]] : $ABC, case #ABC.A!enumelt: [[Y_A:bb[0-9]+]], case #ABC.B!enumelt: [[Y_B:bb[0-9]+]], case #ABC.C!enumelt: [[Y_C:bb[0-9]+]]
// CHECK-NOT: default
// CHECK: [[Y_A]]:
// CHECK: function_ref @$s6switch1byyF
// CHECK: [[Y_B]]:
// CHECK: function_ref @$s6switch1cyyF
// CHECK: [[Y_C]]:
// CHECK: switch_enum [[X]] : $ABC, case #ABC.C!enumelt: [[X_C:bb[0-9]+]], default [[X_NOT_C:bb[0-9]+]]
// CHECK: [[X_C]]:
// CHECK: function_ref @$s6switch1dyyF
// CHECK: [[X_NOT_C]](
// CHECK: function_ref @$s6switch1eyyF
func testTupleWildcards(_ x: ABC, _ y: ABC) {
switch (x, y) {
case (.A, _):
a()
case (_, .A):
b()
case (_, .B):
c()
case (.C, .C):
d()
default:
e()
}
}
enum LabeledScalarPayload {
case Payload(name: Int)
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch24testLabeledScalarPayloadyypAA0cdE0OF
func testLabeledScalarPayload(_ lsp: LabeledScalarPayload) -> Any {
// CHECK: switch_enum {{%.*}}, case #LabeledScalarPayload.Payload!enumelt: bb1
switch lsp {
// CHECK: bb1([[TUPLE:%.*]] : $(name: Int)):
// CHECK: [[X:%.*]] = destructure_tuple [[TUPLE]]
// CHECK: [[ANY_X_ADDR:%.*]] = init_existential_addr {{%.*}}, $Int
// CHECK: store [[X]] to [trivial] [[ANY_X_ADDR]]
case let .Payload(x):
return x
}
}
// There should be no unreachable generated.
// CHECK-LABEL: sil hidden [ossa] @$s6switch19testOptionalPatternyySiSgF
func testOptionalPattern(_ value : Int?) {
// CHECK: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt: bb1, case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
switch value {
case 1?: a()
case 2?: b()
case nil: d()
default: e()
}
}
// x? and .none should both be considered "similar" and thus handled in the same
// switch on the enum kind. There should be no unreachable generated.
// CHECK-LABEL: sil hidden [ossa] @$s6switch19testOptionalEnumMixyS2iSgF
func testOptionalEnumMix(_ a : Int?) -> Int {
// CHECK: debug_value %0 : $Optional<Int>, let, name "a"
// CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
switch a {
case let x?:
return 0
// CHECK: [[SOMEBB]]([[X:%.*]] : $Int):
// CHECK-NEXT: debug_value [[X]] : $Int, let, name "x"
// CHECK: integer_literal $Builtin.IntLiteral, 0
case .none:
return 42
// CHECK: [[NILBB]]:
// CHECK: integer_literal $Builtin.IntLiteral, 42
}
}
// x? and nil should both be considered "similar" and thus handled in the same
// switch on the enum kind. There should be no unreachable generated.
// CHECK-LABEL: sil hidden [ossa] @$s6switch26testOptionalEnumMixWithNilyS2iSgF
func testOptionalEnumMixWithNil(_ a : Int?) -> Int {
// CHECK: debug_value %0 : $Optional<Int>, let, name "a"
// CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]]
switch a {
case let x?:
return 0
// CHECK: [[SOMEBB]]([[X:%.*]] : $Int):
// CHECK-NEXT: debug_value [[X]] : $Int, let, name "x"
// CHECK: integer_literal $Builtin.IntLiteral, 0
case nil:
return 42
// CHECK: [[NILBB]]:
// CHECK: integer_literal $Builtin.IntLiteral, 42
}
}
// SR-3518
// CHECK-LABEL: sil hidden [ossa] @$s6switch43testMultiPatternsWithOuterScopeSameNamedVar4base6filterySiSg_AEtF
func testMultiPatternsWithOuterScopeSameNamedVar(base: Int?, filter: Int?) {
switch(base, filter) {
case (.some(let base), .some(let filter)):
// CHECK: bb2(%10 : $Int):
// CHECK-NEXT: debug_value %8 : $Int, let, name "base"
// CHECK-NEXT: debug_value %10 : $Int, let, name "filter"
print("both: \(base), \(filter)")
case (.some(let base), .none), (.none, .some(let base)):
// CHECK: bb3:
// CHECK-NEXT: br bb6(%8 : $Int)
// CHECK: bb5([[OTHER_BASE:%.*]] : $Int)
// CHECK-NEXT: br bb6([[OTHER_BASE]] : $Int)
// CHECK: bb6([[ARG:%.*]] : $Int):
// CHECK-NEXT: debug_value [[ARG]] : $Int, let, name "base"
print("single: \(base)")
default:
print("default")
}
}
// All cases are unreachable, either structurally (tuples involving Never) or
// nominally (empty enums). We fold all of these to 'unreachable'.
enum MyNever {}
func ~= (_ : MyNever, _ : MyNever) -> Bool { return true }
func myFatalError() -> MyNever { fatalError("asdf") }
func testUninhabitedSwitchScrutinee() {
func test1(x : MyNever) {
// CHECK: bb0(%0 : $MyNever):
// CHECK-NEXT: debug_value %0 : $MyNever, let, name "x"
// CHECK-NEXT: unreachable
switch x {
case myFatalError(): break
case myFatalError(): break
case myFatalError(): break
}
}
func test2(x : Never) {
// CHECK: bb0(%0 : $Never):
// CHECK-NEXT: debug_value %0 : $Never, let, name "x"
// CHECK-NEXT: unreachable
switch (x, x) {}
}
func test3(x : Never) {
// CHECK: unreachable
// CHECK-NEXT: } // end sil function '$s6switch30testUninhabitedSwitchScrutineeyyF5test3L_1xys5NeverO_tF'
switch (x, 5, x) {}
}
func test4(x : Never) {
// CHECK: unreachable
// CHECK-NEXT: } // end sil function '$s6switch30testUninhabitedSwitchScrutineeyyF5test4L_1xys5NeverO_tF'
switch ((8, 6, 7), (5, 3, (0, x))) {}
}
func test5() {
// CHECK: %0 = function_ref @$s6switch12myFatalErrorAA7MyNeverOyF : $@convention(thin) () -> MyNever
// CHECK-NEXT: %1 = apply %0() : $@convention(thin) () -> MyNever
// CHECK-NEXT: unreachable
switch myFatalError() {}
}
}
// Make sure that we properly can handle address only tuples with loadable
// subtypes.
// CHECK-LABEL: sil hidden [ossa] @$s6switch33address_only_with_trivial_subtypeyyAA21TrivialSingleCaseEnumO_yptF : $@convention(thin) (TrivialSingleCaseEnum, @in_guaranteed Any) -> () {
// CHECK: [[MEM:%.*]] = alloc_stack $(TrivialSingleCaseEnum, Any)
// CHECK: [[INIT_TUP_0:%.*]] = tuple_element_addr [[MEM]] : $*(TrivialSingleCaseEnum, Any), 0
// CHECK: [[INIT_TUP_1:%.*]] = tuple_element_addr [[MEM]] : $*(TrivialSingleCaseEnum, Any), 1
// CHECK: store {{%.*}} to [trivial] [[INIT_TUP_0]]
// CHECK: copy_addr [take] {{%.*}} to [initialization] [[INIT_TUP_1]]
// CHECK: [[TUP_0:%.*]] = tuple_element_addr [[MEM]] : $*(TrivialSingleCaseEnum, Any), 0
// CHECK: [[TUP_0_VAL:%.*]] = load [trivial] [[TUP_0]]
// CHECK: [[TUP_1:%.*]] = tuple_element_addr [[MEM]] : $*(TrivialSingleCaseEnum, Any), 1
// CHECK: switch_enum [[TUP_0_VAL]]
//
// CHECK: } // end sil function '$s6switch33address_only_with_trivial_subtypeyyAA21TrivialSingleCaseEnumO_yptF'
func address_only_with_trivial_subtype(_ a: TrivialSingleCaseEnum, _ value: Any) {
switch (a, value) {
case (.a, _):
break
default:
break
}
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch36address_only_with_nontrivial_subtypeyyAA24NonTrivialSingleCaseEnumO_yptF : $@convention(thin) (@guaranteed NonTrivialSingleCaseEnum, @in_guaranteed Any) -> () {
// CHECK: [[MEM:%.*]] = alloc_stack $(NonTrivialSingleCaseEnum, Any)
// CHECK: [[INIT_TUP_0:%.*]] = tuple_element_addr [[MEM]] : $*(NonTrivialSingleCaseEnum, Any), 0
// CHECK: [[INIT_TUP_1:%.*]] = tuple_element_addr [[MEM]] : $*(NonTrivialSingleCaseEnum, Any), 1
// CHECK: store {{%.*}} to [init] [[INIT_TUP_0]]
// CHECK: copy_addr [take] {{%.*}} to [initialization] [[INIT_TUP_1]]
// CHECK: [[TUP_0:%.*]] = tuple_element_addr [[MEM]] : $*(NonTrivialSingleCaseEnum, Any), 0
// CHECK: [[TUP_0_VAL:%.*]] = load_borrow [[TUP_0]]
// CHECK: [[TUP_1:%.*]] = tuple_element_addr [[MEM]] : $*(NonTrivialSingleCaseEnum, Any), 1
// CHECK: switch_enum [[TUP_0_VAL]]
//
// CHECK: bb1([[CASE_VAL:%.*]] :
// CHECK-NEXT: destroy_addr [[TUP_1]]
// CHECK-NEXT: end_borrow [[TUP_0_VAL]]
// CHECK-NEXT: destroy_addr [[TUP_0]]
// CHECK-NEXT: dealloc_stack [[MEM]]
//
// CHECK: bb2:
// CHECK-NEXT: destroy_addr [[MEM]]
// CHECK-NEXT: dealloc_stack [[MEM]]
// CHECK: } // end sil function '$s6switch36address_only_with_nontrivial_subtypeyyAA24NonTrivialSingleCaseEnumO_yptF'
func address_only_with_nontrivial_subtype(_ a: NonTrivialSingleCaseEnum, _ value: Any) {
switch (a, value) {
case (.a, _):
break
default:
break
}
}
// This test makes sure that when we have a tuple that is partly address only
// and partially an object that even though we access the object at +0 via a
// load_borrow, we do not lose the +1 from the original tuple formation.
// CHECK-LABEL: sil hidden [ossa] @$s6switch35partial_address_only_tuple_dispatchyyAA5KlassC_ypSgtF : $@convention(thin) (@guaranteed Klass, @in_guaranteed Optional<Any>) -> () {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $Klass, [[ARG1:%.*]] : $*Optional<Any>):
// CHECK: [[ARG0_COPY:%.*]] = copy_value [[ARG0]]
// CHECK: [[ARG1_COPY:%.*]] = alloc_stack $Optional<Any>
// CHECK: copy_addr [[ARG1]] to [initialization] [[ARG1_COPY]]
// CHECK: [[TUP:%.*]] = alloc_stack $(Klass, Optional<Any>)
// CHECK: [[TUP_0:%.*]] = tuple_element_addr [[TUP]] : $*(Klass, Optional<Any>), 0
// CHECK: [[TUP_1:%.*]] = tuple_element_addr [[TUP]] : $*(Klass, Optional<Any>), 1
// CHECK: store [[ARG0_COPY]] to [init] [[TUP_0]]
// CHECK: copy_addr [take] [[ARG1_COPY]] to [initialization] [[TUP_1]]
// CHECK: [[TUP_0:%.*]] = tuple_element_addr [[TUP]] : $*(Klass, Optional<Any>), 0
// CHECK: [[TUP_0_VAL:%.*]] = load_borrow [[TUP_0]]
// CHECK: [[TUP_1:%.*]] = tuple_element_addr [[TUP]] : $*(Klass, Optional<Any>), 1
// CHECK: destroy_addr [[TUP_1]]
// CHECK: end_borrow [[TUP_0_VAL]]
// CHECK: destroy_addr [[TUP_0]]
// CHECK: dealloc_stack [[TUP]]
// CHECK: br bb2
//
// CHECK: bb1:
// CHECK: destroy_addr [[TUP]]
// CHECK: dealloc_stack [[TUP]]
// CHECK: } // end sil function '$s6switch35partial_address_only_tuple_dispatchyyAA5KlassC_ypSgtF'
func partial_address_only_tuple_dispatch(_ name: Klass, _ value: Any?) {
switch (name, value) {
case (_, _):
break
default:
break
}
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch50partial_address_only_tuple_dispatch_with_fail_caseyyAA5KlassC_ypSgtF : $@convention(thin) (@guaranteed Klass, @in_guaranteed Optional<Any>) -> () {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $Klass, [[ARG1:%.*]] : $*Optional<Any>):
// CHECK: [[ARG0_COPY:%.*]] = copy_value [[ARG0]]
// CHECK: [[ARG1_COPY:%.*]] = alloc_stack $Optional<Any>
// CHECK: copy_addr [[ARG1]] to [initialization] [[ARG1_COPY]]
// CHECK: [[TUP:%.*]] = alloc_stack $(Klass, Optional<Any>)
// CHECK: [[TUP_0:%.*]] = tuple_element_addr [[TUP]] : $*(Klass, Optional<Any>), 0
// CHECK: [[TUP_1:%.*]] = tuple_element_addr [[TUP]] : $*(Klass, Optional<Any>), 1
// CHECK: store [[ARG0_COPY]] to [init] [[TUP_0]]
// CHECK: copy_addr [take] [[ARG1_COPY]] to [initialization] [[TUP_1]]
// CHECK: [[TUP_0:%.*]] = tuple_element_addr [[TUP]] : $*(Klass, Optional<Any>), 0
// CHECK: [[TUP_0_VAL:%.*]] = load_borrow [[TUP_0]]
// CHECK: [[TUP_1:%.*]] = tuple_element_addr [[TUP]] : $*(Klass, Optional<Any>), 1
// CHECK: checked_cast_br [[TUP_0_VAL]] : $Klass to AnyObject, [[IS_ANYOBJECT_BB:bb[0-9]+]], [[ISNOT_ANYOBJECT_BB:bb[0-9]+]]
//
// CHECK: [[IS_ANYOBJECT_BB]]([[ANYOBJECT:%.*]] : @guaranteed $AnyObject):
// CHECK: [[ANYOBJECT_COPY:%.*]] = copy_value [[ANYOBJECT]]
// ... CASE BODY ...
// CHECK: destroy_addr [[TUP_1]]
// CHECK: end_borrow [[TUP_0_VAL]]
// CHECK: destroy_addr [[TUP_0]]
// CHECK: dealloc_stack [[TUP]]
// CHECK: br [[EXIT_BB:bb[0-9]+]]
//
// CHECK: [[ISNOT_ANYOBJECT_BB]](
// CHECK: switch_enum_addr [[TUP_1]] : $*Optional<Any>, case #Optional.some!enumelt: [[HAS_TUP_1_BB:bb[0-9]+]], default [[NO_TUP_1_BB:bb[0-9]+]]
//
// CHECK: [[HAS_TUP_1_BB]]:
// CHECK-NEXT: [[OPT_ANY_ADDR:%.*]] = alloc_stack $Optional<Any>
// CHECK-NEXT: copy_addr [[TUP_1]] to [initialization] [[OPT_ANY_ADDR]]
// CHECK-NEXT: [[SOME_ANY_ADDR:%.*]] = unchecked_take_enum_data_addr [[OPT_ANY_ADDR]]
// CHECK-NEXT: [[ANYOBJECT_ADDR:%.*]] = alloc_stack $AnyObject
// CHECK-NEXT: checked_cast_addr_br copy_on_success Any in {{%.*}} : $*Any to AnyObject in {{%.*}} : $*AnyObject, [[IS_ANY_BB:bb[0-9]+]], [[ISNOT_ANY_BB:bb[0-9]+]]
//
// Make sure that we clean up everything here. We are exiting here.
//
// CHECK: [[IS_ANY_BB]]:
// CHECK-NEXT: [[ANYOBJECT:%.*]] = load [take] [[ANYOBJECT_ADDR]]
// CHECK-NEXT: begin_borrow
// CHECK-NEXT: debug_value
// CHECK-NEXT: end_borrow
// CHECK-NEXT: destroy_value [[ANYOBJECT]]
// CHECK-NEXT: dealloc_stack [[ANYOBJECT_ADDR]]
// CHECK-NEXT: destroy_addr [[SOME_ANY_ADDR]]
// CHECK-NEXT: dealloc_stack [[OPT_ANY_ADDR]]
// CHECK-NEXT: destroy_addr [[TUP_1]]
// CHECK-NEXT: end_borrow [[TUP_0_VAL]]
// CHECK-NEXT: destroy_addr [[TUP_0]]
// CHECK-NEXT: dealloc_stack [[TUP]]
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: br [[EXIT_BB]]
//
// CHECK: [[ISNOT_ANY_BB]]:
// CHECK-NEXT: dealloc_stack [[ANYOBJECT_ADDR]]
// CHECK-NEXT: destroy_addr [[SOME_ANY_ADDR]]
// CHECK-NEXT: dealloc_stack [[OPT_ANY_ADDR]]
// CHECK-NEXT: end_borrow
// CHECK-NEXT: br [[UNFORWARD_BB:bb[0-9]+]]
//
// CHECK: [[NO_TUP_1_BB]]:
// CHECK-NEXT: end_borrow
// CHECK-NEXT: br [[UNFORWARD_BB]]
//
// CHECK: [[UNFORWARD_BB]]:
// CHECK-NEXT: destroy_addr [[TUP]]
// CHECK-NEXT: dealloc_stack [[TUP]]
// CHECK: br [[EXIT_BB]]
//
// CHECK: [[EXIT_BB]]:
// ...
// CHECK: } // end sil function '$s6switch50partial_address_only_tuple_dispatch_with_fail_caseyyAA5KlassC_ypSgtF'
func partial_address_only_tuple_dispatch_with_fail_case(_ name: Klass, _ value: Any?) {
switch (name, value) {
case let (x as AnyObject, _):
break
case let (_, y as AnyObject):
break
default:
break
}
}
// This was crashing the ownership verifier at some point and was reported in
// SR-6664. Just make sure that we still pass the ownership verifier.
// `indirect` is necessary; generic parameter is necessary.
indirect enum SR6664_Base<Element> {
// Tuple associated value is necessary; one element must be a function,
// the other must be a non-function using the generic parameter.
// (The original associated value was `(where: (Element) -> Bool, of: Element?)`,
// to give you an idea of the variety of types.)
case index((Int) -> Void, Element)
// Function can be in an extension or not. Can have a return value or not. Can
// have a parameter or not. Can be generic or not.
func relative() {
switch self {
// Matching the case is necessary. You can capture or ignore the associated
// values.
case .index:
// Body doesn't matter.
break
}
}
}
// Make sure that we properly create switch_enum success arguments if we have an
// associated type that is a void type.
func testVoidType() {
let x: Optional<()> = ()
switch x {
case .some(let x):
break
case .none:
break
}
}
////////////////////////////////////////////////
// Fallthrough Multiple Case Label Item Tests //
////////////////////////////////////////////////
// CHECK-LABEL: sil hidden [ossa] @$s6switch28addressOnlyFallthroughCalleeyyAA015MultipleAddressC8CaseEnumOyxGSzRzlF : $@convention(thin) <T where T : BinaryInteger> (@in_guaranteed MultipleAddressOnlyCaseEnum<T>) -> () {
// CHECK: bb0([[ARG:%.*]] :
// CHECK: [[AB_PHI:%.*]] = alloc_stack $T, let, name "x"
// CHECK: [[ABB_PHI:%.*]] = alloc_stack $T, let, name "x"
// CHECK: [[ABBC_PHI:%.*]] = alloc_stack $T, let, name "x"
// CHECK: [[SWITCH_ENUM_ARG:%.*]] = alloc_stack $MultipleAddressOnlyCaseEnum<T>
// CHECK: copy_addr [[ARG]] to [initialization] [[SWITCH_ENUM_ARG]]
// CHECK: switch_enum_addr [[SWITCH_ENUM_ARG]] : $*MultipleAddressOnlyCaseEnum<T>, case #MultipleAddressOnlyCaseEnum.a!enumelt: [[BB_A:bb[0-9]+]], case #MultipleAddressOnlyCaseEnum.b!enumelt: [[BB_B:bb[0-9]+]], case #MultipleAddressOnlyCaseEnum.c!enumelt: [[BB_C:bb[0-9]+]]
//
// CHECK: [[BB_A]]:
// CHECK: [[SWITCH_ENUM_ARG_PROJ:%.*]] = unchecked_take_enum_data_addr [[SWITCH_ENUM_ARG]]
// CHECK: [[CASE_BODY_VAR_A:%.*]] = alloc_stack [lexical] $T, let, name "x"
// CHECK: copy_addr [take] [[SWITCH_ENUM_ARG_PROJ]] to [initialization] [[CASE_BODY_VAR_A]]
// CHECK: copy_addr [[CASE_BODY_VAR_A]] to [initialization] [[AB_PHI]]
// CHECK: destroy_addr [[CASE_BODY_VAR_A]]
// CHECK: br [[BB_AB:bb[0-9]+]]
//
// CHECK: [[BB_B]]:
// CHECK: [[SWITCH_ENUM_ARG_PROJ:%.*]] = unchecked_take_enum_data_addr [[SWITCH_ENUM_ARG]]
// CHECK: [[CASE_BODY_VAR_B:%.*]] = alloc_stack [lexical] $T, let, name "x"
// CHECK: copy_addr [[SWITCH_ENUM_ARG_PROJ]] to [initialization] [[CASE_BODY_VAR_B]]
// CHECK: [[FUNC_CMP:%.*]] = function_ref @$sSzsE2eeoiySbx_qd__tSzRd__lFZ :
// CHECK: [[GUARD_RESULT:%.*]] = apply [[FUNC_CMP]]<T, Int>([[CASE_BODY_VAR_B]], {{%.*}}, {{%.*}})
// CHECK: [[GUARD_RESULT_EXT:%.*]] = struct_extract [[GUARD_RESULT]]
// CHECK: cond_br [[GUARD_RESULT_EXT]], [[BB_B_GUARD_SUCC:bb[0-9]+]], [[BB_B_GUARD_FAIL:bb[0-9]+]]
//
// CHECK: [[BB_B_GUARD_SUCC]]:
// CHECK: copy_addr [[CASE_BODY_VAR_B]] to [initialization] [[AB_PHI]]
// CHECK: destroy_addr [[CASE_BODY_VAR_B]]
// CHECK: destroy_addr [[SWITCH_ENUM_ARG_PROJ]]
// CHECK: br [[BB_AB]]
//
// CHECK: [[BB_AB]]:
// CHECK: copy_addr [[AB_PHI]] to [initialization] [[ABB_PHI]]
// CHECK: destroy_addr [[AB_PHI]]
// CHECK: br [[BB_AB_CONT:bb[0-9]+]]
//
// CHECK: [[BB_AB_CONT]]:
// CHECK: copy_addr [[ABB_PHI]] to [initialization] [[ABBC_PHI]]
// CHECK: destroy_addr [[ABB_PHI]]
// CHECK: br [[BB_FINAL_CONT:bb[0-9]+]]
//
// CHECK: [[BB_B_GUARD_FAIL]]:
// CHECK: destroy_addr [[CASE_BODY_VAR_B]]
// CHECK: [[CASE_BODY_VAR_B_2:%.*]] = alloc_stack [lexical] $T, let, name "x"
// CHECK: copy_addr [take] [[SWITCH_ENUM_ARG_PROJ]] to [initialization] [[CASE_BODY_VAR_B_2]]
// CHECK: copy_addr [[CASE_BODY_VAR_B_2]] to [initialization] [[ABB_PHI]]
// CHECK: br [[BB_AB_CONT]]
//
// CHECK: [[BB_C]]:
// CHECK: [[SWITCH_ENUM_ARG_PROJ:%.*]] = unchecked_take_enum_data_addr [[SWITCH_ENUM_ARG]]
// CHECK: [[CASE_BODY_VAR_C:%.*]] = alloc_stack [lexical] $T, let, name "x"
// CHECK: copy_addr [take] [[SWITCH_ENUM_ARG_PROJ]] to [initialization] [[CASE_BODY_VAR_C]]
// CHECK: copy_addr [[CASE_BODY_VAR_C]] to [initialization] [[ABBC_PHI]]
// CHECK: destroy_addr [[CASE_BODY_VAR_C]]
// CHECK: br [[BB_FINAL_CONT]]
//
// CHECK: [[BB_FINAL_CONT]]:
// CHECK: destroy_addr [[ABBC_PHI]]
// CHECK: return
// CHECK: } // end sil function '$s6switch28addressOnlyFallthroughCalleeyyAA015MultipleAddressC8CaseEnumOyxGSzRzlF'
func addressOnlyFallthroughCallee<T : BinaryInteger>(_ e : MultipleAddressOnlyCaseEnum<T>) {
switch e {
case .a(let x): fallthrough
case .b(let x) where x == 2: fallthrough
case .b(let x): fallthrough
case .c(let x):
print(x)
}
}
func addressOnlyFallthroughCaller() {
var myFoo : MultipleAddressOnlyCaseEnum = MultipleAddressOnlyCaseEnum.a(10)
addressOnlyFallthroughCallee(myFoo)
}
// CHECK-LABEL: sil hidden [ossa] @$s6switch35nonTrivialLoadableFallthroughCalleeyyAA011MultipleNonC8CaseEnumOF : $@convention(thin) (@guaranteed MultipleNonTrivialCaseEnum) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $MultipleNonTrivialCaseEnum):
// CHECK: switch_enum [[ARG]] : $MultipleNonTrivialCaseEnum, case #MultipleNonTrivialCaseEnum.a!enumelt: [[BB_A:bb[0-9]+]], case #MultipleNonTrivialCaseEnum.b!enumelt: [[BB_B:bb[0-9]+]], case #MultipleNonTrivialCaseEnum.c!enumelt: [[BB_C:bb[0-9]+]]
//
// CHECK: [[BB_A]]([[BB_A_ARG:%.*]] : @guaranteed
// CHECK: [[BB_A_ARG_COPY:%.*]] = copy_value [[BB_A_ARG]]
// CHECK: [[BB_A_ARG_COPY_BORROW:%.*]] = begin_borrow [lexical] [[BB_A_ARG_COPY]]
// CHECK: apply {{%.*}}([[BB_A_ARG_COPY_BORROW]])
// CHECK: [[RESULT:%.*]] = copy_value [[BB_A_ARG_COPY_BORROW]]
// CHECK: br [[BB_AB:bb[0-9]+]]([[RESULT]] :
//
// CHECK: [[BB_B]]([[BB_B_ARG:%.*]] : @guaranteed
// CHECK: [[BB_B_ARG_COPY:%.*]] = copy_value [[BB_B_ARG]]
// CHECK: [[BB_B_ARG_COPY_BORROW:%.*]] = begin_borrow [lexical] [[BB_B_ARG_COPY]]
// CHECK: [[RESULT:%.*]] = copy_value [[BB_B_ARG_COPY_BORROW]]
// CHECK: br [[BB_AB:bb[0-9]+]]([[RESULT]] :
//
// CHECK: [[BB_AB:bb[0-9]+]]([[BB_AB_PHI:%.*]] : @owned
// CHECK: [[BB_AB_PHI_BORROW:%.*]] = begin_borrow [[BB_AB_PHI]]
// CHECK: apply {{%.*}}([[BB_AB_PHI_BORROW]])
// CHECK: [[RESULT:%.*]] = copy_value [[BB_AB_PHI]]
// CHECK: br [[BB_ABC:bb[0-9]+]]([[RESULT]] :
//
// CHECK: [[BB_C]]([[BB_C_ARG:%.*]] : @guaranteed
// CHECK: [[BB_C_COPY:%.*]] = copy_value [[BB_C_ARG]]
// CHECK: [[BB_C_BORROWED_COPY:%.*]] = begin_borrow [lexical] [[BB_C_COPY]]
// CHECK: [[RESULT:%.*]] = copy_value [[BB_C_BORROWED_COPY]]
// CHECK: br [[BB_ABC]]([[RESULT]] :
//
// CHECK: [[BB_ABC]]([[BB_ABC_ARG:%.*]] : @owned
// CHECK: [[BB_ABC_ARG_BORROW:%.*]] = begin_borrow [[BB_ABC_ARG]]
// CHECK: apply {{%.*}}([[BB_ABC_ARG_BORROW]])
// CHECK: return
// CHECK: } // end sil function '$s6switch35nonTrivialLoadableFallthroughCalleeyyAA011MultipleNonC8CaseEnumOF'
func nonTrivialLoadableFallthroughCallee(_ e : MultipleNonTrivialCaseEnum) {
switch e {
case .a(let x):
a(x)
fallthrough
case .b(let x):
b(x)
fallthrough
case .c(let x):
c(x)
}
}
// Just make sure that we do not crash on this.
func nonTrivialLoadableFallthroughCalleeGuards(_ e : MultipleNonTrivialCaseEnum) {
switch e {
case .a(let x) where x.isFalse:
a(x)
fallthrough
case .a(let x) where x.isTrue:
a(x)
fallthrough
case .b(let x) where x.isTrue:
b(x)
fallthrough
case .b(let x) where x.isFalse:
b(x)
fallthrough
case .c(let x) where x.isTrue:
c(x)
fallthrough
case .c(let x) where x.isFalse:
c(x)
break
default:
d()
}
}
func nonTrivialLoadableFallthroughCallee2(_ e : MultipleNonTrivialCaseEnum) {
switch e {
case .a(let x):
a(x)
fallthrough
case .b(let x):
b(x)
break
default:
break
}
}
// Make sure that we do not crash while emitting this code.
//
// DISCUSSION: The original crash was due to us performing an assignment/lookup
// on the VarLocs DenseMap in the same statement. This was caught be an
// asanified compiler. This test is just to make sure we do not regress.
enum Storage {
case empty
case single(Int)
case pair(Int, Int)
case array([Int])
subscript(range: [Int]) -> Storage {
get {
return .empty
}
set {
switch self {
case .empty:
break
case .single(let index):
break
case .pair(let first, let second):
switch (range[0], range[1]) {
case (0, 0):
switch newValue {
case .empty:
break
case .single(let other):
break
case .pair(let otherFirst, let otherSecond):
break
case .array(let other):
break
}
break
case (0, 1):
switch newValue {
case .empty:
break
case .single(let other):
break
case .pair(let otherFirst, let otherSecond):
break
case .array(let other):
break
}
break
case (0, 2):
break
case (1, 2):
switch newValue {
case .empty:
break
case .single(let other):
break
case .pair(let otherFirst, let otherSecond):
break
case .array(let other):
self = .array([first] + other)
}
break
case (2, 2):
switch newValue {
case .empty:
break
case .single(let other):
break
case .pair(let otherFirst, let otherSecond):
break
case .array(let other):
self = .array([first, second] + other)
}
break
default:
let r = range
}
case .array(let indexes):
break
}
}
}
}
// Make sure that we do not leak tuple elements if we fail to match the first
// tuple element.
enum rdar49990484Enum1 {
case case1(Klass)
case case2(Klass, Int)
}
enum rdar49990484Enum2 {
case case1(Klass)
case case2(rdar49990484Enum1, Klass)
}
struct rdar49990484Struct {
var value: rdar49990484Enum2
func doSomethingIfLet() {
if case let .case2(.case2(k, _), _) = value {
return
}
}
func doSomethingSwitch() {
switch value {
case let .case2(.case2(k, _), _):
return
default:
return
}
return
}
func doSomethingGuardLet() {
guard case let .case2(.case2(k, _), _) = value else {
return
}
}
}
| apache-2.0 | c4e43e009cd6747f4c8479793d6d5bd7 | 32.1018 | 275 | 0.574418 | 2.967392 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document2.playgroundchapter/Pages/Challenge3.playgroundpage/Sources/Setup.swift | 1 | 4180 | //
// Setup.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
//let world = GridWorld(columns: 7, rows: 5)
let world = loadGridWorld(named: "2.6")
let actor = Actor()
public func playgroundPrologue() {
world.place(actor, facing: north, at: Coordinate(column: 2, row: 2))
placeItems()
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world)
//// ----
}
// Called from LiveView.swift to initially set the LiveView.
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func playgroundEpilogue() {
sendCommands(for: world)
}
func placeItems() {
let items = [
Coordinate(column: 2, row: 0),
Coordinate(column: 3, row: 0),
Coordinate(column: 4, row: 0),
Coordinate(column: 2, row: 4),
Coordinate(column: 3, row: 4),
Coordinate(column: 4, row: 4),
]
world.placeGems(at: items)
}
func placeFloor() {
let obstacles = [
Coordinate(column: 0, row: 0),
Coordinate(column: 0, row: 1),
Coordinate(column: 0, row: 2),
Coordinate(column: 0, row: 3),
Coordinate(column: 0, row: 4),
Coordinate(column: 1, row: 0),
Coordinate(column: 1, row: 1),
Coordinate(column: 1, row: 3),
Coordinate(column: 1, row: 4),
Coordinate(column: 5, row: 0),
Coordinate(column: 5, row: 1),
Coordinate(column: 5, row: 3),
Coordinate(column: 5, row: 4),
Coordinate(column: 6, row: 0),
Coordinate(column: 6, row: 1),
Coordinate(column: 6, row: 2),
Coordinate(column: 6, row: 3),
Coordinate(column: 6, row: 4),
]
world.removeNodes(at: obstacles)
world.placeWater(at: obstacles)
let tiers = [
Coordinate(column: 1, row: 2),
Coordinate(column: 2, row: 2),
Coordinate(column: 3, row: 2),
Coordinate(column: 3, row: 1),
Coordinate(column: 4, row: 2),
Coordinate(column: 5, row: 2),
Coordinate(column: 2, row: 4),
Coordinate(column: 2, row: 4),
Coordinate(column: 4, row: 4),
Coordinate(column: 4, row: 4),
Coordinate(column: 3, row: 0),
Coordinate(column: 3, row: 0),
Coordinate(column: 2, row: 3),
Coordinate(column: 4, row: 3),
]
world.placeBlocks(at: tiers)
let stairsCoordinates = [
Coordinate(column: 3, row: 1),
Coordinate(column: 3, row: 3),
]
world.place(nodeOfType: Stair.self, facing: north, at: stairsCoordinates)
let stairsCoordinates1 = [
Coordinate(column: 2, row: 1),
Coordinate(column: 2, row: 3),
Coordinate(column: 4, row: 1),
Coordinate(column: 4, row: 3),
]
world.place(nodeOfType: Stair.self, at: stairsCoordinates1)
}
| mit | 6e7e343072cf9394609601985f430c71 | 32.98374 | 89 | 0.428947 | 4.946746 | false | false | false | false |
dreamsxin/swift | stdlib/public/Platform/POSIXError.swift | 5 | 8151 | // FIXME: Only defining _POSIXError for Darwin at the moment.
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
/// Enumeration describing POSIX error codes.
@objc public enum POSIXError : CInt {
// FIXME: These are the values for Darwin. We need to get the Linux
// values as well.
case EPERM = 1 /// Operation not permitted.
case ENOENT = 2 /// No such file or directory.
case ESRCH = 3 /// No such process.
case EINTR = 4 /// Interrupted system call.
case EIO = 5 /// Input/output error.
case ENXIO = 6 /// Device not configured.
case E2BIG = 7 /// Argument list too long.
case ENOEXEC = 8 /// Exec format error.
case EBADF = 9 /// Bad file descriptor.
case ECHILD = 10 /// No child processes.
case EDEADLK = 11 /// Resource deadlock avoided.
/// 11 was EAGAIN.
case ENOMEM = 12 /// Cannot allocate memory.
case EACCES = 13 /// Permission denied.
case EFAULT = 14 /// Bad address.
case ENOTBLK = 15 /// Block device required.
case EBUSY = 16 /// Device / Resource busy.
case EEXIST = 17 /// File exists.
case EXDEV = 18 /// Cross-device link.
case ENODEV = 19 /// Operation not supported by device.
case ENOTDIR = 20 /// Not a directory.
case EISDIR = 21 /// Is a directory.
case EINVAL = 22 /// Invalid argument.
case ENFILE = 23 /// Too many open files in system.
case EMFILE = 24 /// Too many open files.
case ENOTTY = 25 /// Inappropriate ioctl for device.
case ETXTBSY = 26 /// Text file busy.
case EFBIG = 27 /// File too large.
case ENOSPC = 28 /// No space left on device.
case ESPIPE = 29 /// Illegal seek.
case EROFS = 30 /// Read-only file system.
case EMLINK = 31 /// Too many links.
case EPIPE = 32 /// Broken pipe.
/// math software.
case EDOM = 33 /// Numerical argument out of domain.
case ERANGE = 34 /// Result too large.
/// non-blocking and interrupt i/o.
case EAGAIN = 35 /// Resource temporarily unavailable.
public static var EWOULDBLOCK: POSIXError { return EAGAIN } /// Operation would block.
case EINPROGRESS = 36 /// Operation now in progress.
case EALREADY = 37 /// Operation already in progress.
/// ipc/network software -- argument errors.
case ENOTSOCK = 38 /// Socket operation on non-socket.
case EDESTADDRREQ = 39 /// Destination address required.
case EMSGSIZE = 40 /// Message too long.
case EPROTOTYPE = 41 /// Protocol wrong type for socket.
case ENOPROTOOPT = 42 /// Protocol not available.
case EPROTONOSUPPORT = 43 /// Protocol not supported.
case ESOCKTNOSUPPORT = 44 /// Socket type not supported.
case ENOTSUP = 45 /// Operation not supported.
case EPFNOSUPPORT = 46 /// Protocol family not supported.
case EAFNOSUPPORT = 47 /// Address family not supported by protocol family.
case EADDRINUSE = 48 /// Address already in use.
case EADDRNOTAVAIL = 49 /// Can't assign requested address.
/// ipc/network software -- operational errors
case ENETDOWN = 50 /// Network is down.
case ENETUNREACH = 51 /// Network is unreachable.
case ENETRESET = 52 /// Network dropped connection on reset.
case ECONNABORTED = 53 /// Software caused connection abort.
case ECONNRESET = 54 /// Connection reset by peer.
case ENOBUFS = 55 /// No buffer space available.
case EISCONN = 56 /// Socket is already connected.
case ENOTCONN = 57 /// Socket is not connected.
case ESHUTDOWN = 58 /// Can't send after socket shutdown.
case ETOOMANYREFS = 59 /// Too many references: can't splice.
case ETIMEDOUT = 60 /// Operation timed out.
case ECONNREFUSED = 61 /// Connection refused.
case ELOOP = 62 /// Too many levels of symbolic links.
case ENAMETOOLONG = 63 /// File name too long.
case EHOSTDOWN = 64 /// Host is down.
case EHOSTUNREACH = 65 /// No route to host.
case ENOTEMPTY = 66 /// Directory not empty.
/// quotas & mush.
case EPROCLIM = 67 /// Too many processes.
case EUSERS = 68 /// Too many users.
case EDQUOT = 69 /// Disc quota exceeded.
/// Network File System.
case ESTALE = 70 /// Stale NFS file handle.
case EREMOTE = 71 /// Too many levels of remote in path.
case EBADRPC = 72 /// RPC struct is bad.
case ERPCMISMATCH = 73 /// RPC version wrong.
case EPROGUNAVAIL = 74 /// RPC prog. not avail.
case EPROGMISMATCH = 75 /// Program version wrong.
case EPROCUNAVAIL = 76 /// Bad procedure for program.
case ENOLCK = 77 /// No locks available.
case ENOSYS = 78 /// Function not implemented.
case EFTYPE = 79 /// Inappropriate file type or format.
case EAUTH = 80 /// Authentication error.
case ENEEDAUTH = 81 /// Need authenticator.
/// Intelligent device errors.
case EPWROFF = 82 /// Device power is off.
case EDEVERR = 83 /// Device error, e.g. paper out.
case EOVERFLOW = 84 /// Value too large to be stored in data type.
/// Program loading errors.
case EBADEXEC = 85 /// Bad executable.
case EBADARCH = 86 /// Bad CPU type in executable.
case ESHLIBVERS = 87 /// Shared library version mismatch.
case EBADMACHO = 88 /// Malformed Macho file.
case ECANCELED = 89 /// Operation canceled.
case EIDRM = 90 /// Identifier removed.
case ENOMSG = 91 /// No message of desired type.
case EILSEQ = 92 /// Illegal byte sequence.
case ENOATTR = 93 /// Attribute not found.
case EBADMSG = 94 /// Bad message.
case EMULTIHOP = 95 /// Reserved.
case ENODATA = 96 /// No message available on STREAM.
case ENOLINK = 97 /// Reserved.
case ENOSR = 98 /// No STREAM resources.
case ENOSTR = 99 /// Not a STREAM.
case EPROTO = 100 /// Protocol error.
case ETIME = 101 /// STREAM ioctl timeout.
case ENOPOLICY = 103 /// No such policy registered.
case ENOTRECOVERABLE = 104 /// State not recoverable.
case EOWNERDEAD = 105 /// Previous owner died.
case EQFULL = 106 /// Interface output queue is full.
public static var ELAST: POSIXError { return EQFULL } /// Must be equal largest errno.
// FIXME: EOPNOTSUPP has different values depending on __DARWIN_UNIX03 and
// KERNEL.
}
#endif // os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
| apache-2.0 | 5277993cbf060ddf8bf5f21660f732dd | 54.44898 | 93 | 0.498957 | 5.149084 | false | false | false | false |
dclelland/HOWL | Pods/AudioUnitExtensions/AudioUnitExtensions/UInt32+FourCharacterCodes.swift | 1 | 1148 | //
// AudioUnit+Properties.swift
// Pods
//
// Created by Daniel Clelland on 02/04/17.
//
import Foundation
// MARK: - Four character codes
extension UInt32 {
/// Create a `UInt32` with a four character code. Will crash if the string is not four characters long.
public init(fourCharacterCode: String) {
assert(fourCharacterCode.count == 4, "String should be four characters long")
let reversed = String(fourCharacterCode.reversed())
let bytes = (reversed as NSString).utf8String
let pointer = UnsafeRawPointer(bytes)!.assumingMemoryBound(to: UInt32.self)
self = pointer.pointee.littleEndian
}
/// Converts the four character code back to a string.
public var fourCharacterCode: String {
var bytes = bigEndian
return String(bytesNoCopy: &bytes, length: 4, encoding: .ascii, freeWhenDone: false)!
}
}
// MARK: - Private methods
internal extension OSStatus {
func check() throws {
if self != noErr {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(self), userInfo: nil)
}
}
}
| mit | 6bb1377097eded44bf9dede7a6012e5d | 25.697674 | 107 | 0.643728 | 4.381679 | false | false | false | false |
STShenZhaoliang/Swift2Guide | Swift2Guide/Swift100Tips/Swift100Tips/ObserversController.swift | 1 | 3730 | //
// ObserversController.swift
// Swift100Tips
//
// Created by 沈兆良 on 16/5/30.
// Copyright © 2016年 ST. All rights reserved.
//
import UIKit
class ObserversController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let foo = MyClass6()
foo.date = foo.date.dateByAddingTimeInterval(10086)
// 输出
// 即将将日期从 2014-08-23 12:47:36 +0000 设定至 2014-08-23 15:35:42 +0000
// 已经将日期从 2014-08-23 12:47:36 +0000 设定至 2014-08-23 15:35:42 +0000
// 365 * 24 * 60 * 60 = 31_536_000
let foo1 = MyClass7()
foo1.date = foo1.date.dateByAddingTimeInterval(100_000_000)
// 输出
// 即将将日期从 2014-08-23 13:24:14 +0000 设定至 2017-10-23 23:10:54 +0000
// 设定的时间太晚了!
// 已经将日期从 2014-08-23 13:24:14 +0000 设定至 2015-08-23 13:24:14 +0000
let b = B2()
b.number = 0
// 输出
// get
// willSet
// set
// didSet
}
}
class MyClass6 {
var date: NSDate {
willSet {
let d = date
print("即将将日期从 \(d) 设定至 \(newValue)")
}
didSet {
print("已经将日期从 \(oldValue) 设定至 \(date)")
}
}
init() {
date = NSDate()
}
}
class MyClass7 {
let oneYearInSecond: NSTimeInterval = 365 * 24 * 60 * 60
var date: NSDate {
//...
didSet {
if (date.timeIntervalSinceNow > oneYearInSecond) {
print("设定的时间太晚了!")
date = NSDate().dateByAddingTimeInterval(oneYearInSecond)
}
print("已经将日期从 \(oldValue) 设定至 \(date)")
}
}
init() {
date = NSDate()
}
//...
}
class A2 {
var number :Int {
get {
print("get")
return 1
}
set {print("set")}
}
}
class B2: A2 {
override var number: Int {
willSet {print("willSet")}
didSet {print("didSet")}
}
}
/*
set 和对应的属性观察的调用都在我们的预想之中。
这里要注意的是 get 首先被调用了一次。这是因为我们实现了 didSet,didSet 中会用到 oldValue,而这个值需要在整个 set 动作之前进行获取并存储待用,否则将无法确保正确性。
如果我们不实现 didSet 的话,这次 get 操作也将不存在。
*/
//初始化方法对属性的设定,以及在 willSet 和 didSet 中对属性的再次设定都不会再次触发属性观察的调用,一般来说这会是你所需要的行为,可以放心使用能够。
/*
在 Swift 中所声明的属性包括存储属性和计算属性两种。
其中存储属性将会在内存中实际分配地址对属性进行存储,而计算属性则不包括背后的存储,只是提供 set 和 get 两种方法。
在同一个类型中,属性观察和计算属性是不能同时共存的。
也就是说,想在一个属性定义中同时出现 set 和 willSet 或 didSet 是一件办不到的事情。
计算属性中我们可以通过改写 set 中的内容来达到和 willSet 及 didSet 同样的属性观察的目的。
如果我们无法改动这个类,又想要通过属性观察做一些事情的话,可能就需要子类化这个类,并且重写它的属性了。
重写的属性并不知道父类属性的具体实现情况,而只从父类属性中继承名字和类型,因此在子类的重载属性中我们是可以对父类的属性任意地添加属性观察的,而不用在意父类中到底是存储属性还是计算属性
*/
| mit | 58083fe51ff021898830c16f93a3a832 | 21.025424 | 99 | 0.58561 | 3.011587 | false | false | false | false |
abonz/Swift | SQLite/SQLite/ViewController.swift | 24 | 4134 | //
// ViewController.swift
// SQLite
//
// Created by Carlos Butron on 06/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// 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 UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var statement = COpaquePointer()
var data: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
loadTabla()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadTabla(){
var db_path = NSBundle.mainBundle().pathForResource("FilmCollection", ofType: "sqlite")
println(NSBundle.mainBundle())
var db = COpaquePointer()
var status = sqlite3_open(db_path!, &db)
if(status == SQLITE_OK){
//bbdd open
println("open")
}
else{
//bbdd error
println("open error")
}
var query_stmt = "select * from film"
if(sqlite3_prepare_v2(db, query_stmt, -1, &statement, nil) == SQLITE_OK){
data.removeAllObjects()
while(sqlite3_step(statement) == SQLITE_ROW){
var Dictionary = NSMutableDictionary()
let director = sqlite3_column_text(statement, 1)
let buf_director = String.fromCString(UnsafePointer<CChar>(director))
let image = sqlite3_column_text(statement, 2)
let buf_image = String.fromCString(UnsafePointer<CChar>(image))
let title = sqlite3_column_text(statement, 3)
let buf_title = String.fromCString(UnsafePointer<CChar>(title))
let year = sqlite3_column_text(statement, 4)
let buf_year = String.fromCString(UnsafePointer<CChar>(year))
Dictionary.setObject(buf_director!, forKey:"director")
Dictionary.setObject(buf_image!, forKey: "image")
Dictionary.setObject(buf_title!, forKey: "title")
Dictionary.setObject(buf_year!, forKey: "year")
data.addObject(Dictionary)
//process data
}
sqlite3_finalize(statement)
}
else{
println("ERROR")
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("MyTableViewCell") as! MyTableViewCell
var aux: AnyObject = data[indexPath.row]
var table_director = aux["director"]
cell.director.text = table_director as? String
var aux1: AnyObject = data[indexPath.row]
var table_image = aux["image"]
cell.myImage.image = UIImage(named:table_image as! String)
var aux3: AnyObject = data[indexPath.row]
var table_title = aux["title"]
cell.title.text = table_title as? String
var aux4: AnyObject = data[indexPath.row]
var table_year = aux3["year"]
cell.year.text = table_year as? String
return cell
}
}
| gpl-3.0 | 63dba2c014dcb6f20a5b42b99fde2f4e | 31.809524 | 121 | 0.591195 | 4.903915 | false | false | false | false |
CoderXiaoming/Ronaldo | SaleManager/SaleManager/Stock/Controller/SAMNoOrderSearchDetailController.swift | 1 | 4584 | //
// SAMNoOrderSearchDetailController.swift
// SaleManager
//
// Created by LiuXiaoming on 2017/6/5.
// Copyright © 2017年 YZH. All rights reserved.
//
import UIKit
class SAMNoOrderSearchDetailController: UIViewController {
///对外提供的类工厂方法
class func instance(orderArr: NSMutableArray, shoppingCarListArr: NSMutableArray, productIDName: String, countP: Int, countM: Double) ->SAMNoOrderSearchDetailController {
let vc = SAMNoOrderSearchDetailController()
vc.orderArr = orderArr
vc.shoppingCarListArr = shoppingCarListArr
vc.productIDName = productIDName
vc.countP = countP
vc.countM = countM
return vc
}
override func viewDidLoad() {
super.viewDidLoad()
//设置标题
titleLabel.text = String.init(format: "%@ 共 %d匹 %.1f米", productIDName, countP, countM)
//设置数据
self.setupData()
//设置tableView
mainTableView.dataSource = self
mainTableView.delegate = self
mainTableView.register(UINib(nibName: "SAMNoOrderSearchListCell", bundle: nil), forCellReuseIdentifier: SAMNoOrderSearchListCellReuseIdentifier)
}
//MARK: - 设置数据
fileprivate func setupData() {
if shoppingCarListArr!.count == 0 {
return
}
for index in 0...(shoppingCarListArr!.count - 1) {
let detailModel = SAMNoOrderSearchDetailModel()
let shoppingCarListModel = shoppingCarListArr![index] as! SAMShoppingCarListModel
detailModel.productIDName = shoppingCarListModel.productIDName
detailModel.countP = shoppingCarListModel.countP
detailModel.countM = shoppingCarListModel.countM
detailModel.billNumber = shoppingCarListModel.billNumber
for orderIndex in 0...(orderArr!.count - 1) {
let orderModel = orderArr![orderIndex] as! SAMOrderModel
if orderModel.billNumber == shoppingCarListModel.billNumber {
detailModel.CGUnitName = orderModel.CGUnitName
if Date().yyyyMMddStr() == orderModel.startDate {
detailModel.dateState = "今天"
}else {
detailModel.dateState = "昨天"
}
break
}
}
detailModelArr.add(detailModel)
}
}
@IBAction func dismissButtonClick(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
//MARK: - 属性
fileprivate var orderArr: NSMutableArray?
fileprivate var shoppingCarListArr: NSMutableArray?
fileprivate let detailModelArr = NSMutableArray()
fileprivate var productIDName = ""
fileprivate var countP = 0
fileprivate var countM = 0.0
//MARK: - XIB链接属性
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var mainTableView: UITableView!
//MARK: - 其他方法
fileprivate init() {
super.init(nibName: nil, bundle: nil)
}
fileprivate override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = Bundle.main.loadNibNamed("SAMNoOrderSearchDetailController", owner: self, options: nil)![0] as! UIView
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
//MARK: - mainTableView相关方法
extension SAMNoOrderSearchDetailController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return detailModelArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = detailModelArr[indexPath.row] as! SAMNoOrderSearchDetailModel
let cell = tableView.dequeueReusableCell(withIdentifier: SAMNoOrderSearchListCellReuseIdentifier) as! SAMNoOrderSearchListCell
cell.model = model
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
}
| apache-2.0 | 27bee9d5275081249feea9da2439dbdd | 32.766917 | 174 | 0.622801 | 5.097616 | false | false | false | false |
VArbiter/Rainville_iOS-Swift | FileOpetareRecord/Deleted/2017年06月14日153253/CCMainViewControllerT.swift | 1 | 4917 | //
// CCMainViewControllerT.swift
// Rainville-Swift
//
// Created by 冯明庆 on 31/05/2017.
// Copyright © 2017 冯明庆. All rights reserved.
//
import UIKit
class CCMainViewControllerT: CCBaseViewController , UITableViewDelegate , UITableViewDataSource , CCPlayActionDelegate , CCCellTimerDelegate {
@IBOutlet private weak var labelPoem: UILabel!
private lazy var tableView: UITableView = {
return CCMainHandler.ccCreateContentTableView();
}()
private lazy var cell: CCMainScrollCell = {
return CCMainScrollCell.init(CGRect.null);
}()
private lazy var headerView: CCMainHeaderView = {
return CCMainHeaderView.initFromNib();
}()
private lazy var handler: CCAudioHandler = {
return CCAudioHandler.sharedInstance;
}()
private let dictionaryTheme: Dictionary! = ccDefaultAudioSet();
override func viewDidLoad() {
super.viewDidLoad()
self.ccDefaultSettings();
self.ccInitViewSettings();
}
//MARK: - Private
private func ccDefaultSettings() {
NotificationCenter.default.addObserver(self,
selector: #selector(ccNotificationRemoteControl(_:)),
name: NSNotification.Name(rawValue: _CC_APP_DID_RECEIVE_REMOTE_NOTIFICATION_),
object: nil);
}
private func ccInitViewSettings() {
let _ = self.labelPoem.ccMusket(12.0, _CC_RAIN_POEM_());
self.view.addSubview(self.tableView);
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.headerView.delegate = self;
self.tableView.tableHeaderView = self.headerView;
self.cell.delegate = self;
self.cell.ccConfigureCellWithHandler { [unowned self] (stringKey : String, intSelectedIndex : Int) in
self.ccClickedAction(intSelectedIndex, withKey: stringKey);
self.cell.ccSetTimer(true);
}
}
@objc private func ccNotificationRemoteControl(_ sender : Notification) {
let eventSubtype : UIEventSubtype? = sender.userInfo?["key"] as? UIEventSubtype;
guard (eventSubtype != nil) else {
return;
}
if let eventSubtypeT = eventSubtype {
if eventSubtypeT.rawValue < 0 {
return;
}
switch eventSubtypeT {
case .remoteControlPause:
self.handler.ccPausePlayingWithCompleteHandler({
CCLog("_CC_PAUSE_SUCCEED_");
}, .CCPlayOptionPause);
self.headerView.ccSetButtonStatus(bool: false);
case .remoteControlPlay:
self.handler.ccPausePlayingWithCompleteHandler({
CCLog("_CC_PLAY_SUCCEED_");
}, .CCPlayOptionPlay);
self.headerView.ccSetButtonStatus(bool: true);
case .remoteControlNextTrack:
self.cell.ccSetPlayingAudio(.CCAudioControlNext);
case .remoteControlPreviousTrack:
self.cell.ccSetPlayingAudio(.CCAudioControlPrevious);
default:
return;
}
}
}
//MARK: - UITableViewDataSource , UITableViewDelegate
internal func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1;
}
internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return self.cell;
}
internal func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(ccScreenHeight() * 0.3);
}
//MARK: - CCPlayActionDelegate
internal func ccHeaderButtonActionWithPlayOrPause(bool: Bool) {
self.handler.ccPausePlayingWithCompleteHandler({
CCLog("_CC_PAUSE/PLAY_SUCCEED_");
}, (bool ? CCPlayOption.CCPlayOptionPlay : CCPlayOption.CCPlayOptionPause));
self.cell.ccSetTimer(bool);
if !bool {
self.ccCellTimerWithSeconds(0);
}
}
//MARK: - CCCellTimerDelegate
internal func ccCellTimerWithSeconds(_ integerSeconds: Int) {
self.handler.ccSetAutoStopWithSeconds(integerSeconds) { [unowned self] (isSucceed : Bool, item : Any?) in
if let itemT = item {
self.headerView.labelCountDown.text = itemT as? String;
}
self.headerView.labelCountDown.isHidden = isSucceed;
}
}
private func ccClickedAction(_ intIndex : Int , withKey stringKey : String) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| gpl-3.0 | 78a33cd01ae3ba83675207ae377ae6a8 | 35.325926 | 142 | 0.608891 | 4.831527 | false | false | false | false |
JaleelNazir/MJMaterialSwitch | MJMaterialSwitch/MJMaterialSwitch.swift | 1 | 17130 | //
// MJMaterialSwitch.swift
// MJMaterialSwitch
//
// Created by Jaleel on 3/21/17.
// Copyright © 2017. All rights reserved.
//
import UIKit
//MARK: - Initial state (on or off)
public enum MJMaterialSwitchState {
case on, off
}
class MJMaterialSwitch: UIControl {
var isOn: Bool = true
var thumbOnTintColor: UIColor!
var thumbOffTintColor: UIColor!
var trackOnTintColor: UIColor!
var trackOffTintColor: UIColor!
var thumbDisabledTintColor: UIColor!
var trackDisabledTintColor: UIColor!
var isBounceEnabled: Bool = false {
didSet {
if self.isBounceEnabled {
self.bounceOffset = 3.0
} else {
self.bounceOffset = 0.0
}
}
}
var isRippleEnabled: Bool = true
var rippleFillColor: UIColor = .gray
var switchThumb: UIButton!
var track: UIView!
var tarckEdgeInset: UIEdgeInsets = UIEdgeInsets.init(top: 12, left: 0, bottom: 12, right: 0)
fileprivate var thumbOnPosition: CGFloat!
fileprivate var thumbOffPosition: CGFloat!
fileprivate var bounceOffset: CGFloat!
fileprivate var rippleLayer: CAShapeLayer!
//MARK: - Initializer
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.initialize()
}
func initialize() {
self.backgroundColor = .white
// initialize parameters
self.thumbOnTintColor = UIColor(red:52.0 / 255.0, green:109.0 / 255.0, blue:241.0 / 255.0, alpha:1.0)
self.thumbOffTintColor = UIColor(red:249.0 / 255.0, green:249.0 / 255.0, blue:249.0 / 255.0, alpha:1.0)
self.trackOnTintColor = UIColor(red:143.0 / 255.0, green:179.0 / 255.0, blue:247.0 / 255.0, alpha:1.0)
self.trackOffTintColor = UIColor(red:193.0 / 255.0, green:193.0 / 255.0, blue:193.0 / 255.0, alpha:1.0)
self.thumbDisabledTintColor = UIColor(red:174.0 / 255.0, green:174.0 / 255.0, blue:174.0 / 255.0, alpha:1.0)
self.trackDisabledTintColor = UIColor(red:203.0 / 255.0, green:203.0 / 255.0, blue:203.0 / 255.0, alpha:1.0)
self.track = UIView(frame: self.getTrackFrame())
self.track.backgroundColor = self.trackOnTintColor
self.track.layer.cornerRadius = min(self.track.frame.size.height, self.track.frame.size.width) / 2
self.addSubview(self.track)
self.switchThumb = UIButton(frame: self.getThumbFrame())
self.switchThumb.backgroundColor = self.thumbOnTintColor
self.switchThumb.layer.cornerRadius = self.switchThumb.frame.size.height / 2
self.switchThumb.layer.shadowOpacity = 0.5
self.switchThumb.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
self.switchThumb.layer.shadowColor = UIColor.black.cgColor
self.switchThumb.layer.shadowRadius = 2.0
self.addSubview(self.switchThumb)
// Add events for user action
self.switchThumb.addTarget(self, action: #selector(self.onTouchDown(btn:withEvent:)), for: UIControl.Event.touchDown)
self.switchThumb.addTarget(self, action: #selector(self.onTouchDragInside(btn:withEvent:)), for: UIControl.Event.touchDragInside)
self.switchThumb.addTarget(self, action: #selector(self.onTouchUpOutsideOrCanceled(btn:withEvent:)), for: UIControl.Event.touchUpOutside)
self.switchThumb.addTarget(self, action: #selector(self.onTouchUpOutsideOrCanceled(btn:withEvent:)), for: UIControl.Event.touchCancel)
self.switchThumb.addTarget(self, action: #selector(self.switchAreaTapped), for: UIControl.Event.touchUpInside)
let singleTap = UITapGestureRecognizer(target: self, action: #selector(self.switchAreaTapped))
self.addGestureRecognizer(singleTap)
self.setOn(on: self.isOn, animated: self.isRippleEnabled)
}
func updateUI() {
self.layoutSubviews()
self.track.frame = self.getTrackFrame()
self.track.layer.cornerRadius = min(self.track.frame.size.height, self.track.frame.size.width) / 2
self.switchThumb.frame = self.getThumbFrame()
self.switchThumb.layer.cornerRadius = self.switchThumb.frame.size.height / 2
self.setOn(on: self.isOn, animated: self.isRippleEnabled)
}
fileprivate func getTrackFrame() -> CGRect {
var trackFrame = self.bounds
trackFrame.size.height = (self.bounds.size.height - self.tarckEdgeInset.top - self.tarckEdgeInset.bottom)
let thumbWidth = (trackFrame.size.height + 10) / 2
trackFrame.size.width = frame.size.width - (self.tarckEdgeInset.left + self.tarckEdgeInset.right + thumbWidth)
trackFrame.origin.x = 0.0 + self.tarckEdgeInset.left + (thumbWidth / 2)
trackFrame.origin.y = (self.frame.size.height / 2) - (trackFrame.size.height / 2)
return trackFrame
}
fileprivate func getThumbFrame() -> CGRect {
var thumbFrame = CGRect.zero
thumbFrame.size.height = self.track.frame.size.height + 10
thumbFrame.size.width = thumbFrame.size.height
if isOn {
thumbFrame.origin.x = self.track.frame.maxX - (thumbFrame.size.width / 2)
thumbFrame.origin.y = (frame.size.height / 2) - (thumbFrame.size.height / 2)
} else {
thumbFrame.origin.x = self.track.frame.minX - (thumbFrame.size.width / 2)
thumbFrame.origin.y = (frame.size.height / 2) - (thumbFrame.size.height / 2)
}
return thumbFrame
}
//MARK: setter/getter
func setOn(on: Bool, animated: Bool) {
if on {
if animated {
// set on with animation
self.changeThumbStateONwithAnimation()
} else {
// set on without animation
self.changeThumbStateONwithoutAnimation()
}
} else {
if animated {
// set off with animation
self.changeThumbStateOFFwithAnimation()
} else {
// set off without animation
self.changeThumbStateOFFwithoutAnimation()
}
}
}
func setEnabled(enabled: Bool) {
super.isEnabled = enabled
// Animation for better transfer, better UX
UIView.animate(withDuration: 0.1) {
if enabled {
if self.isOn {
self.switchThumb.backgroundColor = self.thumbOnTintColor
self.track.backgroundColor = self.trackOnTintColor
} else {
self.switchThumb.backgroundColor = self.thumbOffTintColor
self.track.backgroundColor = self.trackOffTintColor
}
self.isEnabled = true
} else { // if disabled
self.switchThumb.backgroundColor = self.thumbDisabledTintColor
self.track.backgroundColor = self.trackDisabledTintColor
self.isEnabled = false
}
}
}
@objc func switchAreaTapped() {
self.changeThumbState()
}
func changeThumbState() {
if self.isOn {
self.changeThumbStateOFFwithAnimation()
} else {
self.changeThumbStateONwithAnimation()
}
if self.isRippleEnabled {
self.animateRippleEffect()
}
}
func changeThumbStateONwithAnimation() {
// switch movement animation
UIView.animate(withDuration: 0.15, delay: 0.05, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.switchThumb.frame = self.getThumbFrame()
if self.isEnabled {
self.switchThumb.backgroundColor = self.thumbOnTintColor
self.track.backgroundColor = self.trackOnTintColor
} else {
self.switchThumb.backgroundColor = self.thumbDisabledTintColor
self.track.backgroundColor = self.trackDisabledTintColor
}
self.isUserInteractionEnabled = false
}) { (finished) in
// change state to ON
if !self.isOn {
self.isOn = true // Expressly put this code here to change surely and send action correctly
self.sendActions(for: UIControl.Event.valueChanged)
}
// Bouncing effect: Move thumb a bit, for better UX
UIView.animate(withDuration: 0.15, animations: {
// Bounce to the position
self.switchThumb.frame = self.getThumbFrame()
}, completion: { (finished) in
self.isUserInteractionEnabled = true
})
}
}
func changeThumbStateOFFwithAnimation() {
// switch movement animation
UIView.animate(withDuration: 0.15, delay: 0.05, options: UIView.AnimationOptions.curveEaseInOut, animations: {
self.switchThumb.frame = self.getThumbFrame()
if self.isEnabled {
self.switchThumb.backgroundColor = self.thumbOffTintColor
self.track.backgroundColor = self.trackOffTintColor
} else {
self.switchThumb.backgroundColor = self.thumbDisabledTintColor
self.track.backgroundColor = self.trackDisabledTintColor
}
self.isUserInteractionEnabled = false
}) { (finished) in
// change state to OFF
if self.isOn {
self.isOn = false // Expressly put this code here to change surely and send action correctly
self.sendActions(for: UIControl.Event.valueChanged)
}
// Bouncing effect: Move thumb a bit, for better UX
UIView.animate(withDuration: 0.15, animations: {
// Bounce to the position
self.switchThumb.frame = self.getThumbFrame()
}, completion: { (finish) in
self.isUserInteractionEnabled = true
})
}
}
// Without animation
func changeThumbStateONwithoutAnimation() {
self.switchThumb.frame = self.getThumbFrame()
if self.isEnabled {
self.switchThumb.backgroundColor = self.thumbOnTintColor
self.track.backgroundColor = self.trackOnTintColor
} else {
self.switchThumb.backgroundColor = self.thumbDisabledTintColor
self.track.backgroundColor = self.trackDisabledTintColor
}
if !self.isOn {
self.isOn = true
self.sendActions(for: UIControl.Event.valueChanged)
}
}
func changeThumbStateOFFwithoutAnimation() {
self.switchThumb.frame = self.getThumbFrame()
if self.isEnabled {
self.switchThumb.backgroundColor = self.thumbOffTintColor
self.track.backgroundColor = self.trackOffTintColor
} else {
self.switchThumb.backgroundColor = self.thumbDisabledTintColor
self.track.backgroundColor = self.trackDisabledTintColor
}
if self.isOn {
self.isOn = false
self.sendActions(for: UIControl.Event.valueChanged)
}
}
// Initialize and appear ripple effect
func initializeRipple() {
// Ripple size is twice as large as switch thumb
let rippleScale : CGFloat = 2
var rippleFrame = CGRect.zero
rippleFrame.origin.x = -self.switchThumb.frame.size.width / (rippleScale * 2)
rippleFrame.origin.y = -self.switchThumb.frame.size.height / (rippleScale * 2)
rippleFrame.size.height = self.switchThumb.frame.size.height * rippleScale
rippleFrame.size.width = rippleFrame.size.height
let path = UIBezierPath.init(roundedRect: rippleFrame, cornerRadius: self.switchThumb.layer.cornerRadius*2)
// Set ripple layer attributes
rippleLayer = CAShapeLayer()
rippleLayer.path = path.cgPath
rippleLayer.frame = rippleFrame
rippleLayer.opacity = 0.2
rippleLayer.strokeColor = UIColor.clear.cgColor
rippleLayer.fillColor = self.rippleFillColor.cgColor
rippleLayer.lineWidth = 0
self.switchThumb.layer.insertSublayer(rippleLayer, below: self.switchThumb.layer)
}
func animateRippleEffect() {
// Create ripple layer
if rippleLayer == nil {
self.initializeRipple()
}
// Animation begins from here
rippleLayer?.opacity = 0.0
CATransaction.begin()
//remove layer after animation completed
CATransaction.setCompletionBlock {
self.rippleLayer?.removeFromSuperlayer()
self.rippleLayer = nil
}
// Scale ripple to the modelate size
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 0.5
scaleAnimation.toValue = 1.25
// Alpha animation for smooth disappearing
let alphaAnimation = CABasicAnimation(keyPath: "opacity")
alphaAnimation.fromValue = 0.4
alphaAnimation.toValue = 0
// Do above animations at the same time with proper duration
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, alphaAnimation]
animation.duration = 0.4
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
rippleLayer?.add(animation, forKey: nil)
CATransaction.commit()
// End of animation, then remove ripple layer
}
//MARK: - Event Actions
@objc func onTouchDown(btn: UIButton, withEvent event: UIEvent) {
if self.isRippleEnabled {
self.initializeRipple()
// Animate for appearing ripple circle when tap and hold the switch thumb
CATransaction.begin()
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 0.0
scaleAnimation.toValue = 1.0
let alphaAnimation = CABasicAnimation(keyPath:"opacity")
alphaAnimation.fromValue = 0
alphaAnimation.toValue = 0.2
// Do above animations at the same time with proper duration
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, alphaAnimation]
animation.duration = 0.4
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
rippleLayer?.add(animation, forKey: nil)
CATransaction.commit()
}
}
// Change thumb state when touchUPOutside action is detected
@objc func onTouchUpOutsideOrCanceled(btn: UIButton, withEvent event: UIEvent) {
if let touch = event.touches(for: btn)?.first {
let prevPos = touch.previousLocation(in: btn)
let pos = touch.location(in: btn)
let dX = pos.x - prevPos.x
//Get the new origin after this motion
let newXOrigin = btn.frame.origin.x + dX
if (newXOrigin > (self.frame.size.width - self.switchThumb.frame.size.width)/2) {
self.changeThumbStateONwithAnimation()
} else {
self.changeThumbStateOFFwithAnimation()
}
if self.isRippleEnabled {
self.animateRippleEffect()
}
}
}
@objc func onTouchDragInside(btn: UIButton, withEvent event:UIEvent) {
//This code can go awry if there is more than one finger on the screen
// if let touch = event.touches(for: btn)?.first {
//
// let prevPos = touch.previousLocation(in: btn)
// let pos = touch.location(in: btn)
// let dX = pos.x - prevPos.x
//
// //Get the original position of the thumb
// var thumbFrame = btn.frame
//
// thumbFrame.origin.x += dX
// //Make sure it's within two bounds
// thumbFrame.origin.x = min(thumbFrame.origin.x, thumbOnPosition)
// thumbFrame.origin.x = max(thumbFrame.origin.x, thumbOffPosition)
//
// //Set the thumb's new frame if need to
// if thumbFrame.origin.x != btn.frame.origin.x {
// btn.frame = thumbFrame
// }
// }
}
}
| mit | edbbb7e132e43d4b1ec0806a2350f58f | 37.578829 | 145 | 0.595306 | 4.835968 | false | false | false | false |
srn214/Floral | Floral/Pods/SwiftLocation/Sources/Support/CLLocationManager+Extras.swift | 1 | 3664 | //
// SwiftLocation - Efficient Location Tracking for iOS
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
import Foundation
import CoreLocation
public extension CLLocationManager {
enum AuthorizationMode: CustomStringConvertible {
case viaInfoPlist
case whenInUse
case always
public var description: String {
switch self {
case .viaInfoPlist: return "viaInfoPlist"
case .whenInUse: return "whenInUse"
case .always: return "always"
}
}
}
/// Return `true` if host application has background location capabilities enabled
static var hasBackgroundCapabilities: Bool {
guard let capabilities = Bundle.main.infoDictionary?["UIBackgroundModes"] as? [String] else {
return false
}
return capabilities.contains("location")
}
internal func requestAuthorizationIfNeeded(_ mode: AuthorizationMode) {
switch mode {
case .viaInfoPlist:
requestViaPList()
case .whenInUse:
self.requestWhenInUseAuthorization()
case .always:
self.requestAlwaysAuthorization()
}
}
private func requestViaPList() {
// Determines which level of permissions to request based on which description key is present in your app's Info.plist
// If you provide values for both description keys, the more permissive "Always" level is requested.
let iOSVersion = floor(NSFoundationVersionNumber)
let isiOS7To10 = (iOSVersion >= NSFoundationVersionNumber_iOS_7_1 && Int32(iOSVersion) <= NSFoundationVersionNumber10_11_Max)
guard LocationManager.state == .undetermined else {
return // no need to ask
}
var canRequestAlways = false
var canRequestWhenInUse = false
if isiOS7To10 {
canRequestAlways = Bundle.main.object(forInfoDictionaryKey: "NSLocationAlwaysUsageDescription") != nil
canRequestWhenInUse = Bundle.main.object(forInfoDictionaryKey: "NSLocationWhenInUseUsageDescription") != nil
} else {
canRequestAlways = Bundle.main.object(forInfoDictionaryKey: "NSLocationAlwaysAndWhenInUseUsageDescription") != nil
canRequestWhenInUse = Bundle.main.object(forInfoDictionaryKey: "NSLocationWhenInUseUsageDescription") != nil
}
if canRequestAlways {
requestAlwaysAuthorization()
} else if canRequestWhenInUse {
requestWhenInUseAuthorization()
} else {
if isiOS7To10 {
// At least one of the keys NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription
// MUST be present in the Info.plist file to use location services on iOS 8+.
assert(canRequestAlways || canRequestWhenInUse, "To use location services in iOS 8+, your Info.plist must provide a value for either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription.")
} else {
// Key NSLocationAlwaysAndWhenInUseUsageDescription MUST be present in the Info.plist file
// to use location services on iOS 11+.
assert(canRequestAlways, "To use location services in iOS 11+, your Info.plist must provide a value for NSLocationAlwaysAndWhenInUseUsageDescription.")
}
}
}
}
| mit | 6af5f6f5ae4804285ba274120c9cbb8c | 41.103448 | 223 | 0.656839 | 5.533233 | false | false | false | false |
voyages-sncf-technologies/Collor | Collor/Classes/CollectionSectionDescriptable.swift | 1 | 5030 | //
// CollectionSectionDescribable.swift
// Collor
//
// Created by Guihal Gwenn on 16/03/17.
// Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved.
//
//
import Foundation
import UIKit
import ObjectiveC
private struct AssociatedKeys {
static var SectionIndex = "collor_SectionIndex"
static var SectionBuilder = "collor_SectionBuilder"
static var SectionBuilderSupp = "collor_SectionBuilderSupp"
static var SectionCells = "collor_SectionCells"
static var SectionSupplementaryViews = "collor_SectionSupplementaryViews"
}
public protocol CollectionSectionDescribable : Identifiable {
func sectionInset(_ collectionView: UICollectionView) -> UIEdgeInsets
func minimumInteritemSpacing(_ collectionView: UICollectionView, layout: UICollectionViewFlowLayout) -> CGFloat
func minimumLineSpacing(_ collectionView: UICollectionView, layout: UICollectionViewFlowLayout) -> CGFloat
}
public typealias SectionBuilderClosure = (inout [CollectionCellDescribable]) -> Void
public typealias SectionBuilderObjectClosure = (SectionBuilder) -> Void
public class SectionBuilder {
public var cells: [CollectionCellDescribable] = []
public internal(set) var supplementaryViews: [String:[CollectionSupplementaryViewDescribable]] = [:]
public func add(supplementaryView: CollectionSupplementaryViewDescribable, kind: String) {
if var viewsForKind = supplementaryViews[kind] {
viewsForKind.append(supplementaryView)
supplementaryViews[kind] = viewsForKind
} else {
supplementaryViews[kind] = [supplementaryView]
}
}
}
// default implementation CollectionSectionDescribable
public extension CollectionSectionDescribable {
func minimumInteritemSpacing(_ collectionView:UICollectionView, layout: UICollectionViewFlowLayout) -> CGFloat {
return layout.minimumInteritemSpacing
}
func minimumLineSpacing(_ collectionView: UICollectionView, layout: UICollectionViewFlowLayout) -> CGFloat {
return layout.minimumLineSpacing
}
@discardableResult func reloadSection(_ builderClosure:@escaping (inout [CollectionCellDescribable]) -> Void) -> Self {
self.builder = builderClosure
cells.removeAll()
supplementaryViews.removeAll()
builderClosure(&cells)
return self
}
@discardableResult func reload(_ builder:@escaping (SectionBuilder) -> Void) -> Self {
self.builderObject = builder
cells.removeAll()
supplementaryViews.removeAll()
let builderObject = SectionBuilder()
builder(builderObject)
cells = builderObject.cells
supplementaryViews = builderObject.supplementaryViews
return self
}
}
public extension CollectionSectionDescribable {
func uid(for cell:CollectionCellDescribable) -> String? {
guard let sectionUID = _uid, let cellUID = cell._uid else {
return nil
}
return "\(sectionUID)/\(cellUID)"
}
}
extension CollectionSectionDescribable {
public internal(set) var index: Int? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.SectionIndex) as? Int
}
set {
objc_setAssociatedObject( self, &AssociatedKeys.SectionIndex, newValue as Int?, .OBJC_ASSOCIATION_COPY)
}
}
var builder: SectionBuilderClosure? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.SectionBuilder) as? SectionBuilderClosure
}
set {
objc_setAssociatedObject( self, &AssociatedKeys.SectionBuilder, newValue as SectionBuilderClosure?, .OBJC_ASSOCIATION_COPY)
}
}
var builderObject: SectionBuilderObjectClosure? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.SectionBuilderSupp) as? SectionBuilderObjectClosure
}
set {
objc_setAssociatedObject( self, &AssociatedKeys.SectionBuilderSupp, newValue as SectionBuilderObjectClosure?, .OBJC_ASSOCIATION_COPY)
}
}
public internal(set) var cells: [CollectionCellDescribable] {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.SectionCells) as? [CollectionCellDescribable] ?? [CollectionCellDescribable]()
}
set {
objc_setAssociatedObject( self, &AssociatedKeys.SectionCells, newValue as [CollectionCellDescribable], .OBJC_ASSOCIATION_COPY)
}
}
public internal(set) var supplementaryViews: [String:[CollectionSupplementaryViewDescribable]] {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.SectionSupplementaryViews) as? [String:[CollectionSupplementaryViewDescribable]] ?? [String:[CollectionSupplementaryViewDescribable]]()
}
set {
objc_setAssociatedObject( self, &AssociatedKeys.SectionSupplementaryViews, newValue as [String:[CollectionSupplementaryViewDescribable]], .OBJC_ASSOCIATION_COPY)
}
}
}
| bsd-3-clause | fb5b4af232bd61691aae8e4d536b1ab4 | 38.296875 | 201 | 0.706362 | 5.33404 | false | false | false | false |
cuappdev/podcast-ios | Recast/iTunesPodcasts/Models/RSS/mapCharacters.swift | 1 | 9757 | //
// RSSFeed + mapCharacters.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable function_body_length
extension Podcast {
/// Maps the characters in the specified string to the `Podcast` model.
///
/// - Parameters:
/// - string: The string to map to the model.
/// - path: The path of feed's element.
func map(_ string: String, for path: RSSPath) {
switch path {
case .rssChannelTitle:
setValue(self.title?.appending(string) ?? string, for: .title)
case .rssChannelLink:
setValue(self.link?.appending(string) ?? string, for: .link)
case .rssChannelDescription:
setValue(self.descriptionText?.appending(string) ?? string, for: .descriptionText)
case .rssChannelLanguage:
setValue(self.language?.appending(string) ?? string, for: .language)
case .rssChannelCopyright:
setValue(self.copyright?.appending(string) ?? string, for: .copyright)
case .rssChannelManagingEditor:
setValue(self.managingEditor?.appending(string), for: .managingEditor)
case .rssChannelWebMaster:
setValue(self.webMaster?.appending(string) ?? string, for: .webMaster)
case .rssChannelPubDate:
setValue(string.toPermissiveDate()! as NSDate, for: .pubDate)
case .rssChannelLastBuildDate:
setValue(string.toPermissiveDate()! as NSDate, for: .lastBuildDate)
case .rssChannelCategory:
setValue(self.categories?.append(string), for: .categories)
case .rssChannelGenerator:
setValue(self.generator?.appending(string) ?? string, for: .generator)
case .rssChannelDocs:
setValue(self.docs?.appending(string) ?? string, for: .docs)
case .rssChannelRating:
setValue(self.rating?.appending(string) ?? string, for: .rating)
case .rssChannelTTL:
setValue(Int64(string), for: .ttl)
case .rssChannelImageURL:
setValue(NSURL(string: string), for: .image)
case .rssChannelTextInputTitle:
self.textInput?.setValue(self.textInput?.title?.appending(string) ?? string, for: .title)
case .rssChannelTextInputDescription:
self.textInput?.setValue(self.textInput?.descriptionText?.appending(string) ?? string, for: .descriptionText)
case .rssChannelTextInputName:
self.textInput?.setValue(self.textInput?.name?.appending(string) ?? string, for: .name)
case .rssChannelTextInputLink:
self.textInput?.setValue(self.textInput?.link?.appending(string) ?? string, for: .link)
case .rssChannelSkipHoursHour:
guard let hour = Int64(string), 0...23 ~= hour else { return }
var skipHours = self.skipHours
skipHours?.append(hour)
setValue(skipHours ?? [], for: .skipHours)
case .rssChannelSkipDaysDay:
self.rawSkipDays?.append(string)
case .rssChannelItemTitle:
let items = self.items?.array as? [Episode]
items?.last?.setValue(items?.last?.title?.appending(string) ?? string, for: .title)
case .rssChannelItemLink:
let items = self.items?.array as? [Episode]
items?.last?.setValue(items?.last?.link?.appending(string) ?? string, for: .link)
case .rssChannelItemDescription:
let items = self.items?.array as? [Episode]
items?.last?.setValue(items?.last?.descriptionText?.appending(string) ?? string, for: .descriptionText)
case .rssChannelItemAuthor:
let items = self.items?.array as? [Episode]
items?.last?.setValue(items?.last?.author?.appending(string) ?? string, for: .author)
case .rssChannelItemCategory:
let items = self.items?.array as? [Episode]
var categories = items?.last?.categories
categories?.append(string)
items?.last?.setValue(categories, for: .categories)
case .rssChannelItemComments:
let items = self.items?.array as? [Episode]
items?.last?.setValue(items?.last?.comments?.appending(string) ?? string, for: .comments)
case .rssChannelItemGUID:
let items = self.items?.array as? [Episode]
items?.last?.setValue(string, for: .guid)
case .rssChannelItemPubDate:
let items = self.items?.array as? [Episode]
items?.last?.setValue(string.toPermissiveDate() as NSDate? ?? NSDate(), for: .pubDate)
case .rssChannelItemSource:
let items = self.items?.array as? [Episode]
items?.last?.source?.setValue(items?.last?.source?.value?.appending(string) ?? string, for: .value)
case .rssChannelItemContentEncoded:
let items = self.items?.array as? [Episode]
items?.last?.setValue(string, for: .content)
case .rssChannelItunesAuthor:
self.iTunes?.setValue(self.iTunes?.author?.appending(string) ?? string, for: .author)
case .rssChannelItunesBlock:
self.iTunes?.setValue(self.iTunes?.block?.appending(string) ?? string, for: .block)
case .rssChannelItunesExplicit:
self.iTunes?.setValue(string.toBool() || string.lowercased() == "explicit", for: .explicit)
case .rssChannelItunesComplete:
self.iTunes?.setValue(self.iTunes?.complete?.appending(string) ?? string, for: .complete)
case .rssChannelItunesNewFeedURL:
self.iTunes?.setValue(self.iTunes?.newFeedUrl?.appending(string) ?? string, for: .newFeedUrl)
case .rssChannelItunesOwnerName:
self.iTunes?.owner?.setValue(self.iTunes?.owner?.name?.appending(string) ?? string, for: .name)
case .rssChannelItunesOwnerEmail:
self.iTunes?.owner?.setValue(self.iTunes?.owner?.email?.appending(string) ?? string, for: .email)
case .rssChannelItunesSubtitle:
self.iTunes?.setValue(self.iTunes?.subtitle?.appending(string) ?? string, for: .subtitle)
case .rssChannelItunesSummary:
self.iTunes?.setValue(self.iTunes?.summary?.appending(string) ?? string, for: .summary)
case .rssChannelItunesKeywords:
self.iTunes?.setValue(self.iTunes?.keywords?.appending(string) ?? string, for: .keywords)
case .rssChannelItunesType:
self.iTunes?.setValue(string, for: .podcastType)
case .rssChannelItemItunesAuthor:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(items?.last?.iTunes?.author?.appending(string) ?? string, for: .author)
case .rssChannelItemItunesBlock:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(items?.last?.iTunes?.block?.appending(string) ?? string, for: .block)
case .rssChannelItemItunesDuration:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(string.toDuration() ?? 0, for: .duration)
case .rssChannelItemItunesExplicit:
self.iTunes?.setValue(string.toBool() || string.lowercased() == "explicit", for: .explicit)
case .rssChannelItemItunesIsClosedCaptioned:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(string.lowercased() == "yes", for: .isClosedCaptioned)
case .rssChannelItemItunesSubtitle:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(items?.last?.iTunes?.subtitle?.appending(string) ?? string, for: .subtitle)
case .rssChannelItemItunesSummary:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(items?.last?.iTunes?.summary?.appending(string) ?? string, for: .summary)
case .rssChannelItemItunesKeywords:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(items?.last?.iTunes?.keywords?.appending(string) ?? string, for: .keywords)
case .rssChannelItemItunesEpisodeType:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(string, for: .episodeType)
case .rssChannelItemItunesSeason:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(Int64(string), for: .season)
case .rssChannelItemItunesEpisode:
let items = self.items?.array as? [Episode]
items?.last?.iTunes?.setValue(Int64(string), for: .episodeNumber)
default: break
}
}
}
| mit | 5ea70284152d1fa5f99b436beecc4537 | 55.726744 | 121 | 0.65225 | 4.232972 | false | false | false | false |
rhodgkins/UIView-IBInspectable | Tests/UIView+IBInspectableTests/UIView_IBInspectableTests.swift | 1 | 5301 | //
// UIView_IBInspectableTests.swift
// UIView+IBInspectableTests
//
// Created by Richard Hodgkins on 15/11/2014.
// Copyright (c) 2014 Rich H. All rights reserved.
//
import UIKit
import XCTest
import UIView_IBInspectable
struct TestComparison {
// Initial values are UIView defaults
var cornerRadius: Double = 0
var borderWidth: Double = 0
var borderColor: UIColor? = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
var shadowColor: UIColor? = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
var shadowOpacity: Float = 0
var shadowOffset: CGSize = CGSize(width: 0, height: -3)
var shadowRadius: Double = 3
func assert(actual: UIView?)
{
XCTAssertNotNil(actual, "Nil view")
if let view = actual {
XCTAssertEqual(view.cornerRadius, cornerRadius, "Incorrect corner radius")
XCTAssertEqual(view.borderWidth, borderWidth, "Incorrect border width")
if let color = borderColor {
XCTAssertEqual(view.borderColor!, color, "Incorrect border color")
} else {
XCTAssertNil(view.borderColor, "Border color should not be set")
}
if let color = shadowColor {
XCTAssertEqual(view.shadowColor!, color, "Incorrect shadow color")
} else {
XCTAssertNil(view.shadowColor, "Shadow color should not be set")
}
XCTAssertEqual(view.shadowOpacity, shadowOpacity, "Incorrect shadow opacity")
XCTAssertEqual(view.shadowOffset, shadowOffset, "Incorrect shadow offset")
XCTAssertEqual(view.shadowRadius, shadowRadius, "Incorrect shadow radius")
}
}
}
class IBInspectables_FromStoryboardTests: XCTestCase {
var viewController: ViewController! {
return UIApplication.sharedApplication().delegate?.window!?.rootViewController! as? ViewController
}
func testNone() {
TestComparison().assert(viewController.noneView)
}
func testCornerRadius() {
var test = TestComparison()
test.cornerRadius = 10
test.assert(viewController.cornerRadiusView)
}
func testBorderWidth() {
var test = TestComparison()
test.borderWidth = 20
test.assert(viewController.borderWidthView)
}
func testBorderColor() {
var test = TestComparison()
test.borderColor = UIColor.redColor()
test.assert(viewController.borderColorView)
}
func testShadowColor() {
var test = TestComparison()
test.shadowColor = UIColor.greenColor()
test.assert(viewController.shadowColorView)
}
func testShadowOpacity() {
var test = TestComparison()
test.shadowOpacity = 0.5
test.assert(viewController.shadowOpacityView)
}
func testShadowOffset() {
var test = TestComparison()
test.shadowOffset = CGSize(width: 100, height: 0)
test.assert(viewController.shadowOffsetView)
}
func testShadowRadius() {
var test = TestComparison()
test.shadowRadius = 30
test.assert(viewController.shadowRadiusView)
}
func testAll() {
var test = TestComparison()
test.cornerRadius = 5
test.borderWidth = 10
test.borderColor = UIColor.blueColor()
test.shadowColor = UIColor.cyanColor()
test.shadowOpacity = 0.75
test.shadowOffset = CGSize(width: 20, height: 25)
test.shadowRadius = 30
test.assert(viewController.allView)
}
}
class IBInspectables_PropertyTests: XCTestCase {
var view: UIView?
override func setUp() {
super.setUp()
view = UIView()
}
func testCornerRadius() {
view?.cornerRadius = 40
var test = TestComparison()
test.cornerRadius = 40
test.assert(view)
}
func testBorderWidth() {
view?.borderWidth = 400
var test = TestComparison()
test.borderWidth = 400
test.assert(view)
}
func testBorderColor() {
view?.borderColor = UIColor.orangeColor()
var test = TestComparison()
test.borderColor = UIColor.orangeColor()
test.assert(view)
view?.borderColor = nil
test = TestComparison()
test.borderColor = nil
test.assert(view)
}
func testShadowColor() {
view?.shadowColor = UIColor.purpleColor()
var test = TestComparison()
test.shadowColor = UIColor.purpleColor()
test.assert(view)
view?.shadowColor = nil
test = TestComparison()
test.shadowColor = nil
test.assert(view)
}
func testShadowOpacity() {
view?.shadowOpacity = 0.05
var test = TestComparison()
test.shadowOpacity = 0.05
test.assert(view)
}
func testShadowOffset() {
view?.shadowOffset = CGSize(width: 100, height: 100)
var test = TestComparison()
test.shadowOffset = CGSize(width: 100, height: 100)
test.assert(view)
}
func testShadowRadius() {
view?.shadowRadius = 30
var test = TestComparison()
test.shadowRadius = 30
test.assert(view)
}
}
| mit | c7c55b282e0afb140b16b882bb01e6b9 | 28.287293 | 106 | 0.611583 | 4.858845 | false | true | false | false |
sugawaray/tools | toolsTests/CtlDuringCmdTests.swift | 1 | 907 | //
// CtlDuringCmdTests.swift
// tools
//
// Created by Yutaka Sugawara on 2016/10/15.
// Copyright © 2016 Yutaka Sugawara. All rights reserved.
//
import XCTest
class CtlDuringCmdTests: XCTestCase {
override func setUp() {
super.setUp()
o = Ctl()
}
override func tearDown() {
o!.cleanup()
super.tearDown()
}
func testPassInputToRunningCmd() {
var c = Cmd(id: Cmdid.shcmd.rawValue, astr: Sh.dummycmd)
o!.procc(c)
o!.proc()
c = Cmd(id: Cmdid.shcmd.rawValue, astr: "input 1:\n")
o!.procc(c)
var ts = timespec()
ts.tv_sec = 0
ts.tv_nsec = 10000000
while (o!.sh.getdummycmdinput().compare("") == ComparisonResult.orderedSame) {
nanosleep(&ts, nil)
}
XCTAssertEqual("input 1:", o!.sh.getdummycmdinput())
}
var o: Ctl?
}
| gpl-2.0 | d53b34d87e2bf59fc56ea448c3f73c1e | 21.65 | 86 | 0.550773 | 3.484615 | false | true | false | false |
rogeruiz/MacPin | modules/MacPin/WebViewDelegates.swift | 2 | 10901 | /// MacPin WebViewDelegates
///
/// Handle modal & interactive webview prompts and errors
// need a <input type="file"> picker & uploader protocol delegate
// https://github.com/WebKit/webkit/commit/a12c1fc70fa906a39a0593aa4124f24427e232e7
// https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW2
// https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSessionUploadTask_class/index.html
//and how about downloads? right now they are passed to safari
// https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/_WKDownloadDelegate.h
// https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/DownloadClient.mm
// lookup table for NSError codes gotten while browsing
// http://nshipster.com/nserror/#nsurlerrordomain-&-cfnetworkerrors
// https://github.com/WebKit/webkit/blob/master/Source/WebKit/mac/Misc/WebKitErrors.h
// https://github.com/WebKit/webkit/blob/master/Source/WebKit2/Shared/API/c/WKErrorRef.h
// overriding right-click context menu: http://stackoverflow.com/a/28981319/3878712
#if os(iOS)
// WebKitError* not defined in iOS. Bizarre.
let WebKitErrorDomain = "WebKitErrorDomain"
#endif
import WebKit
extension AppScriptRuntime: WKScriptMessageHandler {
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let webView = message.webView as? MPWebView {
//called from JS: webkit.messageHandlers.<messsage.name>.postMessage(<message.body>);
switch message.name {
//case "getGeolocation":
// Geolocator.sendLocationEvent(webView) // add this webview as a one-time subscriber
//case "watchGeolocation":
// Geolocator.subscribeToLocationEvents(webView) // add this webview as a continuous subscriber
//case "unwatchGeolocation":
// Geolocator.unsubscribeFromLocationEvents(webView) // remove this webview from subscribers
case "MacPinPollStates": // direct poll. app.js needs to authorize this handler per tab
//FIXME: should iterate message.body's [varnames] to send events for
webView.evaluateJavaScript( //for now, send an omnibus event with all varnames values
"window.dispatchEvent(new window.CustomEvent('MacPinWebViewChanged',{'detail':{'transparent': \(webView.transparent)}})); ",
completionHandler: nil)
default:
true // no-op
}
if jsdelegate.hasProperty(message.name) {
warn("forwarding webkit.messageHandlers.\(message.name) to jsdelegate.\(message.name)(webview,msg)")
jsdelegate.invokeMethod(message.name, withArguments: [webView, message.body])
} else {
warn("unhandled postMessage! \(message.name)() -> \(message.body)")
}
}
}
}
extension WebViewController: WKUIDelegate { } // javascript prompts, implemented per-platform
extension WebViewController: WKNavigationDelegate {
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if let url = webView.URL {
warn("'\(url)'")
// check url against regex'd keys of MatchedAddressOptions
// or just call a JS delegate to do that?
}
#if os(iOS)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
#endif
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.URL
if let url = url, scheme = url.scheme {
switch scheme {
case "data": fallthrough
case "file": fallthrough
case "about": fallthrough
case "javascript": fallthrough
case "http": fallthrough
case "https": break
default: //weird protocols, or app launches like itmss:
askToOpenURL(url)
decisionHandler(.Cancel)
}
if jsdelegate.tryFunc("decideNavigationForURL", url.description) { decisionHandler(.Cancel); return }
switch navigationAction.navigationType {
case .LinkActivated:
#if os(OSX)
let mousebtn = navigationAction.buttonNumber
let modkeys = navigationAction.modifierFlags
if (modkeys & NSEventModifierFlags.AlternateKeyMask).rawValue != 0 { NSWorkspace.sharedWorkspace().openURL(url) } //alt-click
else if (modkeys & NSEventModifierFlags.CommandKeyMask).rawValue != 0 { popup(MPWebView(url: url, agent: webView._customUserAgent)) } //cmd-click
else if !jsdelegate.tryFunc("decideNavigationForClickedURL", url.description) { // allow override from JS
if navigationAction.targetFrame != nil && mousebtn == 1 { fallthrough } // left-click on in_frame target link
popup(MPWebView(url: url, agent: webView._customUserAgent)) // middle-clicked, or out of frame target link
}
#elseif os(iOS)
if !jsdelegate.tryFunc("decideNavigationForClickedURL", url.description) { // allow override from JS
if navigationAction.targetFrame != nil { fallthrough } // tapped in_frame target link
popup(MPWebView(url: url, agent: webView._customUserAgent)) // out of frame target link
}
#endif
warn("-> .Cancel -- user clicked <a href=\(url) target=_blank> or middle-clicked: opening externally")
decisionHandler(.Cancel)
case .FormSubmitted: fallthrough
case .BackForward: fallthrough
case .Reload: fallthrough
case .FormResubmitted: fallthrough
case .Other: fallthrough
default: decisionHandler(.Allow)
}
} else {
// invalid url? should raise error
warn("navType:\(navigationAction.navigationType.rawValue) sourceFrame:(\(navigationAction.sourceFrame?.request.URL)) -> \(url)")
decisionHandler(.Cancel)
}
}
func webView(webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
if let url = webView.URL { warn("~> [\(url)]") }
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { //error returned by webkit when loading content
if let url = webView.URL {
warn("'\(url)' -> `\(error.localizedDescription)` [\(error.domain)] [\(error.code)] `\(error.localizedFailureReason ?? String())` : \(error.userInfo)")
if error.domain == NSURLErrorDomain && error.code != NSURLErrorCancelled && !webView.loading { // dont catch on stopLoading() and HTTP redirects
displayError(error, self)
}
}
}
func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
//content starts arriving...I assume <body> has materialized in the DOM?
(webView as? MPWebView)?.scrapeIcon()
}
func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) {
let mime = navigationResponse.response.MIMEType!
let url = navigationResponse.response.URL!
let fn = navigationResponse.response.suggestedFilename!
if jsdelegate.tryFunc("decideNavigationForMIME", mime, url.description) { decisionHandler(.Cancel); return } //FIXME perf hit?
if navigationResponse.canShowMIMEType {
decisionHandler(.Allow)
} else {
warn("cannot render requested MIME-type:\(mime) @ \(url)")
if !jsdelegate.tryFunc("handleUnrenderableMIME", mime, url.description, fn) { askToOpenURL(url) }
decisionHandler(.Cancel)
}
}
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) { //error during commited main frame navigation
// like server-issued error Statuses with no page content
if let url = webView.URL {
warn("[\(url)] -> `\(error.localizedDescription)` [\(error.domain)] [\(error.code)] `\(error.localizedFailureReason ?? String())` : \(error.userInfo)")
if error.domain == WebKitErrorDomain && error.code == 204 { askToOpenURL(url) } // `Plug-in handled load!` video/mp4 kWKErrorCodePlugInWillHandleLoad
if error.domain == NSURLErrorDomain && error.code != NSURLErrorCancelled { // dont catch on stopLoading() and HTTP redirects
displayError(error, self)
}
}
#if os(iOS)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
#endif
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
warn(webView.description)
//let title = webView.title ?? String()
//let url = webView.URL ?? NSURL(string:"")!
//warn("\"\(title)\" [\(url)]")
//scrapeIcon(webView)
#if os(iOS)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
#endif
}
func webView(webView: WKWebView, createWebViewWithConfiguration configuration: WKWebViewConfiguration, forNavigationAction navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures) -> WKWebView? {
// called via JS:window.open()
// https://developer.mozilla.org/en-US/docs/Web/API/window.open
// https://developer.apple.com/library/prerelease/ios/documentation/WebKit/Reference/WKWindowFeatures_Ref/index.html
let srcurl = navigationAction.sourceFrame?.request.URL ?? NSURL(string:String())!
let openurl = navigationAction.request.URL ?? NSURL(string:String())!
let tgt = (navigationAction.targetFrame == nil) ? NSURL(string:String())! : navigationAction.targetFrame!.request.URL
let tgtdom = navigationAction.targetFrame?.request.mainDocumentURL ?? NSURL(string:String())!
//^tgt is given as a string in JS and WKWebView synthesizes a WKFrameInfo from it _IF_ it matches an iframe title in the DOM
// otherwise == nil
// RDAR? would like the tgt string to be passed here
warn("<\(srcurl)>: window.open(\(openurl), \(tgt))")
if jsdelegate.tryFunc("decideWindowOpenForURL", openurl.description) { return nil }
let wv = MPWebView(config: configuration, agent: webView._customUserAgent)
popup(wv)
#if os(OSX)
if (windowFeatures.allowsResizing ?? 0) == 1 {
if let window = view.window {
var newframe = CGRect(
x: CGFloat(windowFeatures.x ?? window.frame.origin.x as NSNumber),
y: CGFloat(windowFeatures.y ?? window.frame.origin.y as NSNumber),
width: CGFloat(windowFeatures.width ?? window.frame.size.width as NSNumber),
height: CGFloat(windowFeatures.height ?? window.frame.size.height as NSNumber)
)
if !webView.inFullScreenMode && (window.styleMask & NSFullScreenWindowMask == 0) {
warn("resizing window to match window.open() size parameters passed: origin,size[\(newframe)]")
window.setFrame(newframe, display: true)
}
}
}
#endif
//if !tgt.description.isEmpty { evalJS("window.name = '\(tgt)';") }
if !openurl.description.isEmpty { wv.gotoURL(openurl) } // this should be deferred with a timer so all chained JS calls on the window.open() instanciation can finish executing
return wv // window.open() -> Window()
//return nil //window.open() -> undefined
}
func _webViewWebProcessDidCrash(webView: WKWebView) {
warn("reloading page")
webView.reload()
}
}
| gpl-3.0 | ae96a4b83d04c3d9903ff95e75adbee9 | 47.234513 | 177 | 0.736263 | 4.056941 | false | false | false | false |
slepcat/mint | MINT/ArgumentCellViews.swift | 1 | 2995 | //
// ArgumentCellViews.swift
// MINT
//
// Created by NemuNeko on 2015/04/19.
// Copyright (c) 2015年 Taizo A. All rights reserved.
//
import Foundation
import Cocoa
class MintOperandCellView : NSTableCellView, NSTextFieldDelegate {
weak var controller: MintLeafViewController!
var uid : UInt = 0
override func awakeFromNib() {
self.textField?.delegate = self
self.register(forDraggedTypes: ["com.mint.mint.returnLeafID", "com.mint.mint.referenceLeafID"])
}
// 'MintArgumentButton just show argument list. Drop will be catched by 'MintArgumentCell'
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
switch sender.draggingSourceOperationMask() {
case NSDragOperation.link:
if controller.isLinkReqAcceptable() {
return NSDragOperation.link
}
default:
break
}
return []
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
let pboad = sender.draggingPasteboard()
let pbitems = pboad.readObjects(forClasses: [NSPasteboardItem.self], options: nil)
if let item = pbitems?.last as? NSPasteboardItem {
// pasteboardItemDataProvider is called when below line excuted.
// but not reflect to return value. API bug??
// After excution of the line, returnLeafID become available.
Swift.print(item.string(forType: "com.mint.mint.returnLeafID") ?? "nil", terminator: "\n")
Swift.print(item.string(forType: "com.mint.mint.referenceLeafID") ?? "nil", terminator: "\n")
}
switch sender.draggingSourceOperationMask() {
case NSDragOperation.link:
if let leafIDstr = pboad.string(forType: "com.mint.mint.returnLeafID") {
let leafID = NSString(string: leafIDstr).intValue
controller.acceptLinkFrom(UInt(leafID), toArg: uid)
return true
} else if let leafIDstr = pboad.string(forType: "com.mint.mint.referenceLeafID") {
let leafID = NSString(string: leafIDstr).intValue
controller.acceptRefFrom(UInt(leafID), toArg: uid)
return true
}
default: //anything else will be failed
return false
}
return false
}
override func controlTextDidEndEditing(_ obj: Notification) {
Swift.print("cell value edited (id: \(uid))", terminator: "\n")
let row = controller.operandList.row(for: self)
if let newvalue = self.textField?.stringValue {
controller.operand(uid, valueDidEndEditing: newvalue, atRow: row)
}
}
}
class MintRmOpdCellView : MintOperandCellView {
@IBOutlet weak var rmbutton : NSButton!
@IBAction func remove(_ sender: AnyObject) {
controller.remove(uid)
}
}
| gpl-3.0 | f158d90d5a38b47d945af605d01cedbd | 33.802326 | 105 | 0.614434 | 4.5625 | false | false | false | false |
varunrathi28/UserTracker | Pods/Polyline/Polyline/Polyline.swift | 1 | 13288 | // Polyline.swift
//
// Copyright (c) 2015 Raphaël Mor
//
// 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 CoreLocation
// MARK: - Public Classes -
/// This class can be used for :
///
/// - Encoding an [CLLocation] or a [CLLocationCoordinate2D] to a polyline String
/// - Decoding a polyline String to an [CLLocation] or a [CLLocationCoordinate2D]
/// - Encoding / Decoding associated levels
///
/// it is aims to produce the same results as google's iOS sdk not as the online
/// tool which is fuzzy when it comes to rounding values
///
/// it is based on google's algorithm that can be found here :
///
/// :see: https://developers.google.com/maps/documentation/utilities/polylinealgorithm
public struct Polyline {
/// The array of coordinates (nil if polyline cannot be decoded)
public let coordinates: [CLLocationCoordinate2D]?
/// The encoded polyline
public let encodedPolyline: String
/// The array of levels (nil if cannot be decoded, or is not provided)
public let levels: [UInt32]?
/// The encoded levels (nil if cannot be encoded, or is not provided)
public let encodedLevels: String?
/// The array of location (computed from coordinates)
public var locations: [CLLocation]? {
return self.coordinates.map(toLocations)
}
// MARK: - Public Methods -
/// This designated initializer encodes a `[CLLocationCoordinate2D]`
///
/// - parameter coordinates: The `Array` of `CLLocationCoordinate2D` that you want to encode
/// - parameter levels: The optional `Array` of levels that you want to encode (default: `nil`)
/// - parameter precision: The precision used for encoding (default: `1e5`)
public init(coordinates: [CLLocationCoordinate2D], levels: [UInt32]? = nil, precision: Double = 1e5) {
self.coordinates = coordinates
self.levels = levels
encodedPolyline = encodeCoordinates(coordinates, precision: precision)
encodedLevels = levels.map(encodeLevels)
}
/// This designated initializer decodes a polyline `String`
///
/// - parameter encodedPolyline: The polyline that you want to decode
/// - parameter encodedLevels: The levels that you want to decode (default: `nil`)
/// - parameter precision: The precision used for decoding (default: `1e5`)
public init(encodedPolyline: String, encodedLevels: String? = nil, precision: Double = 1e5) {
self.encodedPolyline = encodedPolyline
self.encodedLevels = encodedLevels
coordinates = decodePolyline(encodedPolyline, precision: precision)
levels = self.encodedLevels.flatMap(decodeLevels)
}
/// This init encodes a `[CLLocation]`
///
/// - parameter locations: The `Array` of `CLLocation` that you want to encode
/// - parameter levels: The optional array of levels that you want to encode (default: `nil`)
/// - parameter precision: The precision used for encoding (default: `1e5`)
public init(locations: [CLLocation], levels: [UInt32]? = nil, precision: Double = 1e5) {
let coordinates = toCoordinates(locations)
self.init(coordinates: coordinates, levels: levels, precision:precision)
}
}
// MARK: - Public Functions -
/// This function encodes an `[CLLocationCoordinate2D]` to a `String`
///
/// - parameter coordinates: The `Array` of `CLLocationCoordinate2D` that you want to encode
/// - parameter precision: The precision used to encode coordinates (default: `1e5`)
///
/// - returns: A `String` representing the encoded Polyline
public func encodeCoordinates(_ coordinates: [CLLocationCoordinate2D], precision: Double = 1e5) -> String {
var previousCoordinate = IntegerCoordinates(0, 0)
var encodedPolyline = ""
for coordinate in coordinates {
let intLatitude = Int(round(coordinate.latitude * precision))
let intLongitude = Int(round(coordinate.longitude * precision))
let coordinatesDifference = (intLatitude - previousCoordinate.latitude, intLongitude - previousCoordinate.longitude)
encodedPolyline += encodeCoordinate(coordinatesDifference)
previousCoordinate = (intLatitude,intLongitude)
}
return encodedPolyline
}
/// This function encodes an `[CLLocation]` to a `String`
///
/// - parameter coordinates: The `Array` of `CLLocation` that you want to encode
/// - parameter precision: The precision used to encode locations (default: `1e5`)
///
/// - returns: A `String` representing the encoded Polyline
public func encodeLocations(_ locations: [CLLocation], precision: Double = 1e5) -> String {
return encodeCoordinates(toCoordinates(locations), precision: precision)
}
/// This function encodes an `[UInt32]` to a `String`
///
/// - parameter levels: The `Array` of `UInt32` levels that you want to encode
///
/// - returns: A `String` representing the encoded Levels
public func encodeLevels(_ levels: [UInt32]) -> String {
return levels.reduce("") {
$0 + encodeLevel($1)
}
}
/// This function decodes a `String` to a `[CLLocationCoordinate2D]?`
///
/// - parameter encodedPolyline: `String` representing the encoded Polyline
/// - parameter precision: The precision used to decode coordinates (default: `1e5`)
///
/// - returns: A `[CLLocationCoordinate2D]` representing the decoded polyline if valid, `nil` otherwise
public func decodePolyline(_ encodedPolyline: String, precision: Double = 1e5) -> [CLLocationCoordinate2D]? {
let data = encodedPolyline.data(using: String.Encoding.utf8)!
let byteArray = unsafeBitCast((data as NSData).bytes, to: UnsafePointer<Int8>.self)
let length = Int(data.count)
var position = Int(0)
var decodedCoordinates = [CLLocationCoordinate2D]()
var lat = 0.0
var lon = 0.0
while position < length {
do {
let resultingLat = try decodeSingleCoordinate(byteArray: byteArray, length: length, position: &position, precision: precision)
lat += resultingLat
let resultingLon = try decodeSingleCoordinate(byteArray: byteArray, length: length, position: &position, precision: precision)
lon += resultingLon
} catch {
return nil
}
decodedCoordinates.append(CLLocationCoordinate2D(latitude: lat, longitude: lon))
}
return decodedCoordinates
}
/// This function decodes a String to a [CLLocation]?
///
/// - parameter encodedPolyline: String representing the encoded Polyline
/// - parameter precision: The precision used to decode locations (default: 1e5)
///
/// - returns: A [CLLocation] representing the decoded polyline if valid, nil otherwise
public func decodePolyline(_ encodedPolyline: String, precision: Double = 1e5) -> [CLLocation]? {
return decodePolyline(encodedPolyline, precision: precision).map(toLocations)
}
/// This function decodes a `String` to an `[UInt32]`
///
/// - parameter encodedLevels: The `String` representing the levels to decode
///
/// - returns: A `[UInt32]` representing the decoded Levels if the `String` is valid, `nil` otherwise
public func decodeLevels(_ encodedLevels: String) -> [UInt32]? {
var remainingLevels = encodedLevels.unicodeScalars
var decodedLevels = [UInt32]()
while remainingLevels.count > 0 {
do {
let chunk = try extractNextChunk(&remainingLevels)
let level = decodeLevel(chunk)
decodedLevels.append(level)
} catch {
return nil
}
}
return decodedLevels
}
// MARK: - Private -
// MARK: Encode Coordinate
private func encodeCoordinate(_ locationCoordinate: IntegerCoordinates) -> String {
let latitudeString = encodeSingleComponent(locationCoordinate.latitude)
let longitudeString = encodeSingleComponent(locationCoordinate.longitude)
return latitudeString + longitudeString
}
private func encodeSingleComponent(_ value: Int) -> String {
var intValue = value
if intValue < 0 {
intValue = intValue << 1
intValue = ~intValue
} else {
intValue = intValue << 1
}
return encodeFiveBitComponents(intValue)
}
// MARK: Encode Levels
private func encodeLevel(_ level: UInt32) -> String {
return encodeFiveBitComponents(Int(level))
}
private func encodeFiveBitComponents(_ value: Int) -> String {
var remainingComponents = value
var fiveBitComponent = 0
var returnString = String()
repeat {
fiveBitComponent = remainingComponents & 0x1F
if remainingComponents >= 0x20 {
fiveBitComponent |= 0x20
}
fiveBitComponent += 63
let char = UnicodeScalar(fiveBitComponent)!
returnString.append(String(char))
remainingComponents = remainingComponents >> 5
} while (remainingComponents != 0)
return returnString
}
// MARK: Decode Coordinate
// We use a byte array (UnsafePointer<Int8>) here for performance reasons. Check with swift 2 if we can
// go back to using [Int8]
private func decodeSingleCoordinate(byteArray: UnsafePointer<Int8>, length: Int, position: inout Int, precision: Double = 1e5) throws -> Double {
guard position < length else { throw PolylineError.singleCoordinateDecodingError }
let bitMask = Int8(0x1F)
var coordinate: Int32 = 0
var currentChar: Int8
var componentCounter: Int32 = 0
var component: Int32 = 0
repeat {
currentChar = byteArray[position] - 63
component = Int32(currentChar & bitMask)
coordinate |= (component << (5*componentCounter))
position += 1
componentCounter += 1
} while ((currentChar & 0x20) == 0x20) && (position < length) && (componentCounter < 6)
if (componentCounter == 6) && ((currentChar & 0x20) == 0x20) {
throw PolylineError.singleCoordinateDecodingError
}
if (coordinate & 0x01) == 0x01 {
coordinate = ~(coordinate >> 1)
} else {
coordinate = coordinate >> 1
}
return Double(coordinate) / precision
}
// MARK: Decode Levels
private func extractNextChunk(_ encodedString: inout String.UnicodeScalarView) throws -> String {
var currentIndex = encodedString.startIndex
while currentIndex != encodedString.endIndex {
let currentCharacterValue = Int32(encodedString[currentIndex].value)
if isSeparator(currentCharacterValue) {
let extractedScalars = encodedString[encodedString.startIndex...currentIndex]
encodedString = encodedString[encodedString.index(after: currentIndex)..<encodedString.endIndex]
return String(extractedScalars)
}
currentIndex = encodedString.index(after: currentIndex)
}
throw PolylineError.chunkExtractingError
}
private func decodeLevel(_ encodedLevel: String) -> UInt32 {
let scalarArray = [] + encodedLevel.unicodeScalars
return UInt32(agregateScalarArray(scalarArray))
}
private func agregateScalarArray(_ scalars: [UnicodeScalar]) -> Int32 {
let lastValue = Int32(scalars.last!.value)
let fiveBitComponents: [Int32] = scalars.map { scalar in
let value = Int32(scalar.value)
if value != lastValue {
return (value - 63) ^ 0x20
} else {
return value - 63
}
}
return Array(fiveBitComponents.reversed()).reduce(0) { ($0 << 5 ) | $1 }
}
// MARK: Utilities
enum PolylineError: Error {
case singleCoordinateDecodingError
case chunkExtractingError
}
private func toCoordinates(_ locations: [CLLocation]) -> [CLLocationCoordinate2D] {
return locations.map {location in location.coordinate}
}
private func toLocations(_ coordinates: [CLLocationCoordinate2D]) -> [CLLocation] {
return coordinates.map { coordinate in
CLLocation(latitude:coordinate.latitude, longitude:coordinate.longitude)
}
}
private func isSeparator(_ value: Int32) -> Bool {
return (value - 63) & 0x20 != 0x20
}
private typealias IntegerCoordinates = (latitude: Int, longitude: Int)
| mit | 35c3d325679adfd71ce8b879bf4e6617 | 34.337766 | 145 | 0.680515 | 4.607143 | false | false | false | false |
inderdhir/DatWeatherDoe | DatWeatherDoe/UI/Decorator/Condition/Mapping/WeatherConditionImageMapper.swift | 1 | 1906 | //
// WeatherConditionImageMapper.swift
// DatWeatherDoe
//
// Created by Inder Dhir on 1/11/22.
// Copyright © 2022 Inder Dhir. All rights reserved.
//
import Cocoa
final class WeatherConditionImageMapper {
func map(_ condition: WeatherCondition) -> NSImage? {
let imageString: String
switch condition {
case .cloudy:
imageString = "Cloudy"
case .partlyCloudy:
imageString = "Partly Cloudy"
case .partlyCloudyNight:
imageString = "Partly Cloudy - Night"
case .sunny:
imageString = "Sunny"
case .clearNight:
imageString = "Clear - Night"
case let .smoky(smokyWeatherCondition):
return SmokyWeatherConditionImageMapper().map(smokyWeatherCondition)
case .snow:
imageString = "Snow"
case .heavyRain:
imageString = "Heavy Rain"
case .freezingRain:
imageString = "Freezing Rain"
case .lightRain:
imageString = "Light Rain"
case .partlyCloudyRain:
imageString = "Partly Cloudy with Rain"
case .thunderstorm:
imageString = "Thunderstorm"
}
return NSImage(named: imageString)
}
}
private class SmokyWeatherConditionImageMapper {
func map(_ condition: SmokyWeatherCondition) -> NSImage? {
let imageString: String
switch condition {
case .tornado:
imageString = "Tornado"
case .squall:
imageString = "Windy"
case .ash, .dust, .sand, .sandOrDustWhirls, .fog, .haze, .smoke:
imageString = "Dust or Fog"
case .mist:
imageString = "Mist"
}
return NSImage(named: imageString)
}
}
| apache-2.0 | 11b52570a7460d77d96d1926a0a607a5 | 25.458333 | 80 | 0.546457 | 4.909794 | false | false | false | false |
Aioria1314/WeiBo | WeiBo/WeiBo/Classes/Tools/Extension/ZXCTextView+Extension.swift | 1 | 2965 | //
// ZXCTextView+Extension.swift
// WeiBo
//
// Created by Aioria on 2017/4/8.
// Copyright © 2017年 Aioria. All rights reserved.
//
import UIKit
extension ZXCTextView {
var emoticonText: String {
var sendMessage = ""
self.attributedText.enumerateAttributes(in: NSMakeRange(0, self.attributedText.length), options: []) { (info, range, _) in
// print(info, NSStringFromRange(range))
if let attachment = info["NSAttachment"] as? ZXCTextAttachment
{
let emoticonModel = attachment.emoticonModel!
let chs = emoticonModel.chs!
sendMessage += chs
}
else
{
let subAttributedStr = self.attributedText.attributedSubstring(from: range)
let text = subAttributedStr.string
sendMessage += text
}
}
return sendMessage
}
func insertEmoticon(emoticonModel: ZXCEmoticonModel)
{
if emoticonModel.type == "0" {
let lastAttributedStr = NSMutableAttributedString(attributedString: self.attributedText)
//
// let image = UIImage(named: emoticonModel.path!)
//
// let attachMent = ZXCTextAttachment()
//
// attachMent.emoticonModel = emoticonModel
//
// attachMent.image = image
//
// let linHeight = self.font!.lineHeight
//
// attachMent.bounds = CGRect(x: 0, y: -4, width: linHeight, height: linHeight)
let attributedStr = NSAttributedString.attributedStringWithEmotionModel(emoticonModel: emoticonModel, font: self.font!)
var selectedRange = self.selectedRange
lastAttributedStr.replaceCharacters(in: selectedRange, with: attributedStr)
// lastAttributedStr.append(attributedStr)
lastAttributedStr.addAttributes([NSFontAttributeName: self.font!], range: NSMakeRange(0, lastAttributedStr.length))
self.attributedText = lastAttributedStr
selectedRange.location += 1
self.selectedRange = selectedRange
self.delegate?.textViewDidChange?(self)
NotificationCenter.default.post(name: Notification.Name.UITextViewTextDidChange, object: nil)
} else {
let emoji = (emoticonModel.code! as NSString).emoji()!
self.insertText(emoji)
}
}
}
| mit | 8123905764fea201c861198474b03057 | 30.178947 | 139 | 0.502701 | 5.696154 | false | false | false | false |
congncif/SiFUtilities | Helpers/Debouncer.swift | 1 | 3159 | //
// Debouncer.swift
//
//
// Created by NGUYEN CHI CONG on 3/2/17.
// Copyright © 2017 [iF] Solution Co., Ltd. All rights reserved.
//
import Foundation
public final class TimerDebouncer {
private var delay: DispatchTimeInterval
private let queue: DispatchQueue
private var work: (() -> Void)?
private var timer: DispatchSourceTimer?
public init(delay: DispatchTimeInterval, queue: DispatchQueue = .main, work: (() -> Void)? = nil) {
self.delay = delay
self.queue = queue
set(work: work)
}
private func set(work: (() -> Void)?) {
if let work = work {
self.work = work
}
}
deinit {
timer?.setEventHandler(handler: nil)
cancel()
}
public func cancel() {
guard let timer = timer else { return }
guard !timer.isCancelled else { return }
timer.cancel()
}
public func perform(work: (() -> Void)? = nil) {
cancel()
set(work: work)
guard let currentWork = self.work else {
#if DEBUG
print("⚠️ [TimerDebouncer] Nothing to perform")
#endif
return
}
let nextTimer = DispatchSource.makeTimerSource(queue: queue)
nextTimer.schedule(deadline: .now() + delay)
nextTimer.setEventHandler(handler: currentWork)
timer = nextTimer
timer?.resume()
}
public func performNow() {
guard let work = self.work else {
#if DEBUG
print("⚠️ [TimerDebouncer] Nothing to perform")
#endif
return
}
work()
}
}
public final class Debouncer {
private var delay: DispatchTimeInterval
private let queue: DispatchQueue
private var work: (() -> Void)?
private var workItem: DispatchWorkItem?
public init(delay: DispatchTimeInterval, queue: DispatchQueue = .main, work: (() -> Void)? = nil) {
self.queue = queue
self.delay = delay
self.work = work
}
private func set(work: (() -> Void)?) {
if let work = work {
self.work = work
}
}
private func newWorkItem() {
if let work = self.work {
workItem = DispatchWorkItem(block: work)
}
}
deinit {
cancel()
}
public func cancel() {
workItem?.cancel()
}
public func perform(work: (() -> Void)? = nil) {
cancel()
set(work: work)
newWorkItem()
guard let workItem = self.workItem else {
#if DEBUG
print("⚠️ [Debouncer] Nothing to perform")
#endif
return
}
queue.asyncAfter(deadline: .now() + delay, execute: workItem)
}
public func performNow() {
cancel()
newWorkItem()
guard let workItem = self.workItem else {
#if DEBUG
print("⚠️ [Debouncer] Nothing to perform")
#endif
return
}
queue.async(execute: workItem)
}
}
| mit | d02f980ffd49f15ee1a4317502b66be4 | 22.984733 | 103 | 0.523234 | 4.703593 | false | false | false | false |
SPECURE/rmbt-ios-client | Sources/QOS/QOSControlConnection.swift | 1 | 18633 | /*****************************************************************************************************
* Copyright 2014-2016 SPECURE GmbH
*
* 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 CocoaAsyncSocket
class QOSControlConnectionTaskWeakObserver: NSObject {
weak var delegate: QOSControlConnectionTaskDelegate?
init(_ delegate: QOSControlConnectionTaskDelegate) {
self.delegate = delegate
}
}
class QOSControlConnection: NSObject {
internal let TAG_GREETING = -1
internal let TAG_FIRST_ACCEPT = -2
internal let TAG_TOKEN = -3
//internal let TAG_OK = -4
internal let TAG_SECOND_ACCEPT = -4
internal let TAG_SET_TIMEOUT = -10
internal let TAG_TASK_COMMAND = -100
//
///
weak var delegate: QOSControlConnectionDelegate?
///
var connected = false
///
internal let testToken: String
///
internal let connectCountDownLatch = CountDownLatch()
///
internal let socketQueue = DispatchQueue(label: "com.specure.rmbt.controlConnectionSocketQueue")
internal let mutableQueue = DispatchQueue(label: "com.specure.rmbt.mutableQueue")
///
internal lazy var qosControlConnectionSocket: GCDAsyncSocket = GCDAsyncSocket(delegate: self, delegateQueue: socketQueue)
///
internal var taskDelegateDictionary: [UInt: [QOSControlConnectionTaskWeakObserver]] = [:]
///
internal var pendingTimeout: Double = 0
internal var currentTimeout: Double = 0
//
deinit {
defer {
taskDelegateDictionary = [:]
qosControlConnectionSocket.delegate = nil
qosControlConnectionSocket.disconnect()
}
}
///
init(testToken: String) {
self.testToken = testToken
super.init()
Log.logger.verbose("control connection created")
}
// MARK: connection handling
///
func connect(_ host: String, onPort port: UInt16) -> Bool {
return connect(host, onPort: port, withTimeout: QOS_CONTROL_CONNECTION_TIMEOUT_NS)
}
///
func connect(_ host: String, onPort port: UInt16, withTimeout timeout: UInt64) -> Bool {
let connectTimeout = nsToSec(timeout)
do {
qosControlConnectionSocket.setupSocket()
try qosControlConnectionSocket.connect(toHost: host, onPort: port, withTimeout: connectTimeout)
} catch {
// there was an error
Log.logger.verbose("connection error \(error)")
}
_ = connectCountDownLatch.await(timeout)
return connected
}
///
func disconnect() {
// send quit
Log.logger.debug("QUIT QUIT QUIT QUIT QUIT")
self.writeLine("QUIT", withTimeout: QOS_CONTROL_CONNECTION_TIMEOUT_SEC, tag: -1) // don't bother with the tag, don't need read after this operation
qosControlConnectionSocket.disconnectAfterWriting()
// qosControlConnectionSocket.disconnectAfterReadingAndWriting()
}
// MARK: commands
///
func setTimeout(_ timeout: UInt64) {
// Log.logger.debug("SET TIMEOUT: \(timeout)")
// timeout is in nanoseconds -> convert to ms
var msTimeout = nsToMs(timeout)
// if msTimeout is lower than 15 seconds, increase it
if msTimeout < 15_000 {
msTimeout = 15_000
}
if currentTimeout == msTimeout {
Log.logger.debug("skipping change of control connection timeout because old value = new value")
return // skip if old == new timeout
}
pendingTimeout = msTimeout
// Log.logger.debug("REQUEST CONN TIMEOUT \(msTimeout)")
writeLine("REQUEST CONN TIMEOUT \(msTimeout)", withTimeout: QOS_CONTROL_CONNECTION_TIMEOUT_SEC, tag: TAG_SET_TIMEOUT)
readLine(TAG_SET_TIMEOUT, withTimeout: QOS_CONTROL_CONNECTION_TIMEOUT_SEC)
}
// MARK: control connection delegate methods
func clearObservers() {
for (_, arrayOfObservers) in taskDelegateDictionary.enumerated() {
var observers = arrayOfObservers.value
for observer in arrayOfObservers.value {
if observer.delegate == nil {
if let index = observers.firstIndex(of: observer) {
observers.remove(at: index)
}
}
}
if observers.count == 0 {
taskDelegateDictionary.removeValue(forKey: arrayOfObservers.key)
}
}
}
///
func registerTaskDelegate(_ delegate: QOSControlConnectionTaskDelegate, forTaskId taskId: UInt) {
self.mutableQueue.sync {
var observers: [QOSControlConnectionTaskWeakObserver]? = taskDelegateDictionary[taskId]
if observers == nil {
observers = []
}
observers?.append(QOSControlConnectionTaskWeakObserver(delegate))
taskDelegateDictionary[taskId] = observers
self.clearObservers()
Log.logger.debug("registerTaskDelegate: \(taskId), delegate: \(delegate)")
}
}
///
func unregisterTaskDelegate(_ delegate: QOSControlConnectionTaskDelegate, forTaskId taskId: UInt) {
self.mutableQueue.sync {
if let tempObservers = taskDelegateDictionary[taskId] {
var observers = tempObservers
if let index = observers.firstIndex(where: { (observer) -> Bool in
return observer.delegate! === delegate
}) {
observers.remove(at: index)
Log.logger.debug("unregisterTaskDelegate: \(taskId), delegate: \(delegate)")
}
if observers.count == 0 {
taskDelegateDictionary[taskId] = nil
}
else {
taskDelegateDictionary[taskId] = observers
}
}
else {
Log.logger.debug("TaskDelegate: \(taskId) Not found")
}
self.clearObservers()
}
}
// MARK: task command methods
// TODO: use closure instead of delegate methods
/// command should not contain \n, will be added inside this method
func sendTaskCommand(_ command: String, withTimeout timeout: TimeInterval, forTaskId taskId: UInt, tag: Int) {
/* if (!qosControlConnectionSocket.isConnected) {
Log.logger.error("control connection is closed, sendTaskCommand won't work!")
} */
let _command = command + " +ID\(taskId)"
let t = createTaskCommandTag(forTaskId: taskId, tag: tag)
Log.logger.verbose("SENDTASKCOMMAND: (taskId: \(taskId), tag: \(tag)) -> \(t) (\(String(t, radix: 2)))")
// write command
writeLine(_command, withTimeout: timeout, tag: t)
// and then read? // TODO: or use thread with looped readLine?
readLine(t, withTimeout: timeout)
}
/// command should not contain \n, will be added inside this method
func sendTaskCommand(_ command: String, withTimeout timeout: TimeInterval, forTaskId taskId: UInt) {
sendTaskCommand(command, withTimeout: timeout, forTaskId: taskId, tag: TAG_TASK_COMMAND)
}
// MARK: convenience methods
///
internal func writeLine(_ line: String, withTimeout timeout: TimeInterval, tag: Int) {
qosControlConnectionSocket.writeLine(line: line, withTimeout: timeout, tag: tag)
}
///
internal func readLine(_ tag: Int, withTimeout timeout: TimeInterval) {
qosControlConnectionSocket.readLine(tag: tag, withTimeout: timeout)
}
// MARK: other methods
///
internal func createTaskCommandTag(forTaskId taskId: UInt, tag: Int) -> Int {
// bitfield: 0111|aaaa_aaaa_aaaa|bbbb_bbbb_bbbb_bbbb
var bitfield: UInt32 = 0x7
bitfield = bitfield << 12
bitfield = bitfield + (UInt32(abs(tag)) & 0x0000_0FFF)
bitfield = bitfield << 16
bitfield = bitfield + (UInt32(taskId) & 0x0000_FFFF)
// Log.logger.verbose("created BITFIELD for taskId: \(taskId), tag: \(tag) -> \(String(bitfield, radix: 2))")
// Log.logger.verbose("created BITFIELD for taskId: \(taskId), tag: \(tag) -> \(String(Int(bitfield), radix: 2))")
return Int(bitfield)
}
///
internal func parseTaskCommandTag(taskCommandTag commandTag: Int) -> (taskId: UInt, tag: Int)? {
let _commandTag = UInt(commandTag)
if !isTaskCommandTag(taskCommandTag: commandTag) {
return nil // not a valid task command tag
}
let taskId: UInt = _commandTag & 0x0000_FFFF
let tag = Int((_commandTag & 0x0FFF_0000) >> 16)
Log.logger.verbose("BITFIELD2: \(commandTag) -> (taskId: \(taskId), tag: \(tag))")
return (taskId, tag)
}
///
internal func isTaskCommandTag(taskCommandTag commandTag: Int) -> Bool {
if commandTag < 0 {
return false
}
return UInt(commandTag) & 0x7000_0000 == 0x7000_0000
}
///
internal func matchAndGetTestIdFromResponse(_ response: String) -> UInt? {
do {
let regex = try NSRegularExpression(pattern: "\\+ID(\\d*)", options: [])
if let match = regex.firstMatch(in: response, options: [], range: NSRange(location: 0, length: response.count)) {
// println(match)
if match.numberOfRanges > 0 {
let idStr = (response as NSString).substring(with: match.range(at: 1))
// return UInt(idStr.toInt()) // does not work because of Int?
return UInt(idStr)
}
}
} catch {
// TODO?
}
return nil
}
}
// MARK: GCDAsyncSocketDelegate methods
///
extension QOSControlConnection: GCDAsyncSocketDelegate {
///
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
Log.logger.verbose("connected to host \(host) on port \(port)")
// control connection to qos server uses tls
sock.startTLS(QOS_TLS_SETTINGS)
}
func socket(_ sock: GCDAsyncSocket, didReceive trust: SecTrust, completionHandler: @escaping ((Bool) -> Void)) {
Log.logger.verbose("DID RECEIVE TRUST")
completionHandler(true)
}
///
@objc func socketDidSecure(_ sock: GCDAsyncSocket) {
Log.logger.verbose("socketDidSecure")
// tls connection has been established, start with QTP handshake
readLine(TAG_GREETING, withTimeout: QOS_CONTROL_CONNECTION_TIMEOUT_SEC)
}
///
@objc func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
Log.logger.verbose("didReadData \(data) with tag \(tag)")
let str: String = SocketUtils.parseResponseToString(data)!
Log.logger.verbose("didReadData \(str)")
switch tag {
case TAG_GREETING:
// got greeting
Log.logger.verbose("got greeting")
// read accept
self.readLine(TAG_FIRST_ACCEPT, withTimeout: QOS_CONTROL_CONNECTION_TIMEOUT_SEC)
case TAG_FIRST_ACCEPT:
// got accept
Log.logger.verbose("got accept")
// send token
let tokenCommand = "TOKEN \(testToken)\n"
self.writeLine(tokenCommand, withTimeout: QOS_CONTROL_CONNECTION_TIMEOUT_SEC, tag: TAG_TOKEN)
// read token response
self.readLine(TAG_TOKEN, withTimeout: QOS_CONTROL_CONNECTION_TIMEOUT_SEC)
case TAG_TOKEN:
// response from token command
Log.logger.verbose("got ok")
// read second accept
self.readLine(TAG_SECOND_ACCEPT, withTimeout: QOS_CONTROL_CONNECTION_TIMEOUT_SEC)
case TAG_SECOND_ACCEPT:
// got second accept
Log.logger.verbose("got second accept")
// now connection is ready
Log.logger.verbose("CONNECTION READY")
connected = true // set connected to true to unlock
connectCountDownLatch.countDown()
// call delegate method // TODO: on which queue?
self.delegate?.controlConnectionReadyToUse(self)
//
case TAG_SET_TIMEOUT:
// return from REQUEST CONN TIMEOUT
if str == "OK\n" {
Log.logger.debug("set timeout ok")
currentTimeout = pendingTimeout
// OK
} else {
Log.logger.debug("set timeout fail \(str)")
// FAIL
}
default:
// case TAG_TASK_COMMAND:
// got reply from task command
Log.logger.verbose("TAGTAGTAGTAG: \(tag)")
// dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
if self.isTaskCommandTag(taskCommandTag: tag) {
if let (_taskId, _tag) = self.parseTaskCommandTag(taskCommandTag: tag) {
Log.logger.verbose("\(tag): got reply from task command")
Log.logger.verbose("\(tag): taskId: \(_taskId), _tag: \(_tag)")
if let taskId = self.matchAndGetTestIdFromResponse(str) {
Log.logger.verbose("\(tag): TASK ID: \(taskId)")
//Log.logger.verbose("\(taskDelegateDictionary.count)")
//Log.logger.verbose("\(taskDelegateDictionary.indexForKey(1))")
if let observers = self.taskDelegateDictionary[taskId] {
for observer in observers {
Log.logger.verbose("\(tag): TASK DELEGATE: \(String(describing: observer.delegate))")
Log.logger.debug("CALLING DELEGATE METHOD of \(String(describing: observer.delegate)), withResponse: \(str), taskId: \(taskId), tag: \(tag), _tag: \(_tag)")
// call delegate method // TODO: dispatch delegate methods with dispatch queue of delegate
observer.delegate?.controlConnection(self, didReceiveTaskResponse: str, withTaskId: taskId, tag: _tag)
}
}
}
}
}
// }
}
}
///
@objc func socket(_ sock: GCDAsyncSocket, didReadPartialDataOfLength partialLength: UInt, tag: Int) {
Log.logger.verbose("didReadPartialDataOfLength \(partialLength), tag: \(tag)")
}
///
@objc func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
Log.logger.verbose("didWriteDataWithTag \(tag)")
}
///
@objc func socket(_ sock: GCDAsyncSocket, didWritePartialDataOfLength partialLength: UInt, tag: Int) {
Log.logger.verbose("didWritePartialDataOfLength \(partialLength), tag: \(tag)")
}
///
@objc func socket(_ sock: GCDAsyncSocket, shouldTimeoutReadWithTag tag: Int, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval {
Log.logger.verbose("shouldTimeoutReadWithTag \(tag), elapsed: \(elapsed), bytesDone: \(length)")
// if (tag < TAG_TASK_COMMAND) {
if isTaskCommandTag(taskCommandTag: tag) {
//let taskId = UInt(-tag + TAG_TASK_COMMAND)
if let (taskId, _tag) = parseTaskCommandTag(taskCommandTag: tag) {
Log.logger.verbose("TASK ID: \(taskId)")
if let observers = taskDelegateDictionary[taskId] {
for observer in observers {
Log.logger.verbose("TASK DELEGATE: \(String(describing: observer.delegate))")
// call delegate method // TODO: dispatch delegate methods with dispatch queue of delegate
observer.delegate?.controlConnection(self, didReceiveTimeout: elapsed, withTaskId: taskId, tag: _tag)
Log.logger.debug("!!! AFTER DID_RECEIVE_TIMEOUT !!!!")
}
}
}
}
// return -1 // always let this timeout
return 10000 // extend timeout ... because of the weird timeout handling of GCDAsyncSocket (socket would close)
}
///
@objc func socket(_ sock: GCDAsyncSocket, shouldTimeoutWriteWithTag tag: Int, elapsed: TimeInterval, bytesDone length: UInt) -> TimeInterval {
Log.logger.verbose("shouldTimeoutReadWithTag \(tag), elapsed: \(elapsed), bytesDone: \(length)")
// if (tag < TAG_TASK_COMMAND) {
if isTaskCommandTag(taskCommandTag: tag) {
//let taskId = UInt(-tag + TAG_TASK_COMMAND)
if let (taskId, _tag) = parseTaskCommandTag(taskCommandTag: tag) {
Log.logger.verbose("TASK ID: \(taskId)")
if let observers = taskDelegateDictionary[taskId] {
for observer in observers {
Log.logger.verbose("TASK DELEGATE: \(String(describing: observer.delegate))")
// call delegate method // TODO: dispatch delegate methods with dispatch queue of delegate
observer.delegate?.controlConnection(self, didReceiveTimeout: elapsed, withTaskId: taskId, tag: _tag)
}
}
}
}
//return -1 // always let this timeout
return 10000 // extend timeout ... because of the weird timeout handling of GCDAsyncSocket (socket would close)
}
///
@objc func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
connected = false
if err == nil {
Log.logger.debug("QOS CC: socket closed by server after sending QUIT")
return // if the server closed the connection error is nil (this happens after sending QUIT to the server)
}
Log.logger.debug("QOS CC: disconnected with error \(String(describing: err))")
// TODO: fail!
}
}
| apache-2.0 | 61dffc6c939be6d8b77b86606a08df5c | 35.040619 | 192 | 0.590136 | 4.714828 | false | false | false | false |
IvanVorobei/TwitterLaunchAnimation | TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/ui/controls/segmentedControl/SPSegmentControllCell.swift | 2 | 4238 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class SPSegmentedControlCell: UIView {
var imageView: UIImageView = UIImageView.init()
var label: UILabel = UILabel()
var layout: SPSegmentedControlCellLayout = .onlyText {
didSet {
layoutIfNeeded()
}
}
var iconRelativeScaleFactor: CGFloat = 0.5
var spaceBetweenImageAndLabelRelativeFactor: CGFloat = 0.044 {
didSet {
layoutIfNeeded()
}
}
init(layout: SPSegmentedControlCellLayout) {
super.init(frame: CGRect.zero)
self.layout = layout
self.commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
self.label.font = UIFont(name: "Avenir-Medium", size: 13.0)!
self.label.text = ""
self.label.textColor = UIColor.white
self.label.backgroundColor = UIColor.clear
self.addSubview(label)
self.imageView.backgroundColor = UIColor.clear
self.addSubview(self.imageView)
}
override public func layoutSubviews() {
super.layoutSubviews()
label.frame = CGRect.zero
imageView.frame = CGRect.zero
switch self.layout {
case .onlyImage:
let sideSize = min(self.frame.width , self.frame.height) * self.iconRelativeScaleFactor
self.imageView.frame = CGRect.init(
x: 0, y: 0,
width: sideSize,
height: sideSize
)
self.imageView.center = CGPoint.init(
x: self.frame.width / 2,
y: self.frame.height / 2
)
case .onlyText:
label.textAlignment = .center
label.frame = self.bounds
case .textWithImage:
label.sizeToFit()
let sideSize = min(self.frame.width , self.frame.height) * self.iconRelativeScaleFactor
self.imageView.frame = CGRect.init(
x: 0, y: 0,
width: sideSize,
height: sideSize
)
let space: CGFloat = self.frame.width * self.spaceBetweenImageAndLabelRelativeFactor
let elementsWidth: CGFloat = self.imageView.frame.width + space + self.label.frame.width
let leftEdge = (self.frame.width - elementsWidth) / 2
let centeringHeight = self.frame.height / 2
self.imageView.center = CGPoint.init(
x: leftEdge + self.imageView.frame.width / 2,
y: centeringHeight
)
self.label.center = CGPoint.init(
x: leftEdge + self.imageView.frame.width + space + label.frame.width / 2,
y: centeringHeight
)
default:
break
}
}
}
enum SPSegmentedControlCellLayout {
case emptyData
case onlyText
case onlyImage
case textWithImage
}
| mit | ba44cbd279cf04bd2d8309b9440bd073 | 34.605042 | 100 | 0.622374 | 4.661166 | false | false | false | false |
IvanVorobei/TwitterLaunchAnimation | TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/ui/controls/segmentedControl/SPSegmentedControl.swift | 2 | 10523 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class SPSegmentedControl: UIControl {
var indicatorView: UIView = UIView()
var cells: [SPSegmentedControlCell] = []
var styleDelegate: SPSegmentControlCellStyleDelegate?
var delegate: SPSegmentControlDelegate?
var defaultSelectedIndex: Int = 0
var isUpdateToNearestIndexWhenDrag: Bool = true
var selectedIndex : Int = 0 {
didSet {
if (selectedIndex < 0) {
selectedIndex = 0
}
if (selectedIndex >= self.cells.count) {
selectedIndex = self.cells.count - 1
}
updateSelectedIndex()
}
}
var isScrollEnabled: Bool = true {
didSet {
self.panGestureRecognizer.isEnabled = self.isScrollEnabled
}
}
var isSwipeEnabled: Bool = true {
didSet {
self.leftSwipeGestureRecognizer.isEnabled = self.isSwipeEnabled
self.rightSwipeGestureRecognizer.isEnabled = self.isSwipeEnabled
}
}
var isRoundedFrame: Bool = true {
didSet {
layoutIfNeeded()
}
}
var roundedRelativeFactor: CGFloat = 0.5 {
didSet {
layoutIfNeeded()
}
}
fileprivate var panGestureRecognizer: UIPanGestureRecognizer!
fileprivate var leftSwipeGestureRecognizer: UISwipeGestureRecognizer!
fileprivate var rightSwipeGestureRecognizer: UISwipeGestureRecognizer!
fileprivate var initialIndicatorViewFrame: CGRect?
fileprivate var oldNearestIndex: Int!
init() {
super.init(frame: CGRect.zero)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func add(cell: SPSegmentedControlCell) {
cell.isUserInteractionEnabled = false
self.cells.append(cell)
self.addSubview(cell)
self.selectedIndex = self.defaultSelectedIndex
}
func add(cells: [SPSegmentedControlCell]) {
for cell in cells {
cell.isUserInteractionEnabled = false
self.cells.append(cell)
self.addSubview(cell)
self.selectedIndex = self.defaultSelectedIndex
}
}
private func commonInit() {
self.layer.masksToBounds = true
self.backgroundColor = UIColor.clear
self.layer.borderColor = UIColor.white.cgColor
self.layer.borderWidth = 2
self.indicatorView.backgroundColor = UIColor.white
self.addSubview(indicatorView)
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(SPSegmentedControl.pan(_:)))
panGestureRecognizer.delegate = self
addGestureRecognizer(panGestureRecognizer)
leftSwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(SPSegmentedControl.leftSwipe(_:)))
leftSwipeGestureRecognizer.delegate = self
leftSwipeGestureRecognizer.direction = .left
self.indicatorView.addGestureRecognizer(leftSwipeGestureRecognizer)
rightSwipeGestureRecognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(SPSegmentedControl.rightSwipe(_:)))
rightSwipeGestureRecognizer.delegate = self
rightSwipeGestureRecognizer.direction = .right
self.indicatorView.addGestureRecognizer(rightSwipeGestureRecognizer)
}
private func updateSelectedIndex(animated: Bool = false) {
if self.styleDelegate != nil {
for (index, cell) in self.cells.enumerated() {
self.styleDelegate?.normalState?(segmentControlCell: cell, forIndex: index)
}
self.styleDelegate?.selectedState?(segmentControlCell: self.cells[self.selectedIndex], forIndex: self.selectedIndex)
}
SPAnimationSpring.animate(
0.35,
animations: {
self.indicatorView.frame = self.cells[self.selectedIndex].frame
}, delay: 0,
spring: 1,
velocity: 0.8,
options: [.curveEaseOut]
)
}
override public func layoutSubviews() {
super.layoutSubviews()
if isRoundedFrame {
self.layer.cornerRadius = min(self.frame.width, self.frame.height) * self.roundedRelativeFactor
self.indicatorView.layer.cornerRadius = self.layer.cornerRadius
}
if cells.isEmpty {
return
}
let cellWidth = self.frame.width / CGFloat(self.cells.count)
for (index, cell) in cells.enumerated() {
cell.frame = CGRect.init(
x: cellWidth * CGFloat(index),
y: 0,
width: cellWidth,
height: self.frame.height
)
}
self.indicatorView.frame = CGRect.init(
x: 0, y: 0,
width: cellWidth,
height: self.frame.height
)
self.updateSelectedIndex(animated: true)
}
fileprivate func nearestIndexToPoint(point: CGPoint) -> Int {
var distances = [CGFloat]()
for cell in self.cells {
distances.append(
abs(point.x - cell.center.x)
)
}
return Int(distances.index(of: distances.min()!)!)
}
override public func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let location = touch.location(in: self)
var calculatedIndex : Int?
for (index, cell) in cells.enumerated() {
if cell.frame.contains(location) {
calculatedIndex = index
}
}
if calculatedIndex != nil {
self.selectedIndex = calculatedIndex!
sendActions(for: .valueChanged)
}
return false
}
}
extension SPSegmentedControl: UIGestureRecognizerDelegate {
func pan(_ gestureRecognizer: UIPanGestureRecognizer!) {
switch gestureRecognizer.state {
case .began:
self.initialIndicatorViewFrame = self.indicatorView.frame
self.oldNearestIndex = self.nearestIndexToPoint(point: self.indicatorView.center)
case .changed:
var frame = self.initialIndicatorViewFrame!
frame.origin.x += gestureRecognizer.translation(in: self).x
indicatorView.frame = frame
if indicatorView.frame.origin.x < 0 {
indicatorView.frame.origin.x = 0
}
if (indicatorView.frame.origin.x + indicatorView.frame.width > self.frame.width) {
indicatorView.frame.origin.x = self.frame.width - indicatorView.frame.width
}
if (isUpdateToNearestIndexWhenDrag) {
let nearestIndex = self.nearestIndexToPoint(point: self.indicatorView.center)
if (self.oldNearestIndex != nearestIndex) && (styleDelegate != nil) {
self.oldNearestIndex = self.nearestIndexToPoint(point: self.indicatorView.center)
for (index, cell) in cells.enumerated() {
styleDelegate?.normalState?(segmentControlCell: cell, forIndex: index)
}
styleDelegate?.selectedState?(segmentControlCell: cells[nearestIndex], forIndex:nearestIndex)
}
}
self.delegate?.indicatorViewRelativPosition?(
position: self.indicatorView.frame.origin.x,
onSegmentControl: self
)
case .ended, .failed, .cancelled:
let translation = gestureRecognizer.translation(in: self).x
if abs(translation) > (self.frame.width / CGFloat(self.cells.count) * 0.08) {
if self.selectedIndex == self.nearestIndexToPoint(point: self.indicatorView.center) {
if translation > 0 {
selectedIndex = selectedIndex + 1
} else {
selectedIndex = selectedIndex - 1
}
} else {
self.selectedIndex = self.nearestIndexToPoint(point: self.indicatorView.center)
}
} else {
self.selectedIndex = self.nearestIndexToPoint(point: self.indicatorView.center)
}
default:
break
}
}
func leftSwipe(_ gestureRecognizer: UISwipeGestureRecognizer!) {
switch gestureRecognizer.state {
case.ended:
self.selectedIndex = selectedIndex - 1
default:
break
}
}
func rightSwipe(_ gestureRecognizer: UISwipeGestureRecognizer!) {
switch gestureRecognizer.state {
case.ended:
self.selectedIndex = selectedIndex + 1
default:
break
}
}
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panGestureRecognizer {
return indicatorView.frame.contains(gestureRecognizer.location(in: self))
}
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
}
| mit | 9029dacfaa3b90d16fb1fc65ef7fdaf3 | 35.919298 | 135 | 0.615852 | 5.300756 | false | false | false | false |
mono0926/LicensePlist | Sources/LicensePlistCore/Logger.swift | 1 | 1526 | import HeliumLogger
import LoggerAPI
public struct Logger {
public static func configure(logLevel: LogLevel,
colorCommandLineFlag: Bool?) {
if logLevel == .silenceMode {
return
}
let logger: HeliumLogger = {
if logLevel == .normalLogLevel {
return createDefaultLogger()
} else {
return createDebugLogger()
}
}()
let usedColorMode = AutoColorMode.usedColorMode(commandLineDesignation: UserDesignatedColorMode(from: colorCommandLineFlag))
logger.colored = usedColorMode.boolValue
Log.logger = logger
}
private static func createDefaultLogger() -> HeliumLogger {
let logger = HeliumLogger(LoggerMessageType.info)
logger.details = false
return logger
}
private static func createDebugLogger() -> HeliumLogger {
let logger = HeliumLogger(LoggerMessageType.debug)
logger.details = true
return logger
}
}
extension UserDesignatedColorMode {
init(from flag: Bool?) {
switch flag {
case .none: self = .noDesignation
case .some(true): self = .color
case .some(false): self = .noColor
}
}
}
extension UsedColorMode {
var boolValue: Bool {
switch self {
case .color: return true
case .noColor: return false
}
}
}
public enum LogLevel {
case silenceMode
case normalLogLevel
case verbose
}
| mit | 5ad32725c12a576f403b7a937290f1a8 | 24.016393 | 132 | 0.601573 | 5.003279 | false | false | false | false |
iadmir/Signal-iOS | Signal/src/views/GroupTableViewCell.swift | 2 | 2570 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import UIKit
@objc class GroupTableViewCell: UITableViewCell {
let TAG = "[GroupTableViewCell]"
private let avatarView = AvatarImageView()
private let nameLabel = UILabel()
private let subtitleLabel = UILabel()
init() {
super.init(style: .default, reuseIdentifier: TAG)
self.contentView.addSubview(avatarView)
let textContainer = UIView.container()
textContainer.addSubview(nameLabel)
textContainer.addSubview(subtitleLabel)
self.contentView.addSubview(textContainer)
// Font config
nameLabel.font = UIFont.ows_dynamicTypeBody()
subtitleLabel.font = UIFont.ows_footnote()
subtitleLabel.textColor = UIColor.ows_darkGray()
// Listen to notifications...
// TODO avatar, group name change, group membership change, group member name change
// Layout
nameLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .bottom)
subtitleLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero, excludingEdge: .top)
subtitleLabel.autoPinEdge(.top, to: .bottom, of: nameLabel)
avatarView.autoPinLeadingToSuperview()
avatarView.autoVCenterInSuperview()
avatarView.autoSetDimension(.width, toSize: CGFloat(kContactTableViewCellAvatarSize))
avatarView.autoPinToSquareAspectRatio()
textContainer.autoPinEdge(.leading, to: .trailing, of: avatarView, withOffset: kContactTableViewCellAvatarTextMargin)
textContainer.autoPinTrailingToSuperview()
textContainer.autoVCenterInSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configure(thread: TSGroupThread, contactsManager: OWSContactsManager) {
if let groupName = thread.groupModel.groupName, !groupName.isEmpty {
self.nameLabel.text = groupName
} else {
self.nameLabel.text = MessageStrings.newGroupDefaultTitle
}
let groupMemberIds: [String] = thread.groupModel.groupMemberIds
let groupMemberNames = groupMemberIds.map { (recipientId: String) in
contactsManager.displayName(forPhoneIdentifier: recipientId)
}.joined(separator: ", ")
self.subtitleLabel.text = groupMemberNames
self.avatarView.image = OWSAvatarBuilder.buildImage(thread: thread, diameter: kContactTableViewCellAvatarSize, contactsManager: contactsManager)
}
}
| gpl-3.0 | 45d8fb6aaa780b3555edb9978e40e46f | 36.246377 | 152 | 0.707393 | 5.277207 | false | false | false | false |
hanwanjie853710069/Easy-living | 易持家/Class/BaseViewController/CMBaseViewController/CMBaseViewController.swift | 1 | 646 | //
// CMBaseViewController.swift
// 易持家
//
// Created by 王木木 on 16/5/20.
// Copyright © 2016年 王木木. All rights reserved.
//
import UIKit
class CMBaseViewController: UIViewController, UITabBarDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = .Top
}
func TitleWithWhiteColor(titleMessage: String) ->UIView{
let title = UILabel()
title.text = titleMessage;
title.textColor = UIColor.blueColor()
title.font = UIFont.boldSystemFontOfSize(17.0)
title.sizeToFit()
return title
}
}
| apache-2.0 | 82db6cd7c2c2da1097e31e199017942f | 20.551724 | 64 | 0.6288 | 4.280822 | false | false | false | false |
koutalou/iOS-CleanArchitecture | iOSCleanArchitectureTwitterSample/Presentation/UI/ViewController/TimelineViewController.swift | 1 | 4170 | //
// TimelineViewController.swift
// iOSCleanArchitectureTwitterSample
//
// Created by koutalou on 2015/12/20.
// Copyright © 2015年 koutalou. All rights reserved.
//
import UIKit
protocol TimelineViewInput: class {
func setCondition(isSelectable: Bool)
func setTimelinesModel(_: TimelinesModel)
func setUserModel(_: UserViewModel)
func changedStatus(_: TimelineStatus)
}
class TimelineViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var presenter: TimelinePresenter?
var timelines: [TimelineViewModel] = []
var timelineStatus:TimelineStatus = .loading
fileprivate let headerUserViewNib = Nib<TimelineUserHeaderView>()
fileprivate var headerUserView: TimelineUserHeaderView!
public func inject(presenter: TimelinePresenter) {
self.presenter = presenter
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
presenter?.loadCondition()
presenter?.loadTimelines()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let indexPathForSelectedRow = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPathForSelectedRow, animated: true)
}
}
}
// MARK: Private and Set Condition
extension TimelineViewController {
func setupUI() {
tableView.estimatedRowHeight = 70
tableView.rowHeight = UITableViewAutomaticDimension
headerUserView = headerUserViewNib.view()
}
}
// MARK: TimelineViewInput
extension TimelineViewController: TimelineViewInput {
func setCondition(isSelectable: Bool) {
tableView.allowsSelection = isSelectable
if !isSelectable {
navigationItem.rightBarButtonItem = nil
}
}
func setUserModel(_ userModel: UserViewModel) {
headerUserView.updateView(userModel)
tableView.tableHeaderView = headerUserView
}
func setTimelinesModel(_ timelinesModel: TimelinesModel) {
timelines = timelinesModel.timelines
self.tableView.reloadData()
}
func changedStatus(_ status: TimelineStatus) {
timelineStatus = status
self.tableView.reloadData()
}
}
// MARK: Button Event
extension TimelineViewController {
@IBAction func tapPersonButton(_ sender: Any) {
presenter?.tapPersonButton()
}
}
// MARK: Table view data source
extension TimelineViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (timelineStatus != .normal) {
return 1
}
return timelines.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch timelineStatus {
case .normal:
let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineViewCell", for: indexPath) as! TimelineViewCell
let timeline: TimelineViewModel = timelines[indexPath.row]
cell.updateCell(timeline)
return cell
case .notAuthorized:
return tableView.dequeueReusableCell(withIdentifier: "NotAuthorized", for: indexPath)
case .loading:
return tableView.dequeueReusableCell(withIdentifier: "Loading", for: indexPath)
case .error:
return tableView.dequeueReusableCell(withIdentifier: "Error", for: indexPath)
case .none:
return tableView.dequeueReusableCell(withIdentifier: "Nodata", for: indexPath)
}
}
}
// MARK: UITableView Delegate
extension TimelineViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch timelineStatus {
case .normal:
let timeline: TimelineViewModel = timelines[indexPath.row]
presenter?.selectCell(timeline: timeline)
default:
return
}
}
}
| mit | bc38d4be1cfdcaf5586b1c1f201f0c82 | 29.195652 | 125 | 0.667627 | 5.30828 | false | false | false | false |
Pyroh/Fluor | Fluor/Views/MultilinesCheckBoxLabel.swift | 1 | 2320 | //
// MultilinesCheckBoxLabel.swift
//
// Fluor
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Cocoa
class MultilinesCheckBoxLabel: NSTextField {
@IBOutlet weak var checkBox: NSButton!
override var isHighlighted: Bool {
didSet {
checkBox.isHighlighted = isHighlighted
}
}
private var isClicked = false
override func updateTrackingAreas() {
super.updateTrackingAreas()
self.trackingAreas.forEach(self.removeTrackingArea(_:))
let trackingArea = NSTrackingArea(rect: self.bounds, options: [.activeAlways, .mouseEnteredAndExited, .enabledDuringMouseDrag], owner: self, userInfo: nil)
self.addTrackingArea(trackingArea)
}
override func mouseDown(with event: NSEvent) {
isClicked = true
isHighlighted = true
}
override func mouseUp(with event: NSEvent) {
if isHighlighted { checkBox.performClick(self) }
isClicked = false
}
override func mouseEntered(with event: NSEvent) {
if isClicked { isHighlighted = true }
}
override func mouseExited(with event: NSEvent) {
if isClicked { isHighlighted = false }
}
}
| mit | fac2a098ce166cc60c1221f0e94a1559 | 33.626866 | 163 | 0.696552 | 4.668008 | false | false | false | false |
skyfe79/RxPlayground | RxToDoList-MVVM/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift | 23 | 2849 | //
// UIControl+Rx.swift
// RxCocoa
//
// Created by Daniel Tartaglia on 5/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
extension UIControl {
/**
Bindable sink for `enabled` property.
*/
public var rx_enabled: AnyObserver<Bool> {
return AnyObserver { [weak self] event in
MainScheduler.ensureExecutingOnScheduler()
switch event {
case .Next(let value):
self?.enabled = value
case .Error(let error):
bindingErrorToInterface(error)
break
case .Completed:
break
}
}
}
/**
Reactive wrapper for target action pattern.
- parameter controlEvents: Filter for observed event types.
*/
public func rx_controlEvent(controlEvents: UIControlEvents) -> ControlEvent<Void> {
let source: Observable<Void> = Observable.create { [weak self] observer in
MainScheduler.ensureExecutingOnScheduler()
guard let control = self else {
observer.on(.Completed)
return NopDisposable.instance
}
let controlTarget = ControlTarget(control: control, controlEvents: controlEvents) {
control in
observer.on(.Next())
}
return AnonymousDisposable {
controlTarget.dispose()
}
}.takeUntil(rx_deallocated)
return ControlEvent(events: source)
}
func rx_value<T: Equatable>(getter getter: () -> T, setter: T -> Void) -> ControlProperty<T> {
let source: Observable<T> = Observable.create { [weak self] observer in
guard let control = self else {
observer.on(.Completed)
return NopDisposable.instance
}
observer.on(.Next(getter()))
let controlTarget = ControlTarget(control: control, controlEvents: [.AllEditingEvents, .ValueChanged]) { control in
observer.on(.Next(getter()))
}
return AnonymousDisposable {
controlTarget.dispose()
}
}
.distinctUntilChanged()
.takeUntil(rx_deallocated)
return ControlProperty<T>(values: source, valueSink: AnyObserver { event in
MainScheduler.ensureExecutingOnScheduler()
switch event {
case .Next(let value):
setter(value)
case .Error(let error):
bindingErrorToInterface(error)
break
case .Completed:
break
}
})
}
}
#endif
| mit | 762c89ee0a513fbffbaa465f68789428 | 26.921569 | 127 | 0.545646 | 5.414449 | false | false | false | false |
KeyKrusher/FlappySwift | FlappyBird/GameViewController.swift | 2 | 2077 | //
// GameViewController.swift
// FlappyBird
//
// Created by Nate Murray on 6/2/14.
// Copyright (c) 2014 Fullstack.io. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(_ file : String) -> SKNode? {
let path = Bundle.main.path(forResource: file, ofType: "sks")
let sceneData: Data?
do {
sceneData = try Data(contentsOf: URL(fileURLWithPath: path!), options: .mappedIfSafe)
} catch _ {
sceneData = nil
}
let archiver = NSKeyedUnarchiver(forReadingWith: sceneData!)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObject(forKey: NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .aspectFill
skView.presentScene(scene)
}
}
override var shouldAutorotate : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return UIInterfaceOrientationMask.allButUpsideDown
} else {
return UIInterfaceOrientationMask.all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| mit | 8a8089221cd9f1d7f9a8e12e3deff132 | 28.671429 | 97 | 0.619162 | 5.494709 | false | false | false | false |
myriadmobile/Droar | Droar/Classes/Knob Core/DroarKnobSection.swift | 1 | 2205 | //
// DroarKnobSection.swift
// Droar
//
// Created by Alex Larson on 10/14/19.
//
import UIKit
public class DroarKnobSection {
//State
public private(set) var knobs: [DroarKnob]
public private(set) var title: String
public private(set) var positionInfo: PositionInfo
public private(set) var cellCountMappings: [Int]
//Init
public init(_ knob: DroarKnob) {
self.knobs = [knob]
self.title = knob.droarKnobTitle()
self.positionInfo = knob.droarKnobPosition()
self.cellCountMappings = [knob.droarKnobNumberOfCells()]
}
//Accessors
public func add(_ knob: DroarKnob) {
self.knobs.append(knob)
let positionInfo = knob.droarKnobPosition()
let position = max(self.positionInfo.position, positionInfo.position)
let priority = max(self.positionInfo.priority, positionInfo.priority)
self.positionInfo = PositionInfo(position: position, priority: priority)
cellCountMappings.append(knob.droarKnobNumberOfCells())
}
//Table Logic
func numberOfCells() -> Int {
var count = 0
for sectionCount in cellCountMappings {
count += sectionCount
}
return count
}
func droarKnobCellForIndex(index: Int, tableView: UITableView) -> DroarCell {
let indexPath = mappedIndex(index)
return knobs[indexPath.section].droarKnobCellForIndex(index: indexPath.row, tableView: tableView)
}
func droarKnobIndexSelected(tableView: UITableView, selectedIndex: Int) {
let indexPath = mappedIndex(selectedIndex)
knobs[indexPath.section].droarKnobIndexSelected?(tableView: tableView, selectedIndex: indexPath.row)
}
private func mappedIndex(_ index: Int) -> NSIndexPath {
var section = 0
var count = 0
for sectionCount in cellCountMappings {
if count + sectionCount <= index {
section += 1
count += sectionCount
} else {
break
}
}
return NSIndexPath(row: index - count, section: section)
}
}
| mit | 6b5fdeb68464ec10e68945f3714dfd64 | 28.4 | 108 | 0.617687 | 4.427711 | false | false | false | false |
belkevich/DTModelStorage | DTModelStorage/Utilities/MemoryStorage+DTCollectionViewManager.swift | 1 | 4694 | //
// MemoryStorage+DTCollectionViewManager.swift
// DTModelStorageTests
//
// Created by Denys Telezhkin on 24.08.15.
// Copyright © 2015 Denys Telezhkin. All rights reserved.
//
import Foundation
import UIKit
/// This protocol is used to determine, whether our delegate deals with UICollectionView
public protocol CollectionViewStorageUpdating
{
/// Perform animated update on UICollectionView. This is useful, when animation consists of several actions.
func performAnimatedUpdate(block : (UICollectionView) -> Void)
}
extension MemoryStorage
{
/// Remove all items from UICollectionView.
/// - Note: method will call .reloadData() when finishes.
public func removeAllCollectionItems()
{
guard let collectionViewDelegate = delegate as? CollectionViewStorageUpdating else { return }
for section in self.sections {
(section as! SectionModel).objects.removeAll(keepCapacity: false)
}
collectionViewDelegate.performAnimatedUpdate { collectionView in
collectionView.reloadData()
}
}
/// Move collection item from `sourceIndexPath` to `destinationIndexPath`.
/// - Parameter sourceIndexPath: indexPath from which we need to move
/// - Parameter toIndexPath: destination index path for table item
public func moveCollectionItemAtIndexPath(sourceIndexPath: NSIndexPath, toIndexPath: NSIndexPath)
{
guard self.delegate is CollectionViewStorageUpdating else { return }
self.startUpdate()
defer { self.currentUpdate = nil }
guard let item = self.objectAtIndexPath(sourceIndexPath) else {
print("DTCollectionViewManager: source indexPath should not be nil when moving collection item")
return
}
let sourceSection = self.getValidSection(sourceIndexPath.section)
let destinationSection = self.getValidSection(toIndexPath.section)
guard destinationSection.objects.count >= toIndexPath.item else {
print("DTCollectionViewManager: failed moving item to indexPath: \(toIndexPath), only \(destinationSection.objects.count) items in section")
return
}
(self.delegate as! CollectionViewStorageUpdating).performAnimatedUpdate { collectionView in
let sectionsToInsert = NSMutableIndexSet()
for index in 0..<self.currentUpdate!.insertedSectionIndexes.count {
if collectionView.numberOfSections() <= index {
sectionsToInsert.addIndex(index)
}
}
collectionView.performBatchUpdates({
collectionView.insertSections(sectionsToInsert)
}, completion: nil)
sourceSection.objects.removeAtIndex(sourceIndexPath.item)
destinationSection.objects.insert(item, atIndex: toIndexPath.item)
if sourceIndexPath.item == 0 && sourceSection.objects.count == 0 {
collectionView.reloadData()
}
else {
collectionView.performBatchUpdates({
collectionView.moveItemAtIndexPath(sourceIndexPath, toIndexPath: toIndexPath)
}, completion: nil)
}
}
}
/// Move collection view section
/// - Parameter sourceSection: index of section, from which we'll be moving
/// - Parameter destinationSection: index of section, where we'll be moving
public func moveCollectionViewSection(sourceSectionIndex: Int, toSection: Int)
{
guard self.delegate is CollectionViewStorageUpdating else { return }
self.startUpdate()
defer { self.currentUpdate = nil }
let sectionFrom = self.getValidSection(sourceSectionIndex)
let _ = self.getValidSection(toSection)
self.currentUpdate?.insertedSectionIndexes.removeIndex(toSection)
(self.delegate as! CollectionViewStorageUpdating).performAnimatedUpdate { collectionView in
if self.sections.count > collectionView.numberOfSections() {
collectionView.reloadData()
}
else {
collectionView.performBatchUpdates({
collectionView.insertSections(self.currentUpdate!.insertedSectionIndexes)
self.sections.removeAtIndex(sourceSectionIndex)
self.sections.insert(sectionFrom, atIndex: toSection)
collectionView.moveSection(sourceSectionIndex, toSection: toSection)
}, completion: nil)
}
}
}
} | mit | 3c955518a20bc246d839dda9c3e8315d | 40.539823 | 152 | 0.651396 | 5.815366 | false | false | false | false |
plus44/mhml-2016 | app/Helmo/Helmo/FallCellObject.swift | 1 | 746 | //
// FallCellObject.swift
// Helmo
//
// Created by Mihnea Rusu on 09/03/17.
// Copyright © 2017 Mihnea Rusu. All rights reserved.
//
import Foundation
import SwiftyJSON
struct FallCellObject: CustomStringConvertible {
var timestamp: CFTimeInterval! = nil
var severity: Int! = nil
var dataURL: String! = nil
var offset: Int! = nil
var description: String {
return "\nFall at offset \(offset)\n" +
"Timestamp: \(timestamp)\n" +
"Severity: \(severity)\n" +
"Data URL: \(dataURL)\n"
}
init(json: JSON) {
timestamp = json["timestamp"].doubleValue
dataURL = json["data_url"].stringValue
offset = json["offset"].intValue
}
}
| gpl-3.0 | 15e343b7e15a142ad24c6b13a2dfc32c | 23.833333 | 54 | 0.591946 | 3.941799 | false | false | false | false |
XeresRazor/SMGOLFramework | Sources/XMLNodeFilter.swift | 2 | 680 | //
// XMLNodeFilter.swift
// SMGOLFramework
//
// Created by David Green on 2/23/16.
// Copyright © 2016 David Green. All rights reserved.
//
import Foundation
class NodeFilter {
let node: Node
let filter: String
var index = 0
init(node: Node, filter: String) {
self.node = node
self.filter = filter
}
func next() -> Node? {
while index < node.childCount() {
let node = self.node.children[index]
index += 1
if !node.isTag {
continue
}
if node.text == filter {
return node
}
}
return nil
}
}
| mit | 6fab72cf8c7e43ecb75face8b13e5ffa | 18.970588 | 54 | 0.500736 | 4.140244 | false | false | false | false |
citysite102/kapi-kaffeine | kapi-kaffeine/kapi-kaffeine/KPSimpleRateModel.swift | 1 | 3193 | //
// KPSimpleRateModel.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/7/10.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import Foundation
import ObjectMapper
class KPSimpleRateModel: NSObject, Mappable {
var cheap: NSNumber? = 0
var food: NSNumber? = 0
var quiet: NSNumber? = 0
var seat: NSNumber? = 0
var wifi: NSNumber? = 0
var tasty: NSNumber? = 0
var music: NSNumber? = 0
var createdTime: NSNumber? = 0
var modifiedTime: NSNumber? = 0
var memberID: String?
var displayName: String?
var photoURL: String?
var createdModifiedContent: String! {
let diffInterval = Date().timeIntervalSince1970 - (createdTime?.doubleValue ?? 0)
if diffInterval < 10*60 {
return String(format: "剛剛", Int(diffInterval/60))
} else if diffInterval < 60*60 {
return String(format: "%d分鐘前", Int(diffInterval/60))
} else if diffInterval < 60*60*24 {
return String(format: "%d小時前", Int(diffInterval/(60*60)))
} else {
return String(format: "%d天前", Int(diffInterval/(60*60*24)))
}
}
var averageRate: CGFloat {
get {
var totalRate: CGFloat = 0
var availableRateCount: CGFloat = 0
if let rate = cheap?.cgFloatValue,
rate > 0 {
totalRate += rate
availableRateCount += 1
}
if let rate = food?.cgFloatValue,
rate > 0 {
totalRate += rate
availableRateCount += 1
}
if let rate = quiet?.cgFloatValue,
rate > 0 {
totalRate += rate
availableRateCount += 1
}
if let rate = seat?.cgFloatValue,
rate > 0 {
totalRate += rate
availableRateCount += 1
}
if let rate = wifi?.cgFloatValue,
rate > 0 {
totalRate += rate
availableRateCount += 1
}
if let rate = tasty?.cgFloatValue,
rate > 0 {
totalRate += rate
availableRateCount += 1
}
if let rate = music?.cgFloatValue,
rate > 0 {
totalRate += rate
availableRateCount += 1
}
return totalRate/availableRateCount
}
}
required init?(map: Map) {
}
func mapping(map: Map) {
cheap <- map["cheap"]
food <- map["food"]
quiet <- map["quiet"]
seat <- map["seat"]
wifi <- map["wifi"]
tasty <- map["tasty"]
music <- map["music"]
createdTime <- map["created_time"]
modifiedTime <- map["modified_time"]
memberID <- map["member_id"]
displayName <- map["display_name"]
photoURL <- map["photo_url"]
}
}
| mit | e9ceb7c381d361233b360302a1b1ff5c | 28.082569 | 89 | 0.470978 | 4.696296 | false | false | false | false |
Masteryyz/CSYMicroBlog_TestSina | CSSinaMicroBlog_Test/CSSinaMicroBlog_Test/Class/ViewModel(封装功能)/CSYGetUserInfoModel.swift | 1 | 4666 | //
// CSYGetUserInfoModel.swift
// CSSinaMicroBlog_Test
//
// Created by 姚彦兆 on 15/11/11.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
import AFNetworking
class CSYGetUserInfoModel: NSObject {
//对外提供用户的信息便捷获取方法
var userModel : CSYUserModel?
var userToken : String? {
return userModel?.access_token
}
var isLogin : Bool {
return userModel?.access_token != nil
}
override init() {
userModel = CSYUserModel.readUserPlist()
}
}
extension CSYGetUserInfoModel {
//使用AFN框架向网络发送请求
//根据得到的CODE来获得用户的信息
/**
请求地址:https://api.weibo.com/oauth2/access_token
HTTP请求方式
POST
请求参数 ----->
必选 类型及范围 说明
client_id true string 申请应用时分配的AppKey。
client_secret true string 申请应用时分配的AppSecret。
grant_type true string 请求的类型,填写authorization_code
grant_type为authorization_code时 ----->
必选 类型及范围 说明
code true string 调用authorize获得的code值。
redirect_uri true string 回调地址,需与注册应用里的回调地址一致。
- parameter userCode: 授权请求得到的code串
*/
func getUserInfoWithCode( code : String ,finishBlock : (errorMessage : NSError?) -> ()){
let requestURL = "https://api.weibo.com/oauth2/access_token"
let parameters : [String : AnyObject] = ["client_id" : client_id , "client_secret" : client_secret , "grant_type" : "authorization_code" , "code" : code , "redirect_uri" : redirect_uri]
let AFN = AFHTTPSessionManager()
AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
AFN.POST(requestURL, parameters: parameters, success: { (_, result) -> Void in
// >>>>>>>SHOWRESULT>>>>>>>>{
// "access_token" = "2.00fu7oCG0tFG7h324e19ff98oUkqTD";
// "expires_in" = 157679999;
// "remind_in" = 157679999;
// uid = 5538369521;
// }
if let userInfo = result as? [String : AnyObject]{
let userModel : CSYUserModel = CSYUserModel(userInfo: userInfo)
self.getUserMessageWith(userModel, finishBlock: finishBlock)
}
}) { (_, error) -> Void in
print("ERRORMESSAGE:\(error)")
}
}
func getUserMessageWith(userModel : CSYUserModel , finishBlock:(errorMessage : NSError?) -> ()){
/**
*
参数名称 类型及范围 说明
source false string 采用OAuth授权方式不需要此参数,其他授权方式为必填参数,数值为应用的AppKey。
access_token false string 采用OAuth授权方式为必填参数,其他授权方式不需要此参数,OAuth授权后获得。
uid false int64 需要查询的用户ID。
*/
//Sina官方API --> 获取用户信息的URL请求地址() : https://api.weibo.com/2/users/show.json
let urlSTR = "https://api.weibo.com/2/users/show.json"
let paramaters : [String : AnyObject] = ["access_token" : userModel.access_token! , "uid" : userModel.uid!]
let AFN = AFHTTPSessionManager()
AFN.GET(urlSTR, parameters: paramaters, success: { (_, result) -> Void in
if let result : [String : AnyObject] = result as? [String : AnyObject]{
userModel.avatar_hd = result["avatar_hd"] as? String
userModel.name = result["name"] as? String
print("准备存储用户数据\(userModel)")
userModel.saveUserAccount()
finishBlock(errorMessage: nil)
}
}) { (_, error) -> Void in
finishBlock(errorMessage: error)
}
}
}
| mit | e22265cb2ec40a465bbb3131e144d022 | 22.891429 | 193 | 0.489357 | 4.500538 | false | false | false | false |
aojet/Aojet | Sources/Aojet/runtime/RuntimeEnvironment.swift | 1 | 538 | //
// RuntimeEnvironment.swift
// Aojet
//
// Created by Qihe Bian on 16/10/5.
// Copyright © 2016 Qihe Bian. All rights reserved.
//
public class RuntimeEnvironment {
private static var _isProduction: Bool? = nil
public static var isProduction: Bool {
get {
if _isProduction == nil {
print("RuntimeEnvironment.isProduction is not set, the default value is false.")
_isProduction = false
}
return _isProduction!
}
set(isProduction) {
_isProduction = isProduction
}
}
}
| mit | 3a1950f67286eeb0c36abef1fe988f5e | 21.375 | 88 | 0.640596 | 3.729167 | false | false | false | false |
juliangrosshauser/Countdown | Countdown/Source/CountdownViewModel.swift | 1 | 3069 | //
// CountdownViewModel.swift
// Countdown
//
// Created by Julian Grosshauser on 20/10/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
import Foundation
import ReactiveCocoa
public class CountdownViewModel {
//MARK: Properties
private static let BirthdayKey = "CountdownBirthdayKey"
public static let UserDefaultsSuiteName = "group.com.juliangrosshauser.Countdown"
private let userDefaults: NSUserDefaults
public let active = MutableProperty<Bool>(false)
private let startTimer: Action<Void, NSDate, NoError> = Action { timer(0.1, onScheduler: QueueScheduler()) }
private var startTimerDisposable: Disposable?
public let age = MutableProperty<Double?>(nil)
public var birthday: NSDate? {
get {
return userDefaults.objectForKey(CountdownViewModel.BirthdayKey) as? NSDate
}
set {
userDefaults.setObject(newValue, forKey: CountdownViewModel.BirthdayKey)
}
}
//MARK: Initialization
public init(userDefaults: NSUserDefaults) {
self.userDefaults = userDefaults
if let birthday = birthday {
age.value = ageForBirthday(birthday)
}
// Skip initial value
active.producer.skip(1).startWithNext { [unowned self] active in
if let startTimerDisposable = self.startTimerDisposable {
startTimerDisposable.dispose()
self.startTimerDisposable = nil
}
if active {
self.startTimerDisposable = self.startTimer.apply().start()
}
}
age <~ startTimer.values.map { [unowned self] _ in
guard let birthday = self.birthday else {
return nil
}
return self.ageForBirthday(birthday)
}
}
//MARK: Age Calculation
// Credits: https://github.com/soffes/Motivation/blob/master/Motivation/AgeView.swift
private func ageForBirthday(birthday: NSDate) -> Double {
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
let ageComponents = calendar.components([.Year, .Day, .Second, .Nanosecond], fromDate: birthday, toDate: now, options: [])
let daysInYear = Double(calendar.daysInYear(now))
let hoursInDay = Double(calendar.rangeOfUnit(.Hour, inUnit: .Day, forDate: now).length)
let minutesInHour = Double(calendar.rangeOfUnit(.Minute, inUnit: .Hour, forDate: now).length)
let secondsInMinute = Double(calendar.rangeOfUnit(.Second, inUnit: .Minute, forDate: now).length)
let nanosecondsInSecond = Double(calendar.rangeOfUnit(.Nanosecond, inUnit: .Second, forDate: now).length)
let seconds = Double(ageComponents.second) + Double(ageComponents.nanosecond) / nanosecondsInSecond
let minutes = seconds / secondsInMinute
let hours = minutes / minutesInHour
let days = Double(ageComponents.day) + hours / hoursInDay
let years = Double(ageComponents.year) + days / daysInYear
return years
}
}
| mit | 1a8732532033ea91da4d7144bfa67d51 | 34.674419 | 130 | 0.658735 | 4.741886 | false | false | false | false |
calosth/Instagram | Instragram/HomeTableViewController.swift | 1 | 3331 | //
// HomeTableViewController.swift
// Instragram
//
// Created by Carlos Linares on 4/30/15.
// Copyright (c) 2015 Carlos Linares. All rights reserved.
//
import UIKit
class HomeTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
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
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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 | 486434b682caa825a5616050bb7db93d | 33.340206 | 157 | 0.68508 | 5.588926 | false | false | false | false |
ashleybrgr/surfPlay | surfPlay/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotatePulse.swift | 12 | 4391 | //
// NVActivityIndicatorAnimationBallClipRotatePulse.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class NVActivityIndicatorAnimationBallClipRotatePulse: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let duration: CFTimeInterval = 1
let timingFunction = CAMediaTimingFunction(controlPoints: 0.09, 0.57, 0.49, 0.9)
smallCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color)
bigCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color)
}
func smallCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) {
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
animation.keyTimes = [0, 0.3, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circleSize = size.width / 2
let circle = NVActivityIndicatorShape.circle.layerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2,
y: (layer.bounds.size.height - circleSize) / 2,
width: circleSize,
height: circleSize)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
func bigCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) {
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.6, 1]
scaleAnimation.duration = duration
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.timingFunctions = [timingFunction, timingFunction]
rotateAnimation.values = [0, Double.pi, 2 * Double.pi]
rotateAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = NVActivityIndicatorShape.ringTwoHalfVertical.layerWith(size: size, color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| apache-2.0 | 4afc6b48eba1463ea73cf426ca8f240e | 43.353535 | 137 | 0.687998 | 4.950395 | false | false | false | false |
ashikahmad/SlideMenuControllerSwift | SlideMenuControllerSwift/MainViewController.swift | 5 | 2948 | //
// ViewController.swift
// SlideMenuControllerSwift
//
// Created by Yuji Hato on 12/3/14.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var mainContens = ["data1", "data2", "data3", "data4", "data5", "data6", "data7", "data8", "data9", "data10", "data11", "data12", "data13", "data14", "data15"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerCellNib(DataTableViewCell.self)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension MainViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return DataTableViewCell.height()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "SubContentsViewController", bundle: nil)
let subContentsVC = storyboard.instantiateViewController(withIdentifier: "SubContentsViewController") as! SubContentsViewController
self.navigationController?.pushViewController(subContentsVC, animated: true)
}
}
extension MainViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.mainContens.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: DataTableViewCell.identifier) as! DataTableViewCell
let data = DataTableViewCellData(imageUrl: "dummy", text: mainContens[indexPath.row])
cell.setData(data)
return cell
}
}
extension MainViewController : SlideMenuControllerDelegate {
func leftWillOpen() {
print("SlideMenuControllerDelegate: leftWillOpen")
}
func leftDidOpen() {
print("SlideMenuControllerDelegate: leftDidOpen")
}
func leftWillClose() {
print("SlideMenuControllerDelegate: leftWillClose")
}
func leftDidClose() {
print("SlideMenuControllerDelegate: leftDidClose")
}
func rightWillOpen() {
print("SlideMenuControllerDelegate: rightWillOpen")
}
func rightDidOpen() {
print("SlideMenuControllerDelegate: rightDidOpen")
}
func rightWillClose() {
print("SlideMenuControllerDelegate: rightWillClose")
}
func rightDidClose() {
print("SlideMenuControllerDelegate: rightDidClose")
}
}
| mit | 7a3fda5ab4c3b61cdebf64901d6b2c41 | 30.031579 | 163 | 0.690977 | 5.135889 | false | false | false | false |
ShengQiangLiu/arcgis-runtime-samples-ios | FindTaskSample/swift/FindTask/Controllers/FindTaskViewController.swift | 4 | 10074 | //
// Copyright 2014 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm
//
import UIKit
import ArcGIS
//constants for title, search bar placeholder text and data layer
let kViewTitle = "US State/City/River"
let kSearchBarPlaceholder = "Find State/City/River"
let kDynamicMapServiceURL = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer"
let kTiledMapServiceURL = "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer"
let kResultsSegueIdentifier = "ResultsSegue"
class FindTaskViewController: UIViewController, AGSMapViewLayerDelegate, AGSCalloutDelegate, AGSLayerCalloutDelegate, AGSFindTaskDelegate, UISearchBarDelegate {
@IBOutlet weak var mapView:AGSMapView!
@IBOutlet weak var searchBar:UISearchBar!
var dynamicLayer:AGSDynamicMapServiceLayer!
var dynamicLayerView:UIView!
var graphicsLayer:AGSGraphicsLayer!
var findTask:AGSFindTask!
var findParams:AGSFindParameters!
var cityCalloutTemplate:AGSCalloutTemplate!
var riverCalloutTemplate:AGSCalloutTemplate!
var stateCalloutTemplate:AGSCalloutTemplate!
var selectedGraphic:AGSGraphic!
override func viewDidLoad() {
super.viewDidLoad()
//title for the navigation controller
self.title = kViewTitle
//text in search bar before user enters in query
self.searchBar.placeholder = kSearchBarPlaceholder
//set map view delegate
self.mapView.layerDelegate = self
self.mapView.callout.delegate = self
//create and add a base layer to map
let tiledMapServiceLayer = AGSTiledMapServiceLayer(URL: NSURL(string: kTiledMapServiceURL))
self.mapView.addMapLayer(tiledMapServiceLayer, withName:"World Street Map")
//create and add dynamic layer to map
self.dynamicLayer = AGSDynamicMapServiceLayer(URL: NSURL(string: kDynamicMapServiceURL))
self.mapView.addMapLayer(self.dynamicLayer, withName:"Dynamic Layer")
//create and add graphics layer to map
self.graphicsLayer = AGSGraphicsLayer()
self.mapView.addMapLayer(self.graphicsLayer, withName:"Graphics Layer")
//set the callout delegate so that we can show an appropriate callout for graphics
self.graphicsLayer.calloutDelegate = self
//create find task and set the delegate
self.findTask = AGSFindTask(URL: NSURL(string: kDynamicMapServiceURL))
self.findTask.delegate = self
//create find task parameters
self.findParams = AGSFindParameters()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
//MARK: -
//MARK: AGSMapViewLayerDelegate
func mapViewDidLoad(mapView: AGSMapView!) {
let spatialReference = AGSSpatialReference.wgs84SpatialReference()
//zoom to dynamic layer
let envelope = AGSEnvelope(xmin: -178.217598362366, ymin:18.9247817993164, xmax:-66.9692710360024, ymax:71.4062353532712, spatialReference:spatialReference)
let geometryEngine = AGSGeometryEngine()
let webMercatorEnvelope = geometryEngine.projectGeometry(envelope, toSpatialReference: self.mapView.spatialReference) as! AGSEnvelope
self.mapView.zoomToEnvelope(webMercatorEnvelope, animated:true)
}
//MARK: -
//MARK: AGSCalloutDelegate
func didClickAccessoryButtonForCallout(callout: AGSCallout!) {
//save selected graphic to assign it to the results view controller
self.selectedGraphic = callout.representedObject as! AGSGraphic
self.performSegueWithIdentifier(kResultsSegueIdentifier, sender:self)
}
//MARK: - UISearchBarDelegate
//when the user searches
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
//hide the callout
self.mapView.callout.hidden = true
//set find task parameters
self.findParams.contains = true
self.findParams.layerIds = ["2","1","0"]
self.findParams.outSpatialReference = self.mapView.spatialReference
self.findParams.returnGeometry = true
self.findParams.searchFields = ["CITY_NAME","NAME","STATE_ABBR","STATE_NAME"]
self.findParams.searchText = searchBar.text
//execute find task
self.findTask.executeWithParameters(self.findParams)
searchBar.resignFirstResponder()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
//MARK: - AGSFindTaskDelegate
func findTask(findTask: AGSFindTask!, operation op: NSOperation!, didExecuteWithFindResults results: [AnyObject]!) {
//clear previous results
self.graphicsLayer.removeAllGraphics()
//use these to calculate extent of results
var xmin = DBL_MAX
var ymin = DBL_MAX
var xmax = -DBL_MAX
var ymax = -DBL_MAX
//result object
var result:AGSFindResult!
//loop through all results
for (var i=0 ; i < results.count ; i++) {
//set the result object
result = results[i] as! AGSFindResult
//accumulate the min/max
if (result.feature.geometry.envelope.xmin < xmin) {
xmin = result.feature.geometry.envelope.xmin
}
if (result.feature.geometry.envelope.xmax > xmax) {
xmax = result.feature.geometry.envelope.xmax
}
if (result.feature.geometry.envelope.ymin < ymin) {
ymin = result.feature.geometry.envelope.ymin
}
if (result.feature.geometry.envelope.ymax > ymax) {
ymax = result.feature.geometry.envelope.ymax
}
//if result feature geometry is point/polyline/polygon
if (result.feature.geometry is AGSPoint) {
//create and set marker symbol
let symbol = AGSSimpleMarkerSymbol()
symbol.color = UIColor.yellowColor()
symbol.style = .Diamond
result.feature.symbol = symbol
}
else if (result.feature.geometry is AGSPolyline) {
//create and set simple line symbol
let symbol = AGSSimpleLineSymbol()
symbol.style = .Solid
symbol.color = UIColor.blueColor()
symbol.width = 2
result.feature.symbol = symbol
}
else if (result.feature.geometry is AGSPolygon) {
//create and set simple line symbol
let outline = AGSSimpleLineSymbol()
outline.style = .Solid
outline.color = UIColor.redColor()
outline.width = 2
let symbol = AGSSimpleFillSymbol()
symbol.outline = outline
result.feature.symbol = symbol
}
//add graphic to graphics layer
self.graphicsLayer.addGraphic(result.feature)
}
if results.count == 1 {
//we have one result, center at that point
self.mapView.centerAtPoint(result.feature.geometry.envelope.center, animated:false)
//show the callout
self.mapView.callout.showCalloutAtPoint(result.feature.geometry.envelope.center, forFeature:result.feature, layer:result.feature.layer, animated:true)
}
//if we have more than one result, zoom to the extent of all results
if results.count > 1 {
let extent = AGSMutableEnvelope(xmin: xmin, ymin:ymin, xmax:xmax, ymax:ymax, spatialReference:self.mapView.spatialReference)
extent.expandByFactor(1.5)
self.mapView.zoomToEnvelope(extent, animated:true)
}
}
//if there's an error with the find display it to the user
func findTask(findTask: AGSFindTask!, operation op: NSOperation!, didFailWithError error: NSError!) {
UIAlertView(title: "Error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "Ok").show()
}
//MARK: - AGSLayerCalloutDelegate
func callout(callout: AGSCallout!, willShowForFeature feature: AGSFeature!, layer: AGSLayer!, mapPoint: AGSPoint!) -> Bool {
//set callout width
self.mapView.callout.width = 200
self.mapView.callout.detail = "Click for more detail.."
if feature.hasAttributeForKey("CITY_NAME") {
self.mapView.callout.title = feature.attributeAsStringForKey("CITY_NAME")
}
else if feature.hasAttributeForKey("NAME") {
self.mapView.callout.title = feature.attributeAsStringForKey("NAME")
}
else if feature.hasAttributeForKey("STATE_NAME") {
self.mapView.callout.title = feature.attributeAsStringForKey("STATE_NAME")
}
return true
}
//MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == kResultsSegueIdentifier {
let controller = segue.destinationViewController as! ResultsViewController
controller.results = self.selectedGraphic.allAttributes()
}
}
}
| apache-2.0 | 409f1dd50376b1855cc9dc04bfba0eec | 38.818182 | 164 | 0.643339 | 4.984661 | false | false | false | false |
janukobytsch/cardiola | cardiola/NSDate+SameDay.swift | 1 | 1266 | //
// NSDate+SameDay.swift
// cardiola
//
// Created by Janusch Jacoby on 31/01/16.
// Copyright © 2016 BPPolze. All rights reserved.
//
import Foundation
extension NSDate {
var day: Int {
let components = self.getAllComponentsForCurrentCalendar()
return components.day
}
var month: Int {
let components = self.getAllComponentsForCurrentCalendar()
return components.month
}
var year: Int {
let components = self.getAllComponentsForCurrentCalendar()
return components.year
}
func isSameDayAs(otherDate: NSDate) -> Bool {
let calendar = NSCalendar.currentCalendar()
let unitFlags = NSCalendarUnit(rawValue: UInt.max)
let comp1 = calendar.components(unitFlags, fromDate: self)
let comp2 = calendar.components(unitFlags, fromDate: otherDate)
return comp1.day == comp2.day
&& comp1.month == comp2.month
&& comp1.year == comp2.year
}
func getAllComponentsForCurrentCalendar() -> NSDateComponents {
let calendar = NSCalendar.currentCalendar()
let unitFlags = NSCalendarUnit(rawValue: UInt.max)
return calendar.components(unitFlags, fromDate: self)
}
} | mit | caa8a7bf78cebb959eda24b205a3299e | 27.133333 | 71 | 0.642688 | 4.566787 | false | false | false | false |
edmw/Volumio_ios | Volumio/DefaultStringConvertible.swift | 1 | 6212 | //
// DefaultStringConvertible.swift
//
// Created by Michael Baumgärtner on 17.11.16.
// Copyright © 2016 Michael Baumgärtner. All rights reserved.
//
public protocol DefaultStringConvertible {
}
public extension DefaultStringConvertible {
public var defaultDescription: String {
return generateDescription(self)
}
public var defaultDebugDescription: String {
return generateDebugDescription(self)
}
public var description: String {
return defaultDescription
}
public var debugDescription: String {
return defaultDebugDescription
}
}
private func generateDescription(_ any: Any) -> String {
let mirror = Mirror(reflecting: any)
var children = Array(mirror.children)
var superclassMirror = mirror.superclassMirror
repeat {
if let superChildren = superclassMirror?.children {
children.append(contentsOf: superChildren)
}
superclassMirror = superclassMirror?.superclassMirror
} while superclassMirror != nil
let chunks = children.map { (label: String?, value: Any) -> String in
if let label = label {
if value is String {
return "\(label): \"\(value)\""
}
return "\(label): \(value)"
}
return "\(value)"
}
if chunks.count > 0 {
let chunksString = chunks.joined(separator: ", ")
return "\(mirror.subjectType)(\(chunksString))"
}
return "\(type(of: any))"
}
private func generateDebugDescription(_ any: Any) -> String {
func indentedString(_ string: String) -> String {
return string.characters
.split(separator: "\r")
.map(String.init)
.map { $0.isEmpty ? "" : "\r \($0)" }
.joined(separator: "")
}
func unwrap(_ any: Any) -> Any? {
let mirror = Mirror(reflecting: any)
if mirror.displayStyle != .optional {
return any
}
if let child = mirror.children.first, child.label == "some" {
return unwrap(child.value)
}
return nil
}
guard let any = unwrap(any) else {
return "nil"
}
if any is Void {
return "Void"
}
if let int = any as? Int {
return String(int)
} else if let double = any as? Double {
return String(double)
} else if let float = any as? Float {
return String(float)
} else if let bool = any as? Bool {
return String(bool)
} else if let string = any as? String {
return "\"\(string)\""
}
let mirror = Mirror(reflecting: any)
var properties = Array(mirror.children)
var typeName = String(describing: mirror.subjectType)
if typeName.hasSuffix(".Type") {
typeName = ""
} else {
typeName = "<\(typeName)> "
}
guard let displayStyle = mirror.displayStyle else {
return "\(typeName)\(String(describing: any))"
}
switch displayStyle {
case .tuple:
if properties.isEmpty {
return "()"
}
var string = "("
for (index, property) in properties.enumerated() {
if property.label!.characters.first! == "." {
string += generateDebugDescription(property.value)
} else {
string += "\(property.label!): \(generateDebugDescription(property.value))"
}
string += (index <= properties.count ? ", " : "")
}
return string + ")"
case .collection, .set:
if properties.isEmpty {
return "[]"
}
var string = "["
for (index, property) in properties.enumerated() {
string += indentedString(generateDebugDescription(property.value)
+ (index <= properties.count ? ",\r" : ""))
}
return string + "\r]"
case .dictionary:
if properties.isEmpty {
return "[:]"
}
var string = "["
for (index, property) in properties.enumerated() {
let pair = Array(Mirror(reflecting: property.value).children)
string += indentedString("\(generateDebugDescription(pair[0].value)): \(generateDebugDescription(pair[1].value))"
+ (index <= properties.count ? ",\r" : ""))
}
return string + "\r]"
case .enum:
if !(any is DefaultStringConvertible), let any = any as? CustomDebugStringConvertible {
return any.debugDescription
}
if properties.isEmpty {
return "\(mirror.subjectType)." + String(describing: any)
}
var string = "\(mirror.subjectType).\(properties.first!.label!)"
let associatedValueString = generateDebugDescription(properties.first!.value)
if associatedValueString.characters.first! == "(" {
string += associatedValueString
} else {
string += "(\(associatedValueString))"
}
return string
case .struct, .class:
if !(any is DefaultStringConvertible), let any = any as? CustomDebugStringConvertible {
return any.debugDescription
}
var superclassMirror = mirror.superclassMirror
repeat {
if let superChildren = superclassMirror?.children {
properties.append(contentsOf: superChildren)
}
superclassMirror = superclassMirror?.superclassMirror
} while superclassMirror != nil
if properties.isEmpty {
return "\(typeName)\(String(describing: any))"
}
var typeString = "\(typeName){"
for (index, property) in properties.enumerated() {
var propertyString = "\(property.label!): "
if let value = unwrap(property.value) as? DefaultStringConvertible {
propertyString += String(reflecting: value)
} else {
propertyString += generateDebugDescription(property.value)
}
typeString += indentedString(propertyString + (index <= properties.count ? ",\r" : ""))
}
return typeString + "\r}"
case .optional:
return generateDebugDescription(any)
}
}
| gpl-3.0 | ff65ea4baa3550c6bba21518232bb439 | 28.150235 | 125 | 0.572717 | 4.935612 | false | false | false | false |
vamsikvk915/fusion | Fusion/Fusion/UserDataProvider.swift | 1 | 1332 | //
// UserDataProvider.swift
// Fusion
//
// Created by Mohammad Irteza Khan on 7/31/17.
// Copyright © 2017 Mohammad Irteza Khan. All rights reserved.
//
import Foundation
import CoreData
import SwiftKeychainWrapper
class UserDataProvider{
static var user = [User]()
static let loggedInUser = KeychainWrapper.standard.string(forKey: currentUser)
static let userFetchRequest = NSFetchRequest<User>(entityName: "User")
public static func getUserPhoto() -> UIImage{
userFetchRequest.predicate = NSPredicate(format: "userID == %@", loggedInUser!)
do{
user = try CoreDataStack.sharedCoreDataStack.persistentContainer.viewContext.fetch(userFetchRequest)
return UIImage.init(data: (user.first?.userPhoto)!)!
} catch let error{
print(error)
}
return #imageLiteral(resourceName: "profile-photo-placeholder")
}
public static func getUserZipCode() -> String?{
userFetchRequest.predicate = NSPredicate(format: "userID == %@", loggedInUser!)
do{
user = try CoreDataStack.sharedCoreDataStack.persistentContainer.viewContext.fetch(userFetchRequest)
return (user.first?.zipCode)!
} catch let error{
print(error)
}
return nil
}
}
| apache-2.0 | b1843bf92052ca2e5d95b8bec1196e5a | 29.25 | 112 | 0.654395 | 4.857664 | false | false | false | false |
OpenStreetMap-Monitoring/iOsMo | iOsmo/HistoryViewController.swift | 2 | 6340 | //
// HistoryViewController.swift
// iOsMo
//
// Created by Alexey Sirotkin on 22.05.2019.
// Copyright © 2019 Alexey Sirotkin. All rights reserved.
//
import Foundation
class HistoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var connectionManager = ConnectionManager.sharedConnectionManager
var groupManager = GroupManager.sharedGroupManager
var history: [History] = [History]()
var onHistoryUpdated: ObserverSetEntry<(Int, Any)>?
var task: URLSessionDownloadTask!
var session: URLSession!
var cache:NSCache<AnyObject, AnyObject>!
private let refreshControl = UIRefreshControl()
let trackCell = "trackCell"
override func viewWillAppear(_ animated:Bool) {
print("HistoryViewController WillApear")
super.viewWillAppear(animated)
getHistory()
}
private func getHistory() {
history.removeAll()
connectionManager.getHistory()
}
@objc private func refreshHistory(_ sender: Any) {
getHistory()
}
override func viewDidLoad() {
super.viewDidLoad()
print("HistoryViewController viewDidLoad")
session = URLSession.shared
//task = URLSessionDownloadTask()
self.cache = NSCache()
// Add Refresh Control to Table View
self.tableView.refreshControl = refreshControl
// Configure Refresh Control
refreshControl.addTarget(self, action: #selector(refreshHistory(_:)), for: .valueChanged)
self.onHistoryUpdated = self.connectionManager.historyReceived.add{
let jsonarr = $1 as! Array<AnyObject>
_ = $0
for m in jsonarr {
let track = History.init(json: m as! Dictionary<String, AnyObject>)
self.history.append(track)
}
DispatchQueue.main.async {
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
}
}
// MARK UITableViewDelegate
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return nil;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return history.count;
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return (tableView.frame.width < 400 ? tableView.frame.width + 20 : 400);
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = (indexPath as NSIndexPath).row
let section = (indexPath as NSIndexPath).section
var cell: UITableViewCell?
if (section == 0) {
cell = tableView.dequeueReusableCell(withIdentifier: trackCell, for: indexPath)
if (cell == nil) {
cell = UITableViewCell(style:UITableViewCell.CellStyle.default, reuseIdentifier:trackCell)
}
if (row < history.count) {
let trip = history[row]
if let nameLabel = cell!.contentView.viewWithTag(1) as? UILabel{
nameLabel.text = trip.name
}
if let distanceLabel = cell!.contentView.viewWithTag(2) as? UILabel{
distanceLabel.text = String(format:"%.3f", trip.distantion)
}
if let dateLabel = cell!.contentView.viewWithTag(3) as? UILabel{
let dateFormat = DateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd HH:mm:ss"
let formatedTime = dateFormat.string(from: trip.start!)
dateLabel.text = "\(formatedTime)"
}
if let trackImage = cell!.contentView.viewWithTag(4) as? UIImageView{
if (self.cache.object(forKey: trip) != nil){
// Изображение есть в кэше, грузиь не нужно
trackImage.image = self.cache.object(forKey: trip) as? UIImage
}else{
// 3
let imageUrl = trip.image
let url:URL! = URL(string: imageUrl)
task = session.downloadTask(with: url, completionHandler: { (location, response, error) -> Void in
if let data = try? Data(contentsOf: url){
// 4
DispatchQueue.main.async(execute: { () -> Void in
// 5
// Before we assign the image, check whether the current cell is visible
if let updateCell = tableView.cellForRow(at: indexPath) {
if let img:UIImage = UIImage(data: data), let curTrackImage = updateCell.contentView.viewWithTag(4) as? UIImageView {
curTrackImage.image = img
self.cache.setObject(img, forKey: trip)
}
}
})
}
})
task.resume()
}
}
}
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (indexPath.row >= history.count) {
return
}
let track = Track.init(track: history[indexPath.row])
groupManager.getTrackData(track)
let tbc:UITabBarController = self.tabBarController!
let mvc: MapViewController = tbc.viewControllers![2] as! MapViewController;
mvc.putHistoryOnMap(tracks: [track])
tbc.selectedViewController = mvc;
}
}
| gpl-3.0 | 0a4ff3733876e457474037ccf395b0ad | 38.4125 | 157 | 0.550428 | 5.49782 | false | false | false | false |
nkskalyan/ganesh-yrg | EcoKitchen-iOS/EcoKitcheniOSHackathon/FlowViewController.swift | 1 | 2268 | //
// FlowViewController.swift
// EcoKitcheniOSHackathon
//
// Created by mh53653 on 11/12/16.
// Copyright © 2016 madan. All rights reserved.
//
import UIKit
class FlowViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
let flowNames = ["Refer Enterpreneur","Refer Location","Find Near By Kiosks","About Us","Feedback"];
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad();
tableView.dataSource = self;
tableView.delegate = self;
tableView.tableFooterView = UIView()
self.navigationItem.setHidesBackButton(true, animated:true);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return flowNames.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let flowCell = tableView.dequeueReusableCell(withIdentifier: "flowCell", for: indexPath) as? FlowTableViewCell {
flowCell.updateUI(flowName: flowNames[indexPath.row]);
return flowCell;
}
return UITableViewCell();
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0{
performSegue(withIdentifier: "RefEntrepreneurViewController", sender: nil);
}
else if indexPath.row == 1 {
performSegue(withIdentifier: "LocationViewController", sender: nil);
}
else if indexPath.row == 2 {
performSegue(withIdentifier: "NearByLocationViewController", sender: nil);
}
else if indexPath.row == 3 {
performSegue(withIdentifier: "AboutUsViewController", sender: nil);
}
else if indexPath.row == 4 {
performSegue(withIdentifier: "FeedbackViewController", sender: nil);
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.tableView.frame.size.height / 5
}
}
| apache-2.0 | 2ff3d026985fb6401e104b8b2f23f843 | 31.855072 | 123 | 0.653286 | 5.048998 | false | false | false | false |
jaanussiim/weather-scrape | Sources/WeatherPoint.swift | 1 | 2249 | /*
* Copyright 2016 JaanusSiim
*
* 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
struct WeatherPoint {
let name: String
let lat: Double
let lng: Double
let temperature: Double
let conditions: String?
let precipitation: Double
let windChill: Double
let windDirection: Int
let windStrength: Double
static func from(table: Table) -> [WeatherPoint] {
var result = [WeatherPoint]()
for row in table.rows {
guard let name = row.column(named: "Station")?.value else {
continue
}
//TODO jaanus: check issue where Tuulemäe coordinates not merged
let lat = row.double("Lat")
guard lat > -1000 else {
continue
}
let lng = row.double("Lng")
guard lng > -1000 else {
continue
}
let temperature = row.double("Air temperature (°C)")
let conditions = row.column(named: "Present weather (sensor)")?.value.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let precipitation = row.double("Precipitation (mm)")
let windChill = row.double("Wind chill (°C)")
let windDirection = row.integer("Wind - direction (°)")
let windStrength = row.double("Wind - speed (m/s)")
let point = WeatherPoint(name: name, lat: lat, lng: lng, temperature: temperature, conditions: conditions, precipitation: precipitation, windChill: windChill, windDirection: windDirection, windStrength: windStrength)
result.append(point)
}
return result
}
}
| apache-2.0 | 393314747de76e60a4664820f5c6e7b6 | 35.209677 | 228 | 0.616481 | 4.726316 | false | false | false | false |
johnpatrickmorgan/wtfautolayout | Sources/App/Parsing/ConstraintsParser+Instances.swift | 1 | 2769 | import Foundation
import Sparse
// MARK: - Instances
// (e.g. "UIImageView:0x7fd382f50 'avatar'")
extension ConstraintsParser {
static let instance = className.then(address).thenSkip(optional(fileLocation)).thenSkip(wss).then(optional(identifier))
.map(flatten)
.map { Instance(className: $0, address: $1, identifier: $2) }
.named("instance")
static let infoInstance = classOrName.then(address).thenSkip(optional(fileLocation)).thenSkip(wss).then(optional(identifier))
.map(flatten)
.map { Instance(className: $0, address: $1, identifier: $2) }
.named("info instance")
static let constraintInstance = className.then(address).thenSkip(optional(fileLocation)).thenSkip(al1ws)
.then(isFromAutoresizingMask.thenSkip(wss))
.then(optional(identifier.thenSkip(al1ws)))
.map(flatten)
.map { (Instance(className: $0, address: $1, identifier: $3), $2) }
.named("constraint instance")
static let partialInstance = instance.map({ PartialInstance.instance($0) }).otherwise(partialInstanceIdentifier)
}
private extension ConstraintsParser {
static let classNameCharacter = character(condition: isClassNameCharacter)
.named("valid class name character")
static let className = many(classNameCharacter, untilSkipping: colon).asString()
static let address = string("0x").then(many(hexit)).map { "\($0.0)\(String($0.1))" }
.named("memory address")
static let identifier = many(identifierCharacter.butNot(sqm), boundedBy: sqm).asString()
.named("identifier")
static let fileLocation = character("@").skipThen(many(anyCharacter(), untilSkipping: character("#")).asString()).then(integer)
.named("file location")
static let partialIdentifierCharacter = characterNot(in: "[]|()<>\":")
.named("valid partial identifier character")
static let partialInstanceIdentifier = many(identifierCharacter.and(partialIdentifierCharacter), untilSkipping: dotAttribute.withoutConsuming()).asString()
.map { PartialInstance.identifier($0) }
static let classOrName = many(identifierCharacter, untilSkipping: colon).asString()
static let isFlexible = character(in: "&-").map { $0 == "&" }
static let (h, v) = (string("h="), string("v="))
static let autoresizingIntro = h.skipThen(exactly(3, isFlexible)).thenSkip(wss)
.thenSkip(v).then(exactly(3, isFlexible)).thenSkip(wss)
static let isFromAutoresizingMask = optional(autoresizingIntro).map { $0 != nil }
.named("autoresizing mask info")
static func isClassNameCharacter(_ character: Character) -> Bool {
return CharacterSet.classNameCharacters.contains(character.unicodeScalar())
}
}
| mit | 7a412fda509f9a017addf13670a1b13e | 46.741379 | 159 | 0.687613 | 4.139013 | false | false | false | false |
AsyncNinja/AsyncNinja | Sources/AsyncNinja/MergeFutures.swift | 1 | 3075 | //
// Copyright (c) 2016-2017 Anton Mironov
//
// 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 Dispatch
/// Merges two `Completing`s (e.g. `Future`s). `Completing` that completes first completes the result
///
/// - Parameters:
/// - a: first `Completing`
/// - b: second `Completing`
/// - Returns: future of merged arguments.
public func merge<A: Completing, B: Completing>(_ a: A, _ b: B) -> Future<A.Success>
where A.Success == B.Success {
let promise = Promise<A.Success>()
promise.complete(with: a)
promise.complete(with: b)
return promise
}
/// Merges three `Completing`s (e.g. `Future`s). `Completing` that completes first completes the result
///
/// - Parameters:
/// - a: first
/// - b: second
/// - c: third
/// - Returns: future of merged arguments.
public func merge<A: Completing, B: Completing, C: Completing>(_ a: A, _ b: B, _ c: C) -> Future<A.Success>
where A.Success == B.Success, A.Success == C.Success {
let promise = Promise<A.Success>()
promise.complete(with: a)
promise.complete(with: b)
promise.complete(with: c)
return promise
}
/// Merges two `Completing`s (e.g. `Future`s). `Completing` that completes first completes the result
///
/// - Parameters:
/// - a: first
/// - b: second
/// - Returns: future of merged arguments.
public func merge<A: Completing, B: Completing>(_ a: A, _ b: B) -> Future<Either<A.Success, B.Success>> {
let promise = Promise<Either<A.Success, B.Success>>()
let handlerA = a.makeCompletionHandler(
executor: .immediate
) { [weak promise] (completion, originalExecutor) in
promise?.complete(completion.map(Either.left), from: originalExecutor)
}
promise._asyncNinja_retainHandlerUntilFinalization(handlerA)
let handlerB = b.makeCompletionHandler(
executor: .immediate
) { [weak promise] (completion, originalExecutor) in
promise?.complete(completion.map(Either.right), from: originalExecutor)
}
promise._asyncNinja_retainHandlerUntilFinalization(handlerB)
return promise
}
| mit | 368b1d9c626ba9a64602c880cfbcfb7f | 37.924051 | 107 | 0.704065 | 3.75 | false | false | false | false |
tid-kijyun/QiitaWatch | QiitaWatch WatchKit Extension/HeadLineTableRow.swift | 1 | 1213 | //
// HeadLineTableRow.swift
// QiitaWatch
//
// Created by tid on 2014/11/23.
// Copyright (c) 2014年 tid. All rights reserved.
//
import WatchKit
class HeadLineTableRow: NSObject {
@IBOutlet weak var icon: WKInterfaceImage!
@IBOutlet weak var headline: WKInterfaceLabel!
@IBOutlet weak var author: WKInterfaceLabel!
@IBOutlet weak var stock: WKInterfaceLabel!
var uuid: String = ""
var isStock : Bool = false {
didSet {
stock.setAlpha((isStock) ? 1.0 : 0.2)
}
}
var article : Article? = nil {
didSet {
if let art = article {
self.uuid = art.uuid
self.headline.setText(art.title)
self.author.setText(art.author)
self.isStock = art.isStock
let url = NSURL(string: art.authorImgUrl)
let request = NSURLRequest(URL:url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
let image = UIImage(data: data)
self.icon.setImage(image)
}
}
}
}
}
| mit | 4c236fe56ac07f4a694b3ee8ce8c85d6 | 27.833333 | 130 | 0.55161 | 4.501859 | false | false | false | false |
ilmDitsch/lingvo-swift-client | lingvo-swift-client/NetworkEngine.swift | 1 | 5724 | //
// NetworkEngine.swift
// lingvo-swift-client
//
// Created by Daniel on 06.01.16.
// Copyright © 2016 MicroMovie Media GmbH. All rights reserved.
//
import Foundation
enum NetworkEngineRequestMethod : String {
case Get = "GET"
case Post = "POST"
}
class NetworkEngine {
static let baseURL = URL(string: "http://")
func jsonRequest(_ endpoint: String, method: NetworkEngineRequestMethod, bodyParams: AnyObject?, baseURL : URL) -> URLRequest {
var request = URLRequest(url: (baseURL.appendingPathComponent(endpoint)))
request.httpMethod = method.rawValue
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(NSLocale.current.languageCode ?? "en", forHTTPHeaderField: "Accept-Language")
if bodyParams != nil {
request.httpBody = try! JSONSerialization.data(withJSONObject: bodyParams!, options: []);
}
return request
}
func jsonTask(_ endpoint: String, method: NetworkEngineRequestMethod, bodyParams: AnyObject?, baseURL: URL = NetworkEngine.baseURL!, finishedCallback: @escaping (NetworkEngineResponse) -> Void) -> URLSessionDataTask {
let request = self.jsonRequest(endpoint, method: method, bodyParams: bodyParams, baseURL: baseURL)
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
guard data != nil else {
print("no data found: \(error)")
finishedCallback(NetworkEngineResponse.errorResponse(error?._code, message: error?.localizedDescription))
return
}
// this, on the other hand, can quite easily fail if there's a server error, so you definitely
// want to wrap this in `do`-`try`-`catch`:
//let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
//print(jsonStr)
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
if let metadataDict = json["_metadata"] as? NSDictionary {
if let status = metadataDict["status"] as? String {
if status == "OK" {
//success
finishedCallback(NetworkEngineResponse.defaultResponse(try JSONSerialization.jsonObject(with: data!, options: []))) //we're using swifty json from here
} else {
//handle error
let errorCode = metadataDict["error_code"] as? Int
// let errorMessage = metadataDict["error_message"] as? String
// debugPrint(errorMessage ?? "")
finishedCallback(NetworkEngineResponse.errorResponse(errorCode))
}
} else {
print("no status")
finishedCallback(NetworkEngineResponse.defaultErrorResponse("no status: \(error)"))
}
} else {
print("no metadata")
finishedCallback(NetworkEngineResponse.defaultErrorResponse("no metadata: \(error)"))
}
} else {
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) // No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
finishedCallback(NetworkEngineResponse.defaultErrorResponse("Error could not parse JSON: \(jsonStr)"))
}
} catch let parseError {
print(parseError) // Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Error could not parse JSON: '\(jsonStr)'")
finishedCallback(NetworkEngineResponse.defaultErrorResponse("Error could not parse JSON: \(jsonStr)"))
}
}
return task
}
func jsonGetTask(_ endpoint: String, finishedCallback: @escaping (NetworkEngineResponse) -> Void) -> URLSessionDataTask {
return self.jsonTask(endpoint, method: .Get, bodyParams: nil, finishedCallback: finishedCallback)
}
func jsonPostTask(_ endpoint: String, bodyParams: AnyObject?, finishedCallback: @escaping (NetworkEngineResponse) -> Void) -> URLSessionDataTask {
return self.jsonTask(endpoint, method: .Post, bodyParams: bodyParams, finishedCallback: finishedCallback)
}
func downloadTask(_ endpoint: String, autoDecode: Bool, baseURL: URL = NetworkEngine.baseURL!, finishedCallback: @escaping (NetworkEngineResponse) -> Void) -> URLSessionDownloadTask {
let session = URLSession.shared
return session.downloadTask(with: baseURL.appendingPathComponent(endpoint), completionHandler: { (tmpUrl, response, error) -> Void in
guard error == nil else {
finishedCallback(NetworkEngineResponse.errorResponse(error?._code, message: error?.localizedDescription))
return
}
if tmpUrl != nil {
finishedCallback(NetworkEngineResponse.defaultDownloadResponse(tmpUrl!, decompressAndDecode: autoDecode))
} else {
finishedCallback(NetworkEngineResponse.defaultErrorResponse("no tmp url"))
}
})
}
}
| mit | 5cce0259418a5ae9eeca8d3580ede688 | 44.062992 | 218 | 0.595317 | 5.333644 | false | false | false | false |
lelandjansen/fatigue | ios/Pods/PhoneNumberKit/PhoneNumberKit/PhoneNumberParser.swift | 4 | 13204 | //
// PhoneNumberParser.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 26/09/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
/**
Parser. Contains parsing functions.
*/
final class PhoneNumberParser {
let metadata: MetadataManager
let regex: RegexManager
init(regex: RegexManager, metadata: MetadataManager) {
self.regex = regex
self.metadata = metadata
}
// MARK: Normalizations
/**
Normalize a phone number (e.g +33 612-345-678 to 33612345678).
- Parameter number: Phone number string.
- Returns: Normalized phone number string.
*/
func normalizePhoneNumber(_ number: String) -> String {
let normalizationMappings = PhoneNumberPatterns.allNormalizationMappings
return regex.stringByReplacingOccurrences(number, map: normalizationMappings)
}
// MARK: Extractions
/**
Extract country code (e.g +33 612-345-678 to 33).
- Parameter number: Number string.
- Parameter nationalNumber: National number string - inout.
- Parameter metadata: Metadata territory object.
- Returns: Country code is UInt64.
*/
func extractCountryCode(_ number: String, nationalNumber: inout String, metadata: MetadataTerritory) throws -> UInt64 {
var fullNumber = number
guard let possibleCountryIddPrefix = metadata.internationalPrefix else {
return 0
}
let countryCodeSource = stripInternationalPrefixAndNormalize(&fullNumber, possibleIddPrefix: possibleCountryIddPrefix)
if countryCodeSource != .defaultCountry {
if fullNumber.characters.count <= PhoneNumberConstants.minLengthForNSN {
throw PhoneNumberError.tooShort
}
if let potentialCountryCode = extractPotentialCountryCode(fullNumber, nationalNumber: &nationalNumber), potentialCountryCode != 0 {
return potentialCountryCode
}
else {
return 0
}
}
else {
let defaultCountryCode = String(metadata.countryCode)
if fullNumber.hasPrefix(defaultCountryCode) {
let nsFullNumber = fullNumber as NSString
var potentialNationalNumber = nsFullNumber.substring(from: defaultCountryCode.characters.count)
guard let validNumberPattern = metadata.generalDesc?.nationalNumberPattern, let possibleNumberPattern = metadata.generalDesc?.possibleNumberPattern else {
return 0
}
stripNationalPrefix(&potentialNationalNumber, metadata: metadata)
let potentialNationalNumberStr = potentialNationalNumber
if ((!regex.matchesEntirely(validNumberPattern, string: fullNumber) && regex.matchesEntirely(validNumberPattern, string: potentialNationalNumberStr )) || regex.testStringLengthAgainstPattern(possibleNumberPattern, string: fullNumber as String) == false) {
nationalNumber = potentialNationalNumberStr
if let countryCode = UInt64(defaultCountryCode) {
return UInt64(countryCode)
}
}
}
}
return 0
}
/**
Extract potential country code (e.g +33 612-345-678 to 33).
- Parameter fullNumber: Full number string.
- Parameter nationalNumber: National number string.
- Returns: Country code is UInt64. Optional.
*/
func extractPotentialCountryCode(_ fullNumber: String, nationalNumber: inout String) -> UInt64? {
let nsFullNumber = fullNumber as NSString
if nsFullNumber.length == 0 || nsFullNumber.substring(to: 1) == "0" {
return 0
}
let numberLength = nsFullNumber.length
let maxCountryCode = PhoneNumberConstants.maxLengthCountryCode
var startPosition = 0
if fullNumber.hasPrefix("+") {
if nsFullNumber.length == 1 {
return 0
}
startPosition = 1
}
for i in 1...numberLength {
if i > maxCountryCode {
break
}
let stringRange = NSMakeRange(startPosition, i)
let subNumber = nsFullNumber.substring(with: stringRange)
if let potentialCountryCode = UInt64(subNumber)
, metadata.territoriesByCode[potentialCountryCode] != nil {
nationalNumber = nsFullNumber.substring(from: i)
return potentialCountryCode
}
}
return 0
}
// MARK: Validations
func checkNumberType(_ nationalNumber: String, metadata: MetadataTerritory, leadingZero: Bool = false) -> PhoneNumberType {
if leadingZero {
let type = checkNumberType("0" + String(nationalNumber), metadata: metadata)
if type != .unknown {
return type
}
}
guard let generalNumberDesc = metadata.generalDesc else {
return .unknown
}
if (regex.hasValue(generalNumberDesc.nationalNumberPattern) == false || isNumberMatchingDesc(nationalNumber, numberDesc: generalNumberDesc) == false) {
return .unknown
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.pager)) {
return .pager
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.premiumRate)) {
return .premiumRate
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.tollFree)) {
return .tollFree
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.sharedCost)) {
return .sharedCost
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.voip)) {
return .voip
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.personalNumber)) {
return .personalNumber
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.uan)) {
return .uan
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.voicemail)) {
return .voicemail
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.fixedLine)) {
if metadata.fixedLine?.nationalNumberPattern == metadata.mobile?.nationalNumberPattern {
return .fixedOrMobile
}
else if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.mobile)) {
return .fixedOrMobile
}
else {
return .fixedLine
}
}
if (isNumberMatchingDesc(nationalNumber, numberDesc: metadata.mobile)) {
return .mobile
}
return .unknown
}
/**
Checks if number matches description.
- Parameter nationalNumber: National number string.
- Parameter numberDesc: MetadataPhoneNumberDesc of a given phone number type.
- Returns: True or false.
*/
func isNumberMatchingDesc(_ nationalNumber: String, numberDesc: MetadataPhoneNumberDesc?) -> Bool {
return regex.matchesEntirely(numberDesc?.nationalNumberPattern, string: nationalNumber)
}
/**
Checks and strips if prefix is international dialing pattern.
- Parameter number: Number string.
- Parameter iddPattern: iddPattern for a given country.
- Returns: True or false and modifies the number accordingly.
*/
func parsePrefixAsIdd(_ number: inout String, iddPattern: String) -> Bool {
if (regex.stringPositionByRegex(iddPattern, string: number) == 0) {
do {
guard let matched = try regex.regexMatches(iddPattern as String, string: number as String).first else {
return false
}
let matchedString = number.substring(with: matched.range)
let matchEnd = matchedString.characters.count
let remainString = (number as NSString).substring(from: matchEnd)
let capturingDigitPatterns = try NSRegularExpression(pattern: PhoneNumberPatterns.capturingDigitPattern, options: NSRegularExpression.Options.caseInsensitive)
let matchedGroups = capturingDigitPatterns.matches(in: remainString as String)
if let firstMatch = matchedGroups.first {
let digitMatched = remainString.substring(with: firstMatch.range) as NSString
if digitMatched.length > 0 {
let normalizedGroup = regex.stringByReplacingOccurrences(digitMatched as String, map: PhoneNumberPatterns.allNormalizationMappings)
if normalizedGroup == "0" {
return false
}
}
}
number = remainString as String
return true
}
catch {
return false
}
}
return false
}
// MARK: Strip helpers
/**
Strip an extension (e.g +33 612-345-678 ext.89 to 89).
- Parameter number: Number string.
- Returns: Modified number without extension and optional extension as string.
*/
func stripExtension(_ number: inout String) -> String? {
do {
let matches = try regex.regexMatches(PhoneNumberPatterns.extnPattern, string: number)
if let match = matches.first {
let adjustedRange = NSMakeRange(match.range.location + 1, match.range.length - 1)
let matchString = number.substring(with: adjustedRange)
let stringRange = NSMakeRange(0, match.range.location)
number = number.substring(with: stringRange)
return matchString
}
return nil
}
catch {
return nil
}
}
/**
Strip international prefix.
- Parameter number: Number string.
- Parameter possibleIddPrefix: Possible idd prefix for a given country.
- Returns: Modified normalized number without international prefix and a PNCountryCodeSource enumeration.
*/
func stripInternationalPrefixAndNormalize(_ number: inout String, possibleIddPrefix: String?) -> PhoneNumberCountryCodeSource {
if (regex.matchesAtStart(PhoneNumberPatterns.leadingPlusCharsPattern, string: number as String)) {
number = regex.replaceStringByRegex(PhoneNumberPatterns.leadingPlusCharsPattern, string: number as String)
return .numberWithPlusSign
}
number = normalizePhoneNumber(number as String)
guard let possibleIddPrefix = possibleIddPrefix else {
return .numberWithoutPlusSign
}
let prefixResult = parsePrefixAsIdd(&number, iddPattern: possibleIddPrefix)
if prefixResult == true {
return .numberWithIDD
}
else {
return .defaultCountry
}
}
/**
Strip national prefix.
- Parameter number: Number string.
- Parameter metadata: Final country's metadata.
- Returns: Modified number without national prefix.
*/
func stripNationalPrefix(_ number: inout String, metadata: MetadataTerritory) {
guard let possibleNationalPrefix = metadata.nationalPrefixForParsing else {
return
}
let prefixPattern = String(format: "^(?:%@)", possibleNationalPrefix)
do {
let matches = try regex.regexMatches(prefixPattern, string: number)
if let firstMatch = matches.first {
let nationalNumberRule = metadata.generalDesc?.nationalNumberPattern
let firstMatchString = number.substring(with: firstMatch.range)
let numOfGroups = firstMatch.numberOfRanges - 1
var transformedNumber: String = String()
let firstRange = firstMatch.rangeAt(numOfGroups)
let firstMatchStringWithGroup = (firstRange.location != NSNotFound && firstRange.location < number.characters.count) ? number.substring(with: firstRange): String()
let firstMatchStringWithGroupHasValue = regex.hasValue(firstMatchStringWithGroup)
if let transformRule = metadata.nationalPrefixTransformRule , firstMatchStringWithGroupHasValue == true {
transformedNumber = regex.replaceFirstStringByRegex(prefixPattern, string: number, templateString: transformRule)
}
else {
let index = number.index(number.startIndex, offsetBy: firstMatchString.characters.count)
transformedNumber = number.substring(from: index)
}
if (regex.hasValue(nationalNumberRule) && regex.matchesEntirely(nationalNumberRule, string: number) && regex.matchesEntirely(nationalNumberRule, string: transformedNumber) == false){
return
}
number = transformedNumber
return
}
}
catch {
return
}
}
}
| apache-2.0 | 07421040f5bb2bfb4bfc19c2cf94f497 | 41.866883 | 271 | 0.624858 | 5.321644 | false | false | false | false |
connorkrupp/Taskability | Taskability/Taskability/StagingAreaTableViewController.swift | 1 | 11994 | //
// StagingAreaTableViewController.swift
// Taskability
//
// Created by Connor Krupp on 17/03/2016.
// Copyright © 2016 Connor Krupp. All rights reserved.
//
import UIKit
import CoreData
import TaskabilityKit
class StagingAreaTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, UITextFieldDelegate, StagedTaskTableViewCellDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
// MARK: Types
struct MainStoryboard {
struct TableViewCellIdentifiers {
static let taskCell = "taskCell"
}
struct CollectionViewCellIdentifiers {
static let taskGroupCell = "taskGroupCell"
}
}
// MARK: Properties
@IBOutlet weak var newTaskTextField: UITextField!
@IBOutlet weak var scrollMenuCollectionView: UICollectionView!
@IBOutlet weak var scrollMenuCollectionViewLeadingConstraint: NSLayoutConstraint!
var stagedTaskItems: [TaskItem] {
return fetchedResultsController.fetchedObjects as! [TaskItem]
}
var taskGroups: [TaskGroup] {
return taskGroupsFetchedResultsController.fetchedObjects as! [TaskGroup]
}
var selectedTaskGroup: NSIndexPath?
/// Core Data Properties
var dataController: DataController!
var fetchedResultsController: NSFetchedResultsController!
var taskGroupsFetchedResultsController: NSFetchedResultsController!
var managedObjectContext: NSManagedObjectContext {
return dataController.managedObjectContext
}
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
initializeFetchedResultsControllers()
tableView.backgroundColor = UIColor(red: 248/255, green: 248/255, blue: 248/255, alpha: 1.0)
tableView.tableFooterView = UIView()
let flowLayout = scrollMenuCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
flowLayout.estimatedItemSize = CGSizeMake(100, 40)
scrollMenuCollectionViewLeadingConstraint.constant = self.view.bounds.width
newTaskTextField.delegate = self
newTaskTextField.attributedPlaceholder = NSAttributedString(string: newTaskTextField.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
addNewTaskTextFieldToolbar()
}
// MARK: UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sections = fetchedResultsController.sections!
return sections[section].numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = MainStoryboard.TableViewCellIdentifiers.taskCell
return tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
switch cell {
case let cell as StagedTaskTableViewCell:
cell.selectionStyle = .None
let taskItem = fetchedResultsController.objectAtIndexPath(indexPath) as! TaskItem
cell.titleLabel.text = taskItem.valueForKey("title") as? String
if let taskGroup = taskItem.valueForKey("taskGroup") as? TaskGroup {
cell.groupLabel.text = taskGroup.valueForKey("title") as? String
} else {
cell.groupLabel.text = "Ungrouped"
}
cell.isComplete = taskItem.valueForKey("isComplete") as! Bool
cell.delegate = self
default:
fatalError("Unknown cell type")
}
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
managedObjectContext.deleteObject(fetchedResultsController.objectAtIndexPath(indexPath) as! TaskItem)
}
}
// MARK: FetchedResultsController
func initializeFetchedResultsControllers() {
let taskItemRequest = NSFetchRequest(entityName: "TaskItem")
taskItemRequest.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchedResultsController = TaskabilityCoreData.initializeFetchedResultsController(withFetchRequest: taskItemRequest,
inManagedObjectContext: managedObjectContext)
fetchedResultsController.delegate = self
let taskGroupRequest = NSFetchRequest(entityName: "TaskGroup")
taskGroupRequest.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
taskGroupsFetchedResultsController = TaskabilityCoreData.initializeFetchedResultsController(withFetchRequest: taskGroupRequest,
inManagedObjectContext: managedObjectContext)
}
// MARK: NSFetchedResultsControllerDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
try! managedObjectContext.save()
tableView.endUpdates()
}
// MARK: StagedTaskTableViewCellDelegate
func checkmarkTapped(onCell cell: StagedTaskTableViewCell) {
let indexPath = tableView.indexPathForCell(cell)!
let taskItem = fetchedResultsController.objectAtIndexPath(indexPath) as! TaskItem
let completeKey = "isComplete"
let currentCompleteness = taskItem.valueForKey(completeKey) as! Bool
taskItem.setValue(!currentCompleteness, forKey: completeKey)
}
// MARK: UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return taskGroups.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let identifier = MainStoryboard.CollectionViewCellIdentifiers.taskGroupCell
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! ScrollMenuCollectionViewCell
cell.titleLabel.text = taskGroups[indexPath.row].valueForKey("title") as? String
return cell
}
// MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: true)
if let oldIndexPath = selectedTaskGroup {
let cell = collectionView.cellForItemAtIndexPath(oldIndexPath) as! ScrollMenuCollectionViewCell
cell.backgroundColor = UIColor.whiteColor()
cell.titleLabel.textColor = UIColor.darkGrayColor()
if indexPath == oldIndexPath {
selectedTaskGroup = nil
return
}
}
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! ScrollMenuCollectionViewCell
cell.backgroundColor = UIColor.darkGrayColor()
cell.titleLabel.textColor = UIColor.whiteColor()
selectedTaskGroup = indexPath
}
// MARK: UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
resizeTableHeaderView(true)
}
func textFieldDidEndEditing(textField: UITextField) {
resizeTableHeaderView(false)
}
func resizeTableHeaderView(shouldExpand: Bool) {
if taskGroups.isEmpty {
return
}
let animationDuration = 0.3
let sizeAdjustment: CGFloat = 40
let frame = self.tableView.tableHeaderView!.frame
let newFrame = CGRectMake(frame.origin.x, frame.origin.y, frame.width,
shouldExpand ? frame.height + sizeAdjustment : frame.height - sizeAdjustment)
func resizeHeader() {
self.tableView.tableHeaderView?.frame = newFrame
self.tableView.tableHeaderView = self.tableView.tableHeaderView
self.view.layoutIfNeeded()
}
if shouldExpand {
UIView.animateWithDuration(animationDuration, animations: {
resizeHeader()
}, completion: { _ in
UIView.animateWithDuration(animationDuration, animations: {
self.scrollMenuCollectionViewLeadingConstraint.constant = 0
self.view.layoutIfNeeded()
})
})
} else {
self.scrollMenuCollectionViewLeadingConstraint.constant = self.view.bounds.width
UIView.animateWithDuration(animationDuration, animations: {
self.view.layoutIfNeeded()
}, completion: { _ in
UIView.animateWithDuration(animationDuration, animations: {
resizeHeader()
})
})
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
createTaskItem()
return true
}
// MARK: NewTaskTextField Toolbar Handler
func addNewTaskTextFieldToolbar() {
let toolBar = UIToolbar()
toolBar.barStyle = .Black
let cancelButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(StagingAreaTableViewController.cancelAddingTasks))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(StagingAreaTableViewController.doneAddingTasks))
toolBar.tintColor = UIColor.whiteColor()
toolBar.setItems([cancelButton, flexibleSpace, doneButton], animated: false)
toolBar.userInteractionEnabled = true
toolBar.sizeToFit()
newTaskTextField.inputAccessoryView = toolBar
}
func cancelAddingTasks() {
newTaskTextField.text = ""
newTaskTextField.resignFirstResponder()
}
func doneAddingTasks() {
createTaskItem()
newTaskTextField.resignFirstResponder()
}
func createTaskItem() {
let title = newTaskTextField.text!
if !title.isEmpty {
var taskGroup: TaskGroup? = nil
if let selectedTaskGroupIndexPath = selectedTaskGroup {
taskGroup = taskGroups[selectedTaskGroupIndexPath.row]
}
TaskabilityCoreData.insertTaskItemWithTitle(title, inTaskGroup: taskGroup, inManagedObjectContext: managedObjectContext)
newTaskTextField.text = ""
selectedTaskGroup = nil
}
}
}
| mit | a43da2a9f8579981ef2c93ff9e1c2e5c | 38.321311 | 241 | 0.69082 | 6.162898 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/valid-mountain-array.swift | 1 | 1077 | /**
* https://leetcode.com/problems/valid-mountain-array/
*
*
*/
// Date: Thu Dec 10 10:57:17 PST 2020
class Solution {
func validMountainArray(_ arr: [Int]) -> Bool {
var start = 0
while start < arr.count - 1, arr[start] < arr[start + 1] {
start += 1
}
if start == 0 || start == arr.count - 1 { return false }
start += 1
while start < arr.count, arr[start] < arr[start - 1] {
start += 1
}
return start == arr.count
}
}
class Solution {
/// - Complexity:
/// - Time: O(n), n = arr.count.
/// - Space: O(1), constant space.
func validMountainArray(_ arr: [Int]) -> Bool {
guard arr.count >= 3 else { return false }
var left = 0
while left + 1 < arr.count, arr[left] < arr[left + 1] {
left += 1
}
var right = arr.count - 1
while right - 1 >= 0, arr[right] < arr[right - 1] {
right -= 1
}
return left == right && left > 0 && right < arr.count - 1
}
}
| mit | 081b81d6ba20bdc8adac5c81c9ba8e75 | 26.615385 | 66 | 0.476323 | 3.554455 | false | false | false | false |
alblue/swift | stdlib/public/core/StringUnicodeScalarView.swift | 1 | 14607 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to
// allow performance optimizations of linear traversals.
extension String {
/// A view of a string's contents as a collection of Unicode scalar values.
///
/// You can access a string's view of Unicode scalar values by using its
/// `unicodeScalars` property. Unicode scalar values are the 21-bit codes
/// that are the basic unit of Unicode. Each scalar value is represented by
/// a `Unicode.Scalar` instance and is equivalent to a UTF-32 code unit.
///
/// let flowers = "Flowers 💐"
/// for v in flowers.unicodeScalars {
/// print(v.value)
/// }
/// // 70
/// // 108
/// // 111
/// // 119
/// // 101
/// // 114
/// // 115
/// // 32
/// // 128144
///
/// Some characters that are visible in a string are made up of more than one
/// Unicode scalar value. In that case, a string's `unicodeScalars` view
/// contains more elements than the string itself.
///
/// let flag = "🇵🇷"
/// for c in flag {
/// print(c)
/// }
/// // 🇵🇷
///
/// for v in flag.unicodeScalars {
/// print(v.value)
/// }
/// // 127477
/// // 127479
///
/// You can convert a `String.UnicodeScalarView` instance back into a string
/// using the `String` type's `init(_:)` initializer.
///
/// let favemoji = "My favorite emoji is 🎉"
/// if let i = favemoji.unicodeScalars.firstIndex(where: { $0.value >= 128 }) {
/// let asciiPrefix = String(favemoji.unicodeScalars[..<i])
/// print(asciiPrefix)
/// }
/// // Prints "My favorite emoji is "
@_fixed_layout
public struct UnicodeScalarView {
@usableFromInline
internal var _guts: _StringGuts
@inlinable @inline(__always)
internal init(_ _guts: _StringGuts) {
self._guts = _guts
_invariantCheck()
}
}
}
extension String.UnicodeScalarView {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
// TODO: Assert start/end are scalar aligned
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension String.UnicodeScalarView: BidirectionalCollection {
public typealias Index = String.Index
/// The position of the first Unicode scalar value if the string is
/// nonempty.
///
/// If the string is empty, `startIndex` is equal to `endIndex`.
@inlinable
public var startIndex: Index {
@inline(__always) get { return _guts.startIndex }
}
/// The "past the end" position---that is, the position one greater than
/// the last valid subscript argument.
///
/// In an empty Unicode scalars view, `endIndex` is equal to `startIndex`.
@inlinable
public var endIndex: Index {
@inline(__always) get { return _guts.endIndex }
}
/// Returns the next consecutive location after `i`.
///
/// - Precondition: The next location exists.
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
_sanityCheck(i < endIndex)
// TODO(String performance): isASCII fast-path
if _fastPath(_guts.isFastUTF8) {
let len = _guts.fastUTF8ScalarLength(startingAt: i.encodedOffset)
return i.encoded(offsetBy: len)
}
return _foreignIndex(after: i)
}
/// Returns the previous consecutive location before `i`.
///
/// - Precondition: The previous location exists.
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
precondition(i.encodedOffset > 0)
// TODO(String performance): isASCII fast-path
if _fastPath(_guts.isFastUTF8) {
let len = _guts.withFastUTF8 { utf8 -> Int in
return _utf8ScalarLength(utf8, endingAt: i.encodedOffset)
}
_sanityCheck(len <= 4, "invalid UTF8")
return i.encoded(offsetBy: -len)
}
return _foreignIndex(before: i)
}
/// Accesses the Unicode scalar value at the given position.
///
/// The following example searches a string's Unicode scalars view for a
/// capital letter and then prints the character and Unicode scalar value
/// at the found index:
///
/// let greeting = "Hello, friend!"
/// if let i = greeting.unicodeScalars.firstIndex(where: { "A"..."Z" ~= $0 }) {
/// print("First capital letter: \(greeting.unicodeScalars[i])")
/// print("Unicode scalar value: \(greeting.unicodeScalars[i].value)")
/// }
/// // Prints "First capital letter: H"
/// // Prints "Unicode scalar value: 72"
///
/// - Parameter position: A valid index of the character view. `position`
/// must be less than the view's end index.
@inlinable
public subscript(position: Index) -> Unicode.Scalar {
@inline(__always) get {
String(_guts)._boundsCheck(position)
let i = _guts.scalarAlign(position)
if _fastPath(_guts.isFastUTF8) {
return _guts.fastUTF8Scalar(startingAt: i.encodedOffset)
}
return _foreignSubscript(aligned: i)
}
}
}
extension String.UnicodeScalarView: CustomStringConvertible {
@inlinable
public var description: String {
@inline(__always) get { return String(_guts) }
}
}
extension String.UnicodeScalarView: CustomDebugStringConvertible {
public var debugDescription: String {
return "StringUnicodeScalarView(\(self.description.debugDescription))"
}
}
extension String {
/// Creates a string corresponding to the given collection of Unicode
/// scalars.
///
/// You can use this initializer to create a new string from a slice of
/// another string's `unicodeScalars` view.
///
/// let picnicGuest = "Deserving porcupine"
/// if let i = picnicGuest.unicodeScalars.firstIndex(of: " ") {
/// let adjective = String(picnicGuest.unicodeScalars[..<i])
/// print(adjective)
/// }
/// // Prints "Deserving"
///
/// The `adjective` constant is created by calling this initializer with a
/// slice of the `picnicGuest.unicodeScalars` view.
///
/// - Parameter unicodeScalars: A collection of Unicode scalar values.
@inlinable @inline(__always)
public init(_ unicodeScalars: UnicodeScalarView) {
self.init(unicodeScalars._guts)
}
/// The index type for a string's `unicodeScalars` view.
public typealias UnicodeScalarIndex = UnicodeScalarView.Index
/// The string's value represented as a collection of Unicode scalar values.
@inlinable
public var unicodeScalars: UnicodeScalarView {
@inline(__always) get { return UnicodeScalarView(_guts) }
@inline(__always) set { _guts = newValue._guts }
}
}
extension String.UnicodeScalarView : RangeReplaceableCollection {
/// Creates an empty view instance.
@inlinable @inline(__always)
public init() {
self.init(_StringGuts())
}
/// Reserves enough space in the view's underlying storage to store the
/// specified number of ASCII characters.
///
/// Because a Unicode scalar value can require more than a single ASCII
/// character's worth of storage, additional allocation may be necessary
/// when adding to a Unicode scalar view after a call to
/// `reserveCapacity(_:)`.
///
/// - Parameter n: The minimum number of ASCII character's worth of storage
/// to allocate.
///
/// - Complexity: O(*n*), where *n* is the capacity being reserved.
public mutating func reserveCapacity(_ n: Int) {
self._guts.reserveCapacity(n)
}
/// Appends the given Unicode scalar to the view.
///
/// - Parameter c: The character to append to the string.
public mutating func append(_ c: Unicode.Scalar) {
self._guts.append(String(c)._guts)
}
/// Appends the Unicode scalar values in the given sequence to the view.
///
/// - Parameter newElements: A sequence of Unicode scalar values.
///
/// - Complexity: O(*n*), where *n* is the length of the resulting view.
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Element == Unicode.Scalar {
// TODO(String performance): Skip extra String allocation
let scalars = String(decoding: newElements.map { $0.value }, as: UTF32.self)
self = (String(self._guts) + scalars).unicodeScalars
}
/// Replaces the elements within the specified bounds with the given Unicode
/// scalar values.
///
/// Calling this method invalidates any existing indices for use with this
/// string.
///
/// - Parameters:
/// - bounds: The range of elements to replace. The bounds of the range
/// must be valid indices of the view.
/// - newElements: The new Unicode scalar values to add to the string.
///
/// - Complexity: O(*m*), where *m* is the combined length of the view and
/// `newElements`. If the call to `replaceSubrange(_:with:)` simply
/// removes elements at the end of the string, the complexity is O(*n*),
/// where *n* is equal to `bounds.count`.
public mutating func replaceSubrange<C>(
_ bounds: Range<Index>,
with newElements: C
) where C : Collection, C.Element == Unicode.Scalar {
// TODO(String performance): Skip extra String and Array allocation
let utf8Replacement = newElements.flatMap { String($0).utf8 }
let replacement = utf8Replacement.withUnsafeBufferPointer {
return String._uncheckedFromUTF8($0)
}
var copy = String(_guts)
copy.replaceSubrange(bounds, with: replacement)
self = copy.unicodeScalars
}
}
// Index conversions
extension String.UnicodeScalarIndex {
/// Creates an index in the given Unicode scalars view that corresponds
/// exactly to the specified `UTF16View` position.
///
/// The following example finds the position of a space in a string's `utf16`
/// view and then converts that position to an index in the string's
/// `unicodeScalars` view:
///
/// let cafe = "Café 🍵"
///
/// let utf16Index = cafe.utf16.firstIndex(of: 32)!
/// let scalarIndex = String.Index(utf16Index, within: cafe.unicodeScalars)!
///
/// print(String(cafe.unicodeScalars[..<scalarIndex]))
/// // Prints "Café"
///
/// If the index passed as `sourcePosition` doesn't have an exact
/// corresponding position in `unicodeScalars`, the result of the
/// initializer is `nil`. For example, an attempt to convert the position of
/// the trailing surrogate of a UTF-16 surrogate pair results in `nil`.
///
/// - Parameters:
/// - sourcePosition: A position in the `utf16` view of a string.
/// `utf16Index` must be an element of
/// `String(unicodeScalars).utf16.indices`.
/// - unicodeScalars: The `UnicodeScalarView` in which to find the new
/// position.
public init?(
_ sourcePosition: String.Index,
within unicodeScalars: String.UnicodeScalarView
) {
guard unicodeScalars._guts.isOnUnicodeScalarBoundary(sourcePosition) else {
return nil
}
self = sourcePosition
}
/// Returns the position in the given string that corresponds exactly to this
/// index.
///
/// This example first finds the position of a space (UTF-8 code point `32`)
/// in a string's `utf8` view and then uses this method find the same position
/// in the string.
///
/// let cafe = "Café 🍵"
/// let i = cafe.unicodeScalars.firstIndex(of: "🍵")
/// let j = i.samePosition(in: cafe)!
/// print(cafe[j...])
/// // Prints "🍵"
///
/// - Parameter characters: The string to use for the index conversion.
/// This index must be a valid index of at least one view of `characters`.
/// - Returns: The position in `characters` that corresponds exactly to
/// this index. If this index does not have an exact corresponding
/// position in `characters`, this method returns `nil`. For example,
/// an attempt to convert the position of a UTF-8 continuation byte
/// returns `nil`.
public func samePosition(in characters: String) -> String.Index? {
return String.Index(self, within: characters)
}
}
// Reflection
extension String.UnicodeScalarView : CustomReflectable {
/// Returns a mirror that reflects the Unicode scalars view of a string.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
//===--- Slicing Support --------------------------------------------------===//
/// In Swift 3.2, in the absence of type context,
///
/// someString.unicodeScalars[
/// someString.unicodeScalars.startIndex
/// ..< someString.unicodeScalars.endIndex]
///
/// was deduced to be of type `String.UnicodeScalarView`. Provide a
/// more-specific Swift-3-only `subscript` overload that continues to produce
/// `String.UnicodeScalarView`.
extension String.UnicodeScalarView {
public typealias SubSequence = Substring.UnicodeScalarView
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> String.UnicodeScalarView.SubSequence {
return String.UnicodeScalarView.SubSequence(self, _bounds: r)
}
}
// Foreign string Support
extension String.UnicodeScalarView {
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(after i: Index) -> Index {
_sanityCheck(_guts.isForeign)
let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: i)
let len = _isLeadingSurrogate(cu) ? 2 : 1
return i.encoded(offsetBy: len)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignIndex(before i: Index) -> Index {
_sanityCheck(_guts.isForeign)
let priorIdx = i.priorEncoded
let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: priorIdx)
let len = _isTrailingSurrogate(cu) ? 2 : 1
return i.encoded(offsetBy: -len)
}
@usableFromInline @inline(never)
@_effects(releasenone)
internal func _foreignSubscript(aligned i: Index) -> Unicode.Scalar {
_sanityCheck(_guts.isForeign)
_sanityCheck(_guts.isOnUnicodeScalarBoundary(i),
"should of been aligned prior")
return _guts.foreignErrorCorrectedScalar(startingAt: i).0
}
}
| apache-2.0 | 1d7b7991c1933c8cc5e5460259f70e61 | 34.033654 | 85 | 0.654865 | 4.315665 | false | false | false | false |
3ph/CollectionPickerView | Sources/CollectionPickerView/CollectionPickerView.swift | 2 | 16521 | //
// CollectionPickerView.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Akkyie Y, 2017 Tomas Friml
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
//
import UIKit
/// Allows user to override collection view delegate methods
public class CollectionPickerViewForwardDelegate: NSObject, UICollectionViewDelegate {
init(picker: CollectionPickerView) {
_picker = picker
}
internal weak var delegate : UICollectionViewDelegate?
// MARK: - Private
fileprivate weak var _picker : CollectionPickerView?
override public func forwardingTarget(for aSelector: Selector!) -> Any? {
if let p = _picker, p.responds(to: aSelector) {
return p
} else if let d = delegate, d.responds(to: aSelector) {
return d
}
return super.responds(to: aSelector)
}
override public func responds(to aSelector: Selector!) -> Bool {
if let p = _picker, p.responds(to: aSelector) {
return true
} else if let d = delegate, d.responds(to: aSelector) {
return true
}
return super.responds(to: aSelector)
}
}
public class CollectionPickerView: UIView {
public let collectionView : UICollectionView
/// Readwrite. Spacing between cells
@IBInspectable public var cellSpacing : CGFloat = 10
/// Readwrite. Default cell size (based on direction of picker)
@IBInspectable public var cellSize : CGFloat = 100
/// Readwrite. Select center item on scroll
@IBInspectable public var selectCenter : Bool = true
/// Readwrite. Determines style of the picker
@IBInspectable public var isFlat : Bool = false {
didSet {
didSetIsFlat()
}
}
/// Readwrite. Picker direction
@IBInspectable public var isHorizontal : Bool = true {
didSet {
didSetFlowLayoutDirection()
didSetMaskDisabled()
}
}
/// Readwrite. A float value which determines the perspective representation which used when using wheel style.
@IBInspectable public var viewDepth: CGFloat = 2000 {
didSet {
didSetViewDepth()
}
}
/// Readwrite. A boolean value indicates whether the mask is disabled.
@IBInspectable public var maskDisabled: Bool = false {
didSet {
didSetMaskDisabled()
}
}
/// Readonly. Currently selected collection view item index
public private(set) var selectedIndex : Int = 0
public weak var dataSource : UICollectionViewDataSource? {
didSet {
collectionView.dataSource = dataSource
}
}
public weak var delegate : UICollectionViewDelegate? {
didSet {
_forwardDelegate.delegate = delegate
}
}
public override var intrinsicContentSize : CGSize {
// TODO: figure out max.
if isHorizontal {
return CGSize(width: UIView.noIntrinsicMetric, height: cellSize)
} else {
return CGSize(width: cellSize, height: UIView.noIntrinsicMetric)
}
}
override init(frame: CGRect) {
collectionView = UICollectionView(frame: frame, collectionViewLayout: CollectionPickerViewFlowLayout())
super.init(frame: frame)
initialize()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: CollectionPickerViewFlowLayout())
super.init(coder: aDecoder)
initialize()
}
/**
Select a cell whose index is given one and move to it.
:param: index An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
*/
public func selectItem(at index: Int, animated: Bool = false) {
self.selectItem(at: index, animated: animated, scroll: true, notifySelection: true)
}
/**
Reload the picker view's contents and styles. Call this method always after any property is changed.
*/
public func reloadData() {
invalidateIntrinsicContentSize()
collectionView.collectionViewLayout.invalidateLayout()
collectionView.reloadData()
if collectionView.numberOfItems(inSection: 0) > 0 {
selectItem(at: selectedIndex, animated: false)
}
}
// MARK: - Private
fileprivate var _flowLayout : CollectionPickerViewFlowLayout? {
get {
return collectionView.collectionViewLayout as? CollectionPickerViewFlowLayout
}
}
fileprivate var _forwardDelegate : CollectionPickerViewForwardDelegate!
fileprivate func initialize() {
addSubview(collectionView)
_forwardDelegate = CollectionPickerViewForwardDelegate(picker: self)
collectionView.delegate = _forwardDelegate
collectionView.isScrollEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.decelerationRate = UIScrollView.DecelerationRate.fast
collectionView.backgroundColor = UIColor.clear
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// have to call didSets separatele as it's not being invoked for initial values
didSetFlowLayoutDirection()
didSetIsFlat()
didSetMaskDisabled()
didSetViewDepth()
}
/**
Private. Used to calculate the x-coordinate of the content offset of specified item.
:param: item An integer value which indicates the index of cell.
:returns: An x/y-coordinate of the cell whose index is given one.
*/
fileprivate func offsetForItem(at index: Int) -> CGFloat {
let firstIndexPath = IndexPath(item: 0, section: 0)
let firstSize = self.collectionView(
collectionView,
layout: collectionView.collectionViewLayout,
sizeForItemAt: firstIndexPath)
var offset: CGFloat = isHorizontal
? collectionView.bounds.width / 2 - firstSize.width / 4
: collectionView.bounds.height / 2 - firstSize.height / 4
for i in 0 ..< index {
let indexPath = IndexPath(item: i, section: 0)
let cellSize = self.collectionView(
collectionView,
layout: collectionView.collectionViewLayout,
sizeForItemAt: indexPath)
offset += (isHorizontal ? cellSize.width : cellSize.height) + cellSpacing
}
let selectedIndexPath = IndexPath(item: index, section: 0)
let selectedSize = self.collectionView(
collectionView,
layout: collectionView.collectionViewLayout,
sizeForItemAt: selectedIndexPath)
if isHorizontal {
offset -= collectionView.bounds.width / 2 - selectedSize.width / 2
} else {
offset -= collectionView.bounds.height / 2 - selectedSize.height / 2
}
return offset
}
/**
Move to the cell whose index is given one without selection change.
:param: index An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
*/
fileprivate func scrollToItem(at index: Int, animated: Bool = false) {
if isFlat {
collectionView.scrollToItem(
at: IndexPath(
item: index,
section: 0),
at: isHorizontal ? .centeredHorizontally : .centeredVertically,
animated: animated)
} else {
collectionView.setContentOffset(
CGPoint(
x: isHorizontal ? offsetForItem(at: index) : collectionView.contentOffset.x,
y: isHorizontal ? collectionView.contentOffset.y : offsetForItem(at: index)),
animated: animated)
}
}
/**
Private. Select a cell whose index is given one and move to it, with specifying whether it calls delegate method.
:param: index An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
:param: notifySelection True if the delegate method should be called, false if not.
*/
fileprivate func selectItem(at index: Int, animated: Bool, scroll: Bool, notifySelection: Bool) {
/*
let oldIndexPath = IndexPath(item: selectedIndex, section: 0)
let newIndexPath = IndexPath(item: index, section: 0)
*/
let indexPath = IndexPath(item: index, section: 0)
collectionView.selectItem(
at: indexPath,
animated: animated,
scrollPosition: UICollectionView.ScrollPosition())
if scroll {
scrollToItem(at: index, animated: animated)
}
selectedIndex = index
self.delegate?.collectionView?(collectionView, didSelectItemAt: indexPath)
/*
selectedItem = item
*/
}
fileprivate func didSetFlowLayoutDirection() {
_flowLayout?.scrollDirection = isHorizontal ? .horizontal : .vertical
_flowLayout?.invalidateLayout()
}
fileprivate func didSetIsFlat() {
_flowLayout?.isFlat = isFlat
}
fileprivate func didSetMaskDisabled() {
collectionView.layer.mask = maskDisabled == true ? nil : {
let maskLayer = CAGradientLayer()
maskLayer.frame = collectionView.bounds
maskLayer.colors = [
UIColor.clear.cgColor,
UIColor.black.cgColor,
UIColor.black.cgColor,
UIColor.clear.cgColor]
maskLayer.locations = [0.0, 0.33, 0.66, 1.0]
maskLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
if isHorizontal {
maskLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
} else {
maskLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
}
return maskLayer
}()
}
fileprivate func didSetViewDepth() {
collectionView.layer.sublayerTransform = viewDepth > 0.0 ? {
var transform = CATransform3DIdentity;
transform.m34 = -1.0 / viewDepth;
return transform;
}() : CATransform3DIdentity;
}
}
// MARK: - UICollectionViewDelegate
extension CollectionPickerView: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectItem(at: indexPath.item, animated: true)
}
}
// MARK: - Layout
extension CollectionPickerView {
override public func layoutSubviews() {
super.layoutSubviews()
reloadData()
collectionView.frame = collectionView.superview!.bounds
collectionView.layer.mask?.frame = collectionView.bounds
if collectionView.numberOfItems(inSection: 0) > 0 {
selectItem(at: selectedIndex)
}
}
}
// MARK: - UIScrollViewDelegate
extension CollectionPickerView : UIScrollViewDelegate {
fileprivate func didScroll(end: Bool) {
if isFlat {
let center = convert(collectionView.center, to: collectionView)
if let indexPath = collectionView.indexPathForItem(at: center) {
self.selectItem(at: indexPath.item, animated: true, scroll: end, notifySelection: true)
}
} else {
for i in 0 ..< collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: i, section: 0)
let cellSize = self.collectionView(
collectionView,
layout: collectionView.collectionViewLayout,
sizeForItemAt: indexPath)
if (isHorizontal && (offsetForItem(at: i) + cellSize.width / 2 > collectionView.contentOffset.x))
|| (isHorizontal == false && (offsetForItem(at: i) + cellSize.height / 2 > collectionView.contentOffset.y)) {
//if i != selectedIndex {
selectItem(at: i, animated: true, scroll: end, notifySelection: true)
//}
break
}
}
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
delegate?.scrollViewDidEndDecelerating?(scrollView)
didScroll(end: true)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
delegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
if !decelerate {
didScroll(end: true)
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
delegate?.scrollViewDidScroll?(scrollView)
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
collectionView.layer.mask?.frame = collectionView.bounds
CATransaction.commit()
}
}
extension CollectionPickerView: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let number = collectionView.numberOfItems(inSection: section)
let firstIndexPath = IndexPath(item: 0, section: section)
let firstSize = self.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: firstIndexPath)
let lastIndexPath = IndexPath(item: number - 1, section: section)
let lastSize = self.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: lastIndexPath)
if isHorizontal {
return UIEdgeInsets(
top: 0, left: (collectionView.bounds.size.width - firstSize.width/2) / 2,
bottom: 0, right: (collectionView.bounds.size.width - lastSize.width/2) / 2
)
} else {
return UIEdgeInsets(
top: (collectionView.bounds.size.height - firstSize.height/2) / 2, left: 0,
bottom: (collectionView.bounds.size.height - lastSize.height/2) / 2, right: 0
)
}
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if isHorizontal {
return CGSize(width: cellSize, height: collectionView.bounds.height)
} else {
return CGSize(width: collectionView.bounds.width, height: cellSize)
}
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return cellSpacing
}
}
| mit | fc4e4745a7d52506d70150e5138ce58e | 37.243056 | 182 | 0.636584 | 5.418498 | false | false | false | false |
mipstian/catch | Sources/App/WindowShakeAnimation.swift | 1 | 811 | import AppKit
extension NSWindow {
// Stolen from: http://stackoverflow.com/questions/10517386
func performShakeAnimation(duration: TimeInterval, numberOfShakes: Int = 2, intensity: CGFloat = 0.015) {
let shakeAnimation = CAKeyframeAnimation()
let xOffset = frame.width * intensity
let shakePath = CGMutablePath()
shakePath.move(to: CGPoint(x: frame.minX, y: frame.minY))
for _ in 0..<numberOfShakes {
shakePath.addLine(to: CGPoint(x: frame.minX - xOffset, y: frame.minY))
shakePath.addLine(to: CGPoint(x: frame.minX + xOffset, y: frame.minY))
}
shakePath.closeSubpath()
shakeAnimation.path = shakePath
shakeAnimation.duration = duration
animations = ["frameOrigin": shakeAnimation]
animator().setFrameOrigin(frame.origin)
}
}
| mit | 1f710d5caae92238fe5577a0c2956783 | 31.44 | 107 | 0.691739 | 4.034826 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Calling/CallInfoViewController/CallStatusView.swift | 1 | 4926 | //
// Wire
// Copyright (C) 2018 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 UIKit
import WireCommonComponents
enum CallStatusViewState: Equatable {
case none
case connecting
case ringingIncoming(name: String?) // Caller name + call type "XYZ is calling..."
case ringingOutgoing // "Ringing..."
case established(duration: TimeInterval) // Call duration in seconds "04:18"
case reconnecting // "Reconnecting..."
case terminating // "Ending call..."
}
final class CallStatusView: UIView {
private let titleLabel = UILabel()
private let subtitleLabel = UILabel()
private let bitrateLabel = BitRateLabel()
private let stackView = UIStackView(axis: .vertical)
var configuration: CallStatusViewInputType {
didSet {
updateConfiguration()
}
}
init(configuration: CallStatusViewInputType) {
self.configuration = configuration
super.init(frame: .zero)
setupViews()
createConstraints()
updateConfiguration()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
[stackView, bitrateLabel].forEach(addSubview)
stackView.distribution = .fill
stackView.alignment = .center
stackView.translatesAutoresizingMaskIntoConstraints = false
bitrateLabel.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = 12
accessibilityIdentifier = "CallStatusLabel"
[titleLabel, subtitleLabel].forEach(stackView.addArrangedSubview)
[titleLabel, subtitleLabel, bitrateLabel].forEach {
$0.textAlignment = .center
}
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.font = .systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
subtitleLabel.font = FontSpec(.normal, .semibold).font
subtitleLabel.alpha = 0.64
bitrateLabel.font = FontSpec(.small, .semibold).font
bitrateLabel.alpha = 0.64
bitrateLabel.accessibilityIdentifier = "bitrate-indicator"
bitrateLabel.isHidden = true
}
private func createConstraints() {
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 24),
stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -24),
stackView.topAnchor.constraint(equalTo: topAnchor),
bitrateLabel.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 16),
bitrateLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
bitrateLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
bitrateLabel.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
private func updateConfiguration() {
titleLabel.text = configuration.title
subtitleLabel.text = configuration.displayString
bitrateLabel.isHidden = !configuration.shouldShowBitrateLabel
bitrateLabel.bitRateStatus = BitRateStatus(configuration.isConstantBitRate)
[titleLabel, subtitleLabel, bitrateLabel].forEach {
$0.textColor = UIColor.from(scheme: .textForeground, variant: configuration.effectiveColorVariant)
}
}
}
// MARK: - Helper
private let callDurationFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
private extension CallStatusViewInputType {
var displayString: String {
switch state {
case .none: return ""
case .connecting: return "call.status.connecting".localized
case .ringingIncoming(name: let name?): return "call.status.incoming.user".localized(args: name)
case .ringingIncoming(name: nil): return "call.status.incoming".localized
case .ringingOutgoing: return "call.status.outgoing".localized
case .established(duration: let duration): return callDurationFormatter.string(from: duration) ?? ""
case .reconnecting: return "call.status.reconnecting".localized
case .terminating: return "call.status.terminating".localized
}
}
}
| gpl-3.0 | 7f420d650f6a1723de06c1c456b22a13 | 37.186047 | 110 | 0.699756 | 5.052308 | false | true | false | false |
klundberg/swift-corelibs-foundation | Foundation/IndexSet.swift | 1 | 32685 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
public func ==(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value == rhs.value && rhs.rangeIndex == rhs.rangeIndex
}
public func <(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value < rhs.value && rhs.rangeIndex <= rhs.rangeIndex
}
public func <=(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value <= rhs.value && rhs.rangeIndex <= rhs.rangeIndex
}
public func >(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value > rhs.value && rhs.rangeIndex >= rhs.rangeIndex
}
public func >=(lhs: IndexSet.Index, rhs: IndexSet.Index) -> Bool {
return lhs.value >= rhs.value && rhs.rangeIndex >= rhs.rangeIndex
}
public func ==(lhs: IndexSet.RangeView, rhs: IndexSet.RangeView) -> Bool {
return lhs.startIndex == rhs.startIndex && lhs.endIndex == rhs.endIndex && lhs.indexSet == rhs.indexSet
}
// We currently cannot use this mechanism because NSIndexSet is not abstract; it has its own ivars and therefore subclassing it using the same trick as NSData, etc. does not work.
/*
private final class _SwiftNSIndexSet : _SwiftNativeNSIndexSet, _SwiftNativeFoundationType {
public typealias ImmutableType = NSIndexSet
public typealias MutableType = NSMutableIndexSet
var __wrapped : _MutableUnmanagedWrapper<ImmutableType, MutableType>
init(immutableObject: AnyObject) {
// Take ownership.
__wrapped = .Immutable(
Unmanaged.passRetained(
_unsafeReferenceCast(immutableObject, to: ImmutableType.self)))
super.init()
}
init(mutableObject: AnyObject) {
// Take ownership.
__wrapped = .Mutable(
Unmanaged.passRetained(
_unsafeReferenceCast(mutableObject, to: MutableType.self)))
super.init()
}
public required init(unmanagedImmutableObject: Unmanaged<ImmutableType>) {
// Take ownership.
__wrapped = .Immutable(unmanagedImmutableObject)
super.init()
}
public required init(unmanagedMutableObject: Unmanaged<MutableType>) {
// Take ownership.
__wrapped = .Mutable(unmanagedMutableObject)
super.init()
}
deinit {
releaseWrappedObject()
}
}
*/
/// Manages a `Set` of integer values, which are commonly used as an index type in Cocoa API.
///
/// The range of valid integer values is 0..<INT_MAX-1. Anything outside this range is an error.
public struct IndexSet : ReferenceConvertible, Equatable, BidirectionalCollection, SetAlgebra {
/// An view of the contents of an IndexSet, organized by range.
///
/// For example, if an IndexSet is composed of:
/// `[1..<5]` and `[7..<10]` and `[13]`
/// then calling `next()` on this view's iterator will produce 3 ranges before returning nil.
public struct RangeView : Equatable, BidirectionalCollection {
public typealias Index = Int
public let startIndex : Index
public let endIndex : Index
private var indexSet : IndexSet
// Range of element values
private var intersectingRange : Range<IndexSet.Element>?
private init(indexSet : IndexSet, intersecting range : Range<IndexSet.Element>?) {
self.indexSet = indexSet
self.intersectingRange = range
if let r = range {
if r.lowerBound == r.upperBound {
startIndex = 0
endIndex = 0
} else {
let minIndex = indexSet._indexOfRange(containing: r.lowerBound)
let maxIndex = indexSet._indexOfRange(containing: r.upperBound)
switch (minIndex, maxIndex) {
case (nil, nil):
startIndex = 0
endIndex = 0
case (nil, .some(let max)):
// Start is before our first range
startIndex = 0
endIndex = max + 1
case (.some(let min), nil):
// End is after our last range
startIndex = min
endIndex = indexSet._rangeCount
case (.some(let min), .some(let max)):
startIndex = min
endIndex = max + 1
}
}
} else {
startIndex = 0
endIndex = indexSet._rangeCount
}
}
public func makeIterator() -> IndexingIterator<RangeView> {
return IndexingIterator(_elements: self)
}
public subscript(index : Index) -> CountableRange<IndexSet.Element> {
let indexSetRange = indexSet._range(at: index)
if let intersectingRange = intersectingRange {
return Swift.max(intersectingRange.lowerBound, indexSetRange.lowerBound)..<Swift.min(intersectingRange.upperBound, indexSetRange.upperBound)
} else {
return indexSetRange.lowerBound..<indexSetRange.upperBound
}
}
public subscript(bounds: Range<Index>) -> BidirectionalSlice<RangeView> {
return BidirectionalSlice(base: self, bounds: bounds)
}
public func index(after i: Index) -> Index {
return i + 1
}
public func index(before i: Index) -> Index {
return i - 1
}
}
/// The mechanism for getting to the integers stored in an IndexSet.
public struct Index : CustomStringConvertible, Comparable {
private let indexSet : IndexSet
private var value : IndexSet.Element
private var extent : Range<IndexSet.Element>
private var rangeIndex : Int
private let rangeCount : Int
private init(firstIn indexSet : IndexSet) {
self.indexSet = indexSet
self.rangeCount = indexSet._rangeCount
self.rangeIndex = 0
self.extent = indexSet._range(at: 0)
self.value = extent.lowerBound
}
private init(lastIn indexSet : IndexSet) {
self.indexSet = indexSet
let rangeCount = indexSet._rangeCount
self.rangeIndex = rangeCount - 1
if rangeCount > 0 {
self.extent = indexSet._range(at: rangeCount - 1)
self.value = extent.upperBound // "1 past the end" position is the last range, 1 + the end of that range's extent
} else {
self.extent = 0..<0
self.value = 0
}
self.rangeCount = rangeCount
}
private init(indexSet: IndexSet, index: Int) {
self.indexSet = indexSet
self.rangeCount = self.indexSet._rangeCount
self.value = index
if let rangeIndex = self.indexSet._indexOfRange(containing: index) {
self.extent = self.indexSet._range(at: rangeIndex)
self.rangeIndex = rangeIndex
} else {
self.extent = 0..<0
self.rangeIndex = 0
}
}
// First or last value in a specified range
private init(indexSet: IndexSet, rangeIndex: Int, rangeCount: Int, first : Bool) {
self.indexSet = indexSet
let extent = indexSet._range(at: rangeIndex)
if first {
self.value = extent.lowerBound
} else {
self.value = extent.upperBound-1
}
self.extent = extent
self.rangeCount = rangeCount
self.rangeIndex = rangeIndex
}
private init(indexSet: IndexSet, value: Int, extent: Range<Int>, rangeIndex: Int, rangeCount: Int) {
self.indexSet = indexSet
self.value = value
self.extent = extent
self.rangeCount = rangeCount
self.rangeIndex = rangeIndex
}
private func successor() -> Index {
if value + 1 == extent.upperBound {
// Move to the next range
if rangeIndex + 1 == rangeCount {
// We have no more to go; return a 'past the end' index
return Index(indexSet: indexSet, value: value + 1, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount)
} else {
return Index(indexSet: indexSet, rangeIndex: rangeIndex + 1, rangeCount: rangeCount, first: true)
}
} else {
// Move to the next value in this range
return Index(indexSet: indexSet, value: value + 1, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount)
}
}
private mutating func _successorInPlace() {
if value + 1 == extent.upperBound {
// Move to the next range
if rangeIndex + 1 == rangeCount {
// We have no more to go; return a 'past the end' index
value += 1
} else {
rangeIndex += 1
extent = indexSet._range(at: rangeIndex)
value = extent.lowerBound
}
} else {
// Move to the next value in this range
value += 1
}
}
private func predecessor() -> Index {
if value == extent.lowerBound {
// Move to the next range
if rangeIndex == 0 {
// We have no more to go
return Index(indexSet: indexSet, value: value, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount)
} else {
return Index(indexSet: indexSet, rangeIndex: rangeIndex - 1, rangeCount: rangeCount, first: false)
}
} else {
// Move to the previous value in this range
return Index(indexSet: indexSet, value: value - 1, extent: extent, rangeIndex: rangeIndex, rangeCount: rangeCount)
}
}
public var description: String {
return "index \(value) in a range of \(extent) [range #\(rangeIndex + 1)/\(rangeCount)]"
}
private mutating func _predecessorInPlace() {
if value == extent.lowerBound {
// Move to the next range
if rangeIndex == 0 {
// We have no more to go
} else {
rangeIndex -= 1
extent = indexSet._range(at: rangeIndex)
value = extent.upperBound - 1
}
} else {
// Move to the previous value in this range
value -= 1
}
}
}
public typealias ReferenceType = NSIndexSet
public typealias Element = Int
private var _handle: _MutablePairHandle<NSIndexSet, NSMutableIndexSet>
internal init(indexesIn range: NSRange) {
_handle = _MutablePairHandle(NSIndexSet(indexesIn: range), copying: false)
}
/// Initialize an `IndexSet` with a range of integers.
public init(integersIn range: Range<Element>) {
_handle = _MutablePairHandle(NSIndexSet(indexesIn: _toNSRange(range)), copying: false)
}
/// Initialize an `IndexSet` with a single integer.
public init(integer: Element) {
_handle = _MutablePairHandle(NSIndexSet(index: integer), copying: false)
}
/// Initialize an empty `IndexSet`.
public init() {
_handle = _MutablePairHandle(NSIndexSet(), copying: false)
}
public var hashValue : Int {
return _handle.map { $0.hash }
}
/// Returns the number of integers in `self`.
public var count: Int {
return _handle.map { $0.count }
}
public func makeIterator() -> IndexingIterator<IndexSet> {
return IndexingIterator(_elements: self)
}
/// Returns a `Range`-based view of `self`.
///
/// - parameter range: A subrange of `self` to view. The default value is `nil`, which means that the entire `IndexSet` is used.
public func rangeView(of range : Range<Element>? = nil) -> RangeView {
return RangeView(indexSet: self, intersecting: range)
}
private func _indexOfRange(containing integer : Element) -> RangeView.Index? {
let result = _handle.map {
__NSIndexSetIndexOfRangeContainingIndex($0, UInt(integer))
}
if result == UInt(NSNotFound) {
return nil
} else {
return Int(result)
}
}
private func _range(at index: RangeView.Index) -> Range<Element> {
return _handle.map {
var location : UInt = 0
var length : UInt = 0
if __NSIndexSetRangeCount($0) == 0 {
return 0..<0
}
__NSIndexSetRangeAtIndex($0, UInt(index), &location, &length)
return Int(location)..<Int(location)+Int(length)
}
}
private var _rangeCount : Int {
return _handle.map {
Int(__NSIndexSetRangeCount($0))
}
}
public var startIndex: Index {
// TODO: We should cache this result
// If this winds up being NSNotFound, that's ok because then endIndex is also NSNotFound, and empty collections have startIndex == endIndex
return Index(firstIn: self)
}
public var endIndex: Index {
// TODO: We should cache this result
return Index(lastIn: self)
}
public subscript(index : Index) -> Element {
return index.value
}
public subscript(bounds: Range<Index>) -> BidirectionalSlice<IndexSet> {
return BidirectionalSlice(base: self, bounds: bounds)
}
// We adopt the default implementation of subscript(range: Range<Index>) from MutableCollection
private func _toOptional(_ x : Int) -> Int? {
if x == NSNotFound { return nil } else { return x }
}
/// Returns the first integer in `self`, or nil if `self` is empty.
public var first: Element? {
return _handle.map { _toOptional($0.firstIndex) }
}
/// Returns the last integer in `self`, or nil if `self` is empty.
public var last: Element? {
return _handle.map { _toOptional($0.lastIndex) }
}
/// Returns an integer contained in `self` which is greater than `integer`.
public func integerGreaterThan(_ integer: Element) -> Element {
return _handle.map { $0.indexGreaterThanIndex(integer) }
}
/// Returns an integer contained in `self` which is less than `integer`.
public func integerLessThan(_ integer: Element) -> Element {
return _handle.map { $0.indexLessThanIndex(integer) }
}
/// Returns an integer contained in `self` which is greater than or equal to `integer`.
public func integerGreaterThanOrEqualTo(_ integer: Element) -> Element {
return _handle.map { $0.indexGreaterThanOrEqual(to: integer) }
}
/// Returns an integer contained in `self` which is less than or equal to `integer`.
public func integerLessThanOrEqualTo(_ integer: Element) -> Element {
return _handle.map { $0.indexLessThanOrEqual(to: integer) }
}
/// Return a `Range<IndexSet.Index>` which can be used to subscript the index set.
///
/// The resulting range is the range of the intersection of the integers in `range` with the index set.
///
/// - parameter range: The range of integers to include.
public func indexRange(in range: Range<Element>) -> Range<Index> {
if range.isEmpty {
let i = Index(indexSet: self, index: 0)
return i..<i
}
if range.lowerBound > last || (range.upperBound - 1) < first {
let i = Index(indexSet: self, index: 0)
return i..<i
}
let resultFirst = Index(indexSet: self, index: integerGreaterThanOrEqualTo(range.lowerBound))
let resultLast = Index(indexSet: self, index: integerLessThanOrEqualTo(range.upperBound - 1))
return resultFirst..<resultLast.successor()
}
/// Returns the count of integers in `self` that intersect `range`.
public func count(in range: Range<Element>) -> Int {
return _handle.map { $0.countOfIndexes(in: _toNSRange(range)) }
}
/// Returns `true` if `self` contains `integer`.
public func contains(_ integer: Element) -> Bool {
return _handle.map { $0.contains(integer) }
}
/// Returns `true` if `self` contains all of the integers in `range`.
public func contains(integersIn range: Range<Element>) -> Bool {
return _handle.map { $0.contains(in: _toNSRange(range)) }
}
/// Returns `true` if `self` contains any of the integers in `indexSet`.
public func contains(integersIn indexSet: IndexSet) -> Bool {
return _handle.map { $0.contains(indexSet) }
}
/// Returns `true` if `self` intersects any of the integers in `range`.
public func intersects(integersIn range: Range<Element>) -> Bool {
return _handle.map { $0.intersects(in: _toNSRange(range)) }
}
// MARK: -
// Indexable
public func index(after i: Index) -> Index {
return i.successor()
}
public func formIndex(after i: inout Index) {
i._successorInPlace()
}
public func index(before i: Index) -> Index {
return i.predecessor()
}
public func formIndex(before i: inout Index) {
i._predecessorInPlace()
}
// MARK: -
// MARK: SetAlgebra
/// Union the `IndexSet` with `other`.
public mutating func formUnion(_ other: IndexSet) {
self = self.union(other)
}
/// Union the `IndexSet` with `other`.
public func union(_ other: IndexSet) -> IndexSet {
// This algorithm is naïve but it works. We could avoid calling insert in some cases.
var result = IndexSet()
for r in self.rangeView() {
result.insert(integersIn: Range(r))
}
for r in other.rangeView() {
result.insert(integersIn: Range(r))
}
return result
}
/// Exclusive or the `IndexSet` with `other`.
public func symmetricDifference(_ other: IndexSet) -> IndexSet {
var result = IndexSet()
var boundaryIterator = IndexSetBoundaryIterator(self, other)
var flag = false
var start = 0
while let i = boundaryIterator.next() {
if !flag {
// Starting a range; if the edge is contained or not depends on the xor of this particular value.
let startInclusive = self.contains(i) != other.contains(i)
start = startInclusive ? i : i + 1
flag = true
} else {
// Ending a range; if the edge is contained or not depends on the xor of this particular value.
let endInclusive = self.contains(i) != other.contains(i)
let end = endInclusive ? i + 1 : i
if start < end {
// Otherwise, we had an empty range
result.insert(integersIn: start..<end)
}
flag = false
}
// We never have to worry about having flag set to false after exiting this loop because the iterator will always return an even number of results; ranges come in pairs, and we always alternate flag
}
return result
}
/// Exclusive or the `IndexSet` with `other`.
public mutating func formSymmetricDifference(_ other: IndexSet) {
self = self.symmetricDifference(other)
}
/// Intersect the `IndexSet` with `other`.
public func intersection(_ other: IndexSet) -> IndexSet {
var result = IndexSet()
var boundaryIterator = IndexSetBoundaryIterator(self, other)
var flag = false
var start = 0
while let i = boundaryIterator.next() {
if !flag {
// If both sets contain then start a range.
if self.contains(i) && other.contains(i) {
flag = true
start = i
}
} else {
// If both sets contain then end a range.
if self.contains(i) && other.contains(i) {
flag = false
result.insert(integersIn: start..<(i + 1))
}
}
}
return result
}
/// Intersect the `IndexSet` with `other`.
public mutating func formIntersection(_ other: IndexSet) {
self = self.intersection(other)
}
/// Insert an integer into the `IndexSet`.
@discardableResult
public mutating func insert(_ integer: Element) -> (inserted: Bool, memberAfterInsert: Element) {
_applyMutation { $0.add(integer) }
// TODO: figure out how to return the truth here
return (true, integer)
}
/// Insert an integer into the `IndexSet`.
@discardableResult
public mutating func update(with integer: Element) -> Element? {
_applyMutation { $0.add(integer) }
// TODO: figure out how to return the truth here
return integer
}
/// Remove an integer from the `IndexSet`.
@discardableResult
public mutating func remove(_ integer: Element) -> Element? {
// TODO: Add method to NSIndexSet to do this in one call
let result : Element? = contains(integer) ? integer : nil
_applyMutation { $0.remove(integer) }
return result
}
// MARK: -
/// Remove all values from the `IndexSet`.
public mutating func removeAll() {
_applyMutation { $0.removeAllIndexes() }
}
/// Insert a range of integers into the `IndexSet`.
public mutating func insert(integersIn range: Range<Element>) {
_applyMutation { $0.add(in: _toNSRange(range)) }
}
/// Remove a range of integers from the `IndexSet`.
public mutating func remove(integersIn range: Range<Element>) {
_applyMutation { $0.remove(in: _toNSRange(range)) }
}
/// Returns `true` if self contains no values.
public var isEmpty : Bool {
return self.count == 0
}
/// Returns an IndexSet filtered according to the result of `includeInteger`.
///
/// - parameter range: A range of integers. For each integer in the range that intersects the integers in the IndexSet, then the `includeInteger predicate will be invoked. Pass `nil` (the default) to use the entire range.
/// - parameter includeInteger: The predicate which decides if an integer will be included in the result or not.
public func filteredIndexSet(in range : Range<Element>? = nil, includeInteger: @noescape (Element) throws -> Bool) rethrows -> IndexSet {
let r : NSRange = range != nil ? _toNSRange(range!) : NSMakeRange(0, NSNotFound - 1)
return try _handle.map {
var error : Swift.Error? = nil
let result = $0.indexes(in: r, options: [], passingTest: { (i, stop) -> Bool in
do {
let include = try includeInteger(i)
return include
} catch let e {
error = e
stop.pointee = true
return false
}
}) as IndexSet
if let e = error {
throw e
} else {
return result
}
}
}
/// For a positive delta, shifts the indexes in [index, INT_MAX] to the right, thereby inserting an "empty space" [index, delta], for a negative delta, shifts the indexes in [index, INT_MAX] to the left, thereby deleting the indexes in the range [index - delta, delta].
public mutating func shift(startingAt integer: Element, by delta: IndexSet.IndexDistance) {
_applyMutation { $0.shiftIndexesStarting(at: integer, by: delta) }
}
public var description: String {
return _handle.map { $0.description }
}
public var debugDescription: String {
return _handle.map { $0.debugDescription }
}
// Temporary boxing function, until we can get a native Swift type for NSIndexSet
/// TODO: making this inline causes the compiler to crash horrifically.
// @inline(__always)
mutating func _applyMutation<ReturnType>(_ whatToDo : @noescape (NSMutableIndexSet) throws -> ReturnType) rethrows -> ReturnType {
switch _handle._pointer {
case .Default(let i):
// We need to become mutable; by creating a new box we also become unique
let copy = i.mutableCopy(with: nil) as! NSMutableIndexSet
// Be sure to set the _handle before calling out; otherwise references to the struct in the closure may be looking at the old _handle
_handle = _MutablePairHandle(copy, copying: false)
let result = try whatToDo(copy)
return result
case .Mutable(let m):
// Only create a new box if we are not uniquely referenced
if !isUniquelyReferencedNonObjC(&_handle) {
let copy = m.mutableCopy(with: nil) as! NSMutableIndexSet
_handle = _MutablePairHandle(copy, copying: false)
let result = try whatToDo(copy)
return result
} else {
return try whatToDo(m)
}
}
}
// MARK: - Bridging Support
private var reference: NSIndexSet {
return _handle.reference
}
private init(reference: NSIndexSet) {
_handle = _MutablePairHandle(reference)
}
}
/// Iterate two index sets on the boundaries of their ranges. This is where all of the interesting stuff happens for exclusive or, intersect, etc.
private struct IndexSetBoundaryIterator : IteratorProtocol {
private typealias Element = IndexSet.Element
private var i1 : IndexSet.RangeView.Iterator
private var i2 : IndexSet.RangeView.Iterator
private var i1Range : CountableRange<Element>?
private var i2Range : CountableRange<Element>?
private var i1UsedFirst : Bool
private var i2UsedFirst : Bool
private init(_ is1 : IndexSet, _ is2 : IndexSet) {
i1 = is1.rangeView().makeIterator()
i2 = is2.rangeView().makeIterator()
i1Range = i1.next()
i2Range = i2.next()
// A sort of cheap iterator on [i1Range.first, i1Range.last]
i1UsedFirst = false
i2UsedFirst = false
}
private mutating func next() -> Element? {
if i1Range == nil && i2Range == nil {
return nil
}
let nextIn1 : Element
if let r = i1Range {
nextIn1 = i1UsedFirst ? r.last! : r.first!
} else {
nextIn1 = Int.max
}
let nextIn2 : Element
if let r = i2Range {
nextIn2 = i2UsedFirst ? r.last! : r.first!
} else {
nextIn2 = Int.max
}
var result : Element
if nextIn1 <= nextIn2 {
// 1 has the next element, or they are the same. We need to iterate both the value from is1 and is2 in the == case.
result = nextIn1
if i1UsedFirst { i1Range = i1.next() }
i1UsedFirst = !i1UsedFirst
} else {
// 2 has the next element
result = nextIn2
if i2UsedFirst { i2Range = i2.next() }
i2UsedFirst = !i2UsedFirst
}
return result
}
}
public func ==(lhs: IndexSet, rhs: IndexSet) -> Bool {
return lhs._handle.map { $0.isEqual(to: rhs) }
}
private func _toNSRange(_ r : Range<IndexSet.Element>) -> NSRange {
return NSMakeRange(r.lowerBound, r.upperBound - r.lowerBound)
}
extension IndexSet {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSIndexSet.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSIndexSet {
return reference
}
public static func _forceBridgeFromObjectiveC(_ x: NSIndexSet, result: inout IndexSet?) {
result = IndexSet(reference: x)
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSIndexSet, result: inout IndexSet?) -> Bool {
result = IndexSet(reference: x)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSIndexSet?) -> IndexSet {
return IndexSet(reference: source!)
}
}
// MARK: Protocol
// TODO: This protocol should be replaced with a native Swift object like the other Foundation bridged types. However, NSIndexSet does not have an abstract zero-storage base class like NSCharacterSet, NSData, and NSAttributedString. Therefore the same trick of laying it out with Swift ref counting does not work.and
/// Holds either the immutable or mutable version of a Foundation type.
///
/// In many cases, the immutable type has optimizations which make it preferred when we know we do not need mutation.
private enum _MutablePair<ImmutableType, MutableType> {
case Default(ImmutableType)
case Mutable(MutableType)
}
/// A class type which acts as a handle (pointer-to-pointer) to a Foundation reference type which has both an immutable and mutable class (e.g., NSData, NSMutableData).
///
/// a.k.a. Box
private final class _MutablePairHandle<ImmutableType : NSObject, MutableType : NSObject where ImmutableType : NSMutableCopying, MutableType : NSMutableCopying> {
private var _pointer: _MutablePair<ImmutableType, MutableType>
/// Initialize with an immutable reference instance.
///
/// - parameter immutable: The thing to stash.
/// - parameter copying: Should be true unless you just created the instance (or called copy) and want to transfer ownership to this handle.
init(_ immutable : ImmutableType, copying : Bool = true) {
if copying {
self._pointer = _MutablePair.Default(immutable.copy() as! ImmutableType)
} else {
self._pointer = _MutablePair.Default(immutable)
}
}
/// Initialize with a mutable reference instance.
///
/// - parameter mutable: The thing to stash.
/// - parameter copying: Should be true unless you just created the instance (or called copy) and want to transfer ownership to this handle.
init(_ mutable : MutableType, copying : Bool = true) {
if copying {
self._pointer = _MutablePair.Mutable(mutable.mutableCopy() as! MutableType)
} else {
self._pointer = _MutablePair.Mutable(mutable)
}
}
/// Apply a closure to the reference type, regardless if it is mutable or immutable.
@inline(__always)
func map<ReturnType>(_ whatToDo : @noescape (ImmutableType) throws -> ReturnType) rethrows -> ReturnType {
switch _pointer {
case .Default(let i):
return try whatToDo(i)
case .Mutable(let m):
// TODO: It should be possible to reflect the constraint that MutableType is a subtype of ImmutableType in the generics for the class, but I haven't figured out how yet. For now, cheat and unsafe bit cast.
return try whatToDo(unsafeBitCast(m, to: ImmutableType.self))
}
}
var reference : ImmutableType {
switch _pointer {
case .Default(let i):
return i
case .Mutable(let m):
// TODO: It should be possible to reflect the constraint that MutableType is a subtype of ImmutableType in the generics for the class, but I haven't figured out how yet. For now, cheat and unsafe bit cast.
return unsafeBitCast(m, to: ImmutableType.self)
}
}
}
| apache-2.0 | 0388ea0b3947af6e824cc599bd633afa | 36.828704 | 316 | 0.58524 | 4.889886 | false | false | false | false |
benlangmuir/swift | test/IRGen/multi_payload_shifting.swift | 34 | 846 | // RUN: %target-swift-frontend -enable-objc-interop -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
class Tag {}
struct Scalar {
var str = ""
var x = Tag()
var style: BinaryChoice = .zero
enum BinaryChoice: UInt32 {
case zero = 0
case one
}
}
public struct Sequence {
var tag: Tag = Tag()
var tag2: Tag = Tag()
}
enum Node {
case scalar(Scalar)
case sequence(Sequence)
}
// CHECK: define internal i32 @"$s22multi_payload_shifting4NodeOwet"(%swift.opaque* noalias %value, i32 %numEmptyCases, %swift.type* %Node)
// CHECK: [[ADDR:%.*]] = getelementptr inbounds { i64, i64, i64, i8 }, { i64, i64, i64, i8 }* {{.*}}, i32 0, i32 3
// CHECK: [[BYTE:%.*]] = load i8, i8* [[ADDR]]
// Make sure we zext before we shift.
// CHECK: [[ZEXT:%.*]] = zext i8 [[BYTE]] to i32
// CHECK: shl i32 [[ZEXT]], 10
| apache-2.0 | 82826c1ccd3c4799f9729de096a42326 | 25.4375 | 139 | 0.617021 | 2.927336 | false | false | false | false |
ThumbWorks/i-meditated | IMeditated/QuickEntryViewController.swift | 1 | 4268 | //
// ViewController.swift
// IMeditated
//
// Created by Bob Spryn on 8/9/16.
// Copyright © 2016 Thumbworks. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
protocol QuickEntryViewModelType {
var todaysDuration: Driver<String?> { get }
var yesterdaysDuration: Driver<String?> { get }
}
class QuickEntryViewController: UIViewController {
@IBOutlet private var quickEntryButtons: [MinutesButton]!
@IBOutlet private var customButton: UIButton!
@IBOutlet private var todayDurationLabel: UILabel!
@IBOutlet private var yesterdayDurationLabel: UILabel!
@IBOutlet private var todayTextLabel: UILabel!
@IBOutlet private var yesterdayTextLabel: UILabel!
let actionModel: MainContextActionsType!
let viewModel: QuickEntryViewModelType!
private let disposables = DisposeBag()
let listNavButton = UIBarButtonItem.init(barButtonSystemItem: .bookmarks, target: nil, action: nil)
let infoButton = UIButton(type: UIButtonType.infoDark)
lazy var infoBarButton:UIBarButtonItem = UIBarButtonItem(customView: self.infoButton)
// expose a listTap event for the coordinator to tie navigation into
lazy var listTap: ControlEvent<Void> = {
self.listNavButton.rx.tap
}()
// expose an info tap event for the coordinator to tie navigation into
lazy var infotap: ControlEvent<Void> = {
self.infoButton.rx.tap
}()
// We use a subject as the inbetween for the UIControl and the exposed observable below
// mainly because the custom tap behavior is setup before the view loads
private let customTapSubject = PublishSubject<Void>()
// expose a customDurtion tap event for the coordinator to tie navigation into
lazy var customTap: Observable<Void> = {
self.customTapSubject.asObservable()
}()
init(viewModel: QuickEntryViewModelType, actionModel:MainContextActionsType) {
self.actionModel = actionModel
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
self.navigationItem.rightBarButtonItem = self.listNavButton
self.navigationItem.leftBarButtonItem = self.infoBarButton
// grab the initial meditations
actionModel.fetchMeditations()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(named: .dutchWhite)
self.todayDurationLabel.textColor = UIColor(named: .richBlack)
self.todayTextLabel.textColor = UIColor(named: .richBlack)
self.todayTextLabel.font = UIFont.init(descriptor: self.todayTextLabel.font.fontDescriptor.withSymbolicTraits(.traitBold)!, size: 0)
self.yesterdayDurationLabel.textColor = UIColor(named: .spicyMix)
self.yesterdayTextLabel.textColor = UIColor(named: .spicyMix)
customButton.backgroundColor = UIColor.white
customButton.setTitleColor(UIColor(named: .spicyMix), for: .normal)
customButton.layer.cornerRadius = 10
customButton.layer.shadowRadius = 5
customButton.layer.shadowOpacity = 0.15
customButton.layer.shadowOffset = CGSize.zero
customButton.layer.shadowColor = UIColor(named: .spicyMix).cgColor
// connect the tap to the subject
customButton.rx.tap.subscribe(self.customTapSubject)
.addDisposableTo(self.disposables)
self.quickEntryButtons.forEach { button in
button.rx.tap.subscribe(onNext: { [unowned self] value in
self.actionModel.saveMeditation(minutes: button.minutes)
}).addDisposableTo(self.disposables)
}
self.viewModel.todaysDuration
.drive(self.todayDurationLabel.rx.text)
.addDisposableTo(self.disposables)
self.viewModel.yesterdaysDuration
.drive(self.yesterdayDurationLabel.rx.text)
.addDisposableTo(self.disposables)
}
override func viewDidLayoutSubviews() {
self.quickEntryButtons.forEach { button in
button.layer.cornerRadius = button.frame.size.width/2
}
}
}
| mit | d7fc6b6c1c94cfee3de460c100ccb0b5 | 36.429825 | 140 | 0.693461 | 4.683864 | false | false | false | false |
xsunsmile/tipCalculator | TipsCalculator/ViewController.swift | 1 | 2818 | //
// ViewController.swift
// TipsCalculator
//
// Created by Hao Sun on 1/31/15.
// Copyright (c) 2015 Hao Sun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipControl: UISegmentedControl!
var tipPercentages: Array<Double> = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
self.tipPercentages = [
loadUserPreference("tip1", defaultValue: 0.18),
loadUserPreference("tip2", defaultValue: 0.20),
loadUserPreference("tip3", defaultValue: 0.22)
]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func BillEditingChanged(sender: AnyObject) {
refreshValues()
}
@IBAction func onMainTap(sender: AnyObject) {
view.endEditing(true)
}
func saveUserPreference(key: NSString, value: Double) {
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setDouble(value, forKey: key)
defaults.synchronize()
}
func loadUserPreference(key: NSString, defaultValue: Double) -> Double {
var defaults = NSUserDefaults.standardUserDefaults()
if defaults.doubleForKey(key) != 0 {
return defaults.doubleForKey(key)
} else {
saveUserPreference(key, value: defaultValue)
return defaultValue
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tipPercentages = [
loadUserPreference("tip1", defaultValue: 0.18),
loadUserPreference("tip2", defaultValue: 0.20),
loadUserPreference("tip3", defaultValue: 0.22)
]
tipControl.setTitle(String(format: "%d%%", Int(tipPercentages[0]*100)), forSegmentAtIndex: 0)
tipControl.setTitle(String(format: "%d%%", Int(tipPercentages[1]*100)), forSegmentAtIndex: 1)
tipControl.setTitle(String(format: "%d%%", Int(tipPercentages[2]*100)), forSegmentAtIndex: 2)
refreshValues()
}
func refreshValues() {
var tipPercentage = tipPercentages[tipControl.selectedSegmentIndex]
var billAmount = NSString(string: billField.text).doubleValue
var tip = billAmount * tipPercentage
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", billAmount+tip)
}
}
| apache-2.0 | 54494ad8007215b867eaf44b307802c7 | 31.390805 | 101 | 0.630234 | 4.736134 | false | false | false | false |
Octadero/TensorFlow | Sources/TensorFlowKit/Graph.swift | 1 | 9260 | /* Copyright 2017 The Octadero Authors. All Rights Reserved.
Created by Volodymyr Pavliukevych on 2017.
Licensed under the GPL License, Version 3.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.gnu.org/licenses/gpl-3.0.txt
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 CTensorFlow
import Proto
import CAPI
/// Swift `Error` represents error occurred at `Graph` manipulation.
public enum GraphError: Error {
case newBufferIsNil
case incorrectAttributeValueType
}
/// Graph represents a computation graph. Graphs may be shared between sessions.
public class Graph {
public private(set) var tfGraph: TF_Graph
/// Public constructor.
/// - Return: Returns a new Graph.
public init() {
tfGraph = CAPI.newGraph()
}
/// Returns list of VariableV2, VariableShape and Variable operations.
public var variables: [TensorFlowKit.Operation] {
return operations.filter { $0.type == "VariableV2" || $0.type == "Variable" || $0.type == "VariableShape"}
}
public var operations: [TensorFlowKit.Operation] {
return CAPI.operations(of: self.tfGraph).map { TensorFlowKit.Operation(tfOperation: $0, graph: self) }
}
/// Operation returns the Operation named name in the Graph, or nil if no such
/// operation is present.
public func operation(by name:String) throws -> Operation? {
if let tfOperation = CAPI.operation(in: self.tfGraph, by: name) {
return TensorFlowKit.Operation(tfOperation: tfOperation, graph: self)
}
return nil
}
/// Dispatch attribute commands to special CAPI function.
func setAttribute(operationDescription: TF_OperationDescription?, name: String, value: Any) throws {
if let tensor = value as? Tensor {
try CAPI.setAttribute(tensor: tensor.tfTensor, by: name, for: operationDescription)
} /*else if let tensor = value as? Tensor<Float> {
try CAPI.setAttribute(tensor: tensor.tfTensor, by: name, for: operationDescription)
} else if let tensor = value as? Tensor<Double> {
try CAPI.setAttribute(tensor: tensor.tfTensor, by: name, for: operationDescription)
/// Special case Any.Type -> TF_DataType
}*/ else if let anyType = value as? Any.Type {
let dtype = try TF_DataType(for: anyType)
try setAttribute(operationDescription: operationDescription, name: name, value: dtype)
/// Special case [Any.Type] -> [TF_DataType]
} else if let anyTypes = value as? [Any.Type] {
let dtypes = try anyTypes.map { try TF_DataType(for: $0) }
try setAttribute(operationDescription: operationDescription, name: name, value: dtypes)
} else if let attrValue = value as? Tensorflow_AttrValue {
try CAPI.setAttribute(proto: attrValue, by: name, for: operationDescription)
} else if let dtType = value as? TF_DataType {
CAPI.setAttribute(type: dtType, by: name, for: operationDescription)
} else if let bool = value as? Bool {
CAPI.setAttribute(value: bool, by: name, for: operationDescription)
} else if let string = value as? String {
CAPI.setAttribute(value: string, by: name, for: operationDescription)
} else if let strings = value as? [String] {
CAPI.setAttribute(values: strings, by: name, for: operationDescription)
} else if let int = value as? Int64 {
CAPI.setAttribute(value: int, by: name, for: operationDescription)
} else if let int = value as? Int32 {
CAPI.setAttribute(value: int, by: name, for: operationDescription)
} else if let int = value as? Int8 {
CAPI.setAttribute(value: int, by: name, for: operationDescription)
} else if let int = value as? UInt8 {
CAPI.setAttribute(value: int, by: name, for: operationDescription)
} else if let float = value as? Float {
CAPI.setAttribute(value: float, by: name, for: operationDescription)
} else if let collectionOfFloat = value as? [Float] {
CAPI.setAttribute(values: collectionOfFloat, by: name, for: operationDescription)
} else if let collectionOfInt64 = value as? [Int64] {
CAPI.setAttribute(values: collectionOfInt64, by: name, for: operationDescription)
} else if let collectionOfBool = value as? [Bool] {
CAPI.setAttribute(values: collectionOfBool, by: name, for: operationDescription)
} else if let collectionOfDataType = value as? [TF_DataType] {
CAPI.setAttribute(types: collectionOfDataType, by: name, for: operationDescription)
} else if let shape = value as? Shape {
switch shape {
case .unknown:
CAPI.setAttributeShape(dimensions: nil, by: name, for: operationDescription)
case .dimensions(let value):
CAPI.setAttributeShape(dimensions: value, by: name, for: operationDescription)
}
} else {
//TODO: - Add [Shape] and [Tensor] to attributes.
fatalError("Not ready for: \(type(of:value)) value")
}
}
/// Internal function for appending new operation
func addOperation(specification: OpSpec, controlDependencies: [Operation]? = nil) throws -> Operation {
let tfOperationDescription = newOperation(in: self.tfGraph, operationType: specification.type, operationName: specification.name)
for input in specification.input {
if let output = input as? Output {
CAPI.add(input: output.tfOutput(), for: tfOperationDescription)
} else if let outputs = input as? [Output] {
try CAPI.add(inputs: outputs.map { $0.tfOutput() }, for: tfOperationDescription)
} else {
fatalError("Can't get input of: \(type(of: input))")
}
}
for (name, value) in specification.attrs {
try setAttribute(operationDescription: tfOperationDescription, name: name, value: value)
}
if let controlDependencies = controlDependencies {
controlDependencies.forEach({ (operation) in
CAPI.add(controlInput: operation.tfOperation, for: tfOperationDescription)
})
}
let tfOperation = try finish(operationDescription: tfOperationDescription)
let operation = TensorFlowKit.Operation(tfOperation: tfOperation, graph: self)
return operation
}
/// Obtain `Tensorflow_GraphDef` representation of current graph.
public func graphDef() throws -> Tensorflow_GraphDef {
return try Tensorflow_GraphDef(serializedData: data())
}
/// Return serialized representation of `Graph` (as a GraphDef protocol
/// message) to `output_graph_def` (allocated by TF_NewBuffer()).
///
/// May fail on very large graphs in the future.
public func data() throws -> Data {
let data = try allocAndProcessBuffer { (bufferPointer) in
try CAPI.graphDef(of: self.tfGraph, graphDef: bufferPointer)
}
return data
}
/// Save graph at file url.
/// - Parameters: file - file where file will be stored.
public func save(at file: URL, asText: Bool = false) throws {
if asText {
let txtGraphDef = try graphDef().textFormatString()
if let data = txtGraphDef.data(using: .ascii) {
try data.write(to: file)
}
} else {
try data().write(to: file)
}
}
/// Import imports the nodes and edges from a serialized representation of
/// another Graph into g.
///
/// Names of imported nodes will be prefixed with prefix.
public func `import`(from url: URL, prefix: String = "", asText: Bool = false) throws {
let data = try Data(contentsOf: url, options: [])
try `import`(data: data, prefix: prefix, asText: asText)
}
/// Import imports the nodes and edges from a serialized representation of
/// another Graph into g.
///
/// Names of imported nodes will be prefixed with prefix.
public func `import`(data: Data, prefix: String, asText: Bool = false) throws {
var data = data
if asText {
if let string = String(data: data, encoding: .ascii) {
let graphDef = try Tensorflow_GraphDef(textFormatString: string)
data = try graphDef.serializedData()
}
}
let opts = newImportGraphDefOptions()
defer {
delete(importGraphDefOptions: opts)
}
setPrefix(into: opts, prefix: prefix)
let buffer = CAPI.newBuffer(from: data)
defer {
deleteBuffer(buffer)
}
try CAPI.import(graph: self.tfGraph, in: buffer, sessionOptions: opts)
}
/// At deinit phase we need to delete C Graph object by TF_Grapht pointer.
deinit {
CAPI.delete(graph: tfGraph)
}
}
| gpl-3.0 | 50ef4cf0078643a2cb9162f137c6bf9e | 42.069767 | 131 | 0.649784 | 4.214838 | false | false | false | false |
nekowen/GeoHex3.swift | Sources/GeoHex3Swift/Zone.swift | 1 | 2839 | //
// Zone.swift
// GeoHex3.swift
//
// Created by nekowen on 2017/03/30.
// License: MIT License
//
import Foundation
import CoreLocation
public class Zone {
fileprivate let _coordinate: CLLocationCoordinate2D
fileprivate let _xy: XY
fileprivate let _code: String
fileprivate let _level: Int
fileprivate var _polygonCache: [CLLocationCoordinate2D]?
public init(coordinate: CLLocationCoordinate2D, xy: XY, code: String) {
self._coordinate = coordinate
self._xy = xy
self._code = code
self._level = code.length - 2
}
public var x: Double {
return self._xy.x
}
public var y: Double {
return self._xy.y
}
public var position: XY {
return self._xy
}
public var latitude: Double {
return self._coordinate.latitude
}
public var longitude: Double {
return self._coordinate.longitude
}
public var code: String {
return self._code
}
public var level: Int {
return self._level
}
public var hexSize: Double {
return GeoHex3.hexSize(level: self.level)
}
public var coordinate: CLLocationCoordinate2D {
return self._coordinate
}
public var polygon: [CLLocationCoordinate2D] {
if self._polygonCache == nil {
let h_lat = self.latitude
let h_xy = GeoHex3.loc2xy(latitude: self.latitude, longitude: self.longitude)
let h_x = h_xy.x
let h_y = h_xy.y
let h_deg = tan(Double.pi * (60.0 / 180.0))
let h_size = self.hexSize
let h_top = GeoHex3.xy2loc(x: h_x, y: h_y + h_deg * h_size).latitude
let h_btm = GeoHex3.xy2loc(x: h_x, y: h_y - h_deg * h_size).latitude
let h_l = GeoHex3.xy2loc(x: h_x - 2 * h_size, y: h_y).longitude
let h_r = GeoHex3.xy2loc(x: h_x + 2 * h_size, y: h_y).longitude
let h_cl = GeoHex3.xy2loc(x: h_x - 1 * h_size, y: h_y).longitude
let h_cr = GeoHex3.xy2loc(x: h_x + 1 * h_size, y: h_y).longitude
self._polygonCache = [
CLLocationCoordinate2D(latitude: h_lat, longitude: h_l),
CLLocationCoordinate2D(latitude: h_top, longitude: h_cl),
CLLocationCoordinate2D(latitude: h_top, longitude: h_cr),
CLLocationCoordinate2D(latitude: h_lat, longitude: h_r),
CLLocationCoordinate2D(latitude: h_btm, longitude: h_cr),
CLLocationCoordinate2D(latitude: h_btm, longitude: h_cl)
]
}
return self._polygonCache ?? []
}
}
extension Zone: Equatable {}
public func ==(lhs: Zone, rhs: Zone) -> Bool {
return lhs.code == rhs.code && lhs.position == rhs.position
}
| mit | 4c7fea4bb61deab6d781f83c1d02df7f | 28.268041 | 89 | 0.568862 | 3.672704 | false | false | false | false |
harlanhaskins/swift | test/Interop/Cxx/operators/non-member-inline-typechecker.swift | 1 | 264 | // RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-cxx-interop
import NonMemberInline
var lhs = IntBox(value: 42)
var rhs = IntBox(value: 23)
let resultPlus = lhs + rhs
let resultMinus = lhs - rhs
let resultStar = lhs * rhs
let resultSlash = lhs / rhs
| apache-2.0 | 1c81a08d587fc70b75b156a432985947 | 23 | 71 | 0.719697 | 3.069767 | false | false | false | false |
ktmswzw/FeelingClientBySwift | Pods/IBAnimatable/IBAnimatable/AnimatableBarButtonItem.swift | 1 | 1428 | //
// Created by Jake Lin on 12/16/15.
// Copyright © 2015 Jake Lin. All rights reserved.
//
import UIKit
@IBDesignable public class AnimatableBarButtonItem: UIBarButtonItem, BarButtonItemDesignable, Animatable {
// MARK: - BarButtonItemDesignable
@IBInspectable public var roundedImage: UIImage?
// MARK: - Lifecycle
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
configInspectableProperties()
}
public override func awakeFromNib() {
super.awakeFromNib()
configInspectableProperties()
}
// TODO: animations
// public override func layoutSubviews() {
// super.layoutSubviews()
//
// autoRunAnimation()
// }
// MARK: - Animatable
@IBInspectable public var animationType: String?
@IBInspectable public var autoRun: Bool = true
@IBInspectable public var duration: Double = Double.NaN
@IBInspectable public var delay: Double = Double.NaN
@IBInspectable public var damping: CGFloat = CGFloat.NaN
@IBInspectable public var velocity: CGFloat = CGFloat.NaN
@IBInspectable public var force: CGFloat = CGFloat.NaN
@IBInspectable public var repeatCount: Float = Float.NaN
@IBInspectable public var x: CGFloat = CGFloat.NaN
@IBInspectable public var y: CGFloat = CGFloat.NaN
// MARK: - Private
private func configInspectableProperties() {
// configAnimatableProperties()
confingBarButtonItemImage()
}
}
| mit | 8e4db5adb503f5dd0dc5f25c88d4fefa | 29.361702 | 106 | 0.733006 | 4.870307 | false | true | false | false |
xwu/swift | test/Generics/unify_nested_types_4.swift | 2 | 1442 | // RUN: %target-typecheck-verify-swift -requirement-machine=verify -dump-requirement-machine 2>&1 | %FileCheck %s
protocol P1 {
associatedtype A : P1
associatedtype B : P1
}
struct S1 : P1 {
typealias A = S1
typealias B = S2
}
struct S2 : P1 {
typealias A = S2
typealias B = S1
}
protocol P2 {
associatedtype A where A == S1
associatedtype B where B == S2
}
struct G<T : P1 & P2> {}
// T.A and T.B become concrete, which produces the following series of
// concretized nested types:
//
// T.A.[concrete: S1]
// T.B.[concrete: S2]
// T.A.A.[concrete: S1]
// T.A.B.[concrete: S2]
// T.B.A.[concrete: S2]
// T.B.B.[concrete: S1]
// ...
//
// This would normally go on forever, but since S1 and S2 are not generic,
// we solve this by merging the repeated types with T.A or T.B:
//
// T.A.A => T.A
// T.A.B => T.B
// T.B.A => T.B
// T.B.B => T.A
// ...
// CHECK-LABEL: Requirement machine for <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2>
// CHECK-LABEL: Rewrite system: {
// CHECK: - τ_0_0.[P1&P2:A].[P1:A] => τ_0_0.[P1&P2:A]
// CHECK: - τ_0_0.[P1&P2:A].[P1:B] => τ_0_0.[P1&P2:B]
// CHECK: - τ_0_0.[P1&P2:B].[P1:A] => τ_0_0.[P1&P2:B]
// CHECK: - τ_0_0.[P1&P2:B].[P1:B] => τ_0_0.[P1&P2:A]
// CHECK: }
// CHECK-LABEL: Property map: {
// CHECK: τ_0_0.[P1&P2:A] => { conforms_to: [P1] concrete_type: [concrete: S1] }
// CHECK: τ_0_0.[P1&P2:B] => { conforms_to: [P1] concrete_type: [concrete: S2] }
// CHECK: }
// CHECK: }
| apache-2.0 | 677e8a0d7d5ae4a18575af1de4829f34 | 24.517857 | 113 | 0.587124 | 2.246855 | false | false | false | false |
richardpiazza/SOSwift | Sources/SOSwift/Thing.swift | 1 | 5937 | import Foundation
/// The most generic type of item/entity.
public class Thing: Schema, Codable {
/// An additional type for the item, typically used for adding more specific types from external vocabularies in
/// microdata syntax.
///
/// This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use
/// the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker
/// understanding of extra types, in particular those defined externally.
public var additionalType: URL?
/// An alias for the item.
public var alternativeName: String?
/// A description of the item.
public var description: String?
/// A sub property of description.
///
/// A short description of the item used to disambiguate from other, similar items. Information from other
/// properties (in particular, name) may be necessary for the description to be useful for disambiguation.
public var disambiguatingDescription: String?
/// The identifier property represents any kind of identifier for any kind of Thing, such as ISBNs, GTIN codes,
/// UUIDs etc.
///
/// Schema.org provides dedicated properties for representing many of these, either as textual strings or as URL
/// (URI) links.
public var identifier: Identifier?
/// An image of the item. This can be a URL or a fully described ImageObject.
public var image: ImageObjectOrURL?
/// Indicates a page (or other CreativeWork) for which this thing is the main entity being described.
///
/// ## Inverse Property
/// _mainEntity_
public var mainEntityOfPage: CreativeWorkOrURL?
/// The name of the item.
public var name: String?
/// Indicates a potential Action, which describes an idealized action in which this thing would play an 'object'
/// role.
public var potentialAction: Action?
/// URL of a reference Web page that unambiguously indicates the item's identity.
///
/// ## Example
/// The URL of the item's Wikipedia page, Wikidata entry, or official website.
public var sameAs: [URL]?
/// A CreativeWork or Event about this Thing.
///
/// ## Inverse Property
/// _about_
public var subjectOf: CreativeWorkOrEvent?
/// URL of the item.
public var url: URL?
internal enum ThingCodingKeys: String, CodingKey {
case additionalType
case alternativeName
case description
case disambiguatingDescription
case identifier
case image
case mainEntityOfPage
case name
case potentialAction
case sameAs
case subjectOf
case url
}
public init() {
}
public convenience init(name: String) {
self.init()
self.name = name
}
public required init(from decoder: Decoder) throws {
let schema = try decoder.container(keyedBy: SchemaKeys.self)
let container = try decoder.container(keyedBy: ThingCodingKeys.self)
let id = try schema.decodeIfPresent(Identifier.self, forKey: .id)
let identifier = try container.decodeIfPresent(Identifier.self, forKey: .identifier)
switch (id, identifier) {
case (.some(let id), .none):
self.identifier = id
case (.some, .some(let identifier)), (.none, .some(let identifier)):
self.identifier = identifier
case (.none, .none):
break
}
additionalType = try container.decodeIfPresent(URL.self, forKey: .additionalType)
alternativeName = try container.decodeIfPresent(String.self, forKey: .alternativeName)
description = try container.decodeIfPresent(String.self, forKey: .description)
disambiguatingDescription = try container.decodeIfPresent(String.self, forKey: .disambiguatingDescription)
image = try container.decodeIfPresent(ImageObjectOrURL.self, forKey: .image)
mainEntityOfPage = try container.decodeIfPresent(CreativeWorkOrURL.self, forKey: .mainEntityOfPage)
name = try container.decodeIfPresent(String.self, forKey: .name)
potentialAction = try container.decodeIfPresent(Action.self, forKey: .potentialAction)
sameAs = try container.decodeIfPresent([URL].self, forKey: .sameAs)
subjectOf = try container.decodeIfPresent(CreativeWorkOrEvent.self, forKey: .subjectOf)
url = try container.decodeIfPresent(URL.self, forKey: .url)
}
public func encode(to encoder: Encoder) throws {
var schema = encoder.container(keyedBy: SchemaKeys.self)
try schema.encode(Swift.type(of: self).schemaContext, forKey: .context)
try schema.encode(Swift.type(of: self).schemaName, forKey: .type)
try schema.encodeIfPresent(identifier, forKey: .id)
var container = encoder.container(keyedBy: ThingCodingKeys.self)
try container.encodeIfPresent(identifier, forKey: .identifier)
try container.encodeIfPresent(additionalType, forKey: .additionalType)
try container.encodeIfPresent(alternativeName, forKey: .alternativeName)
try container.encodeIfPresent(description, forKey: .description)
try container.encodeIfPresent(disambiguatingDescription, forKey: .disambiguatingDescription)
try container.encodeIfPresent(image, forKey: .image)
try container.encodeIfPresent(mainEntityOfPage, forKey: .mainEntityOfPage)
try container.encodeIfPresent(name, forKey: .name)
try container.encodeIfPresent(potentialAction, forKey: .potentialAction)
try container.encodeIfPresent(sameAs, forKey: .sameAs)
try container.encodeIfPresent(subjectOf, forKey: .subjectOf)
try container.encodeIfPresent(url, forKey: .url)
}
}
| mit | bfe1dc7d86ca06b172a450009dbc7364 | 41.71223 | 118 | 0.678457 | 4.780193 | false | false | false | false |
minikin/Algorithmics | Pods/Charts/Charts/Classes/Renderers/HorizontalBarChartRenderer.swift | 6 | 20202 | //
// HorizontalBarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class HorizontalBarChartRenderer: BarChartRenderer
{
public override init(dataProvider: BarChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(dataProvider: dataProvider, animator: animator, viewPortHandler: viewPortHandler)
}
public override func drawDataSet(context context: CGContext, dataSet: IBarChartDataSet, index: Int)
{
guard let
dataProvider = dataProvider,
barData = dataProvider.barData,
animator = animator
else { return }
CGContextSaveGState(context)
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let drawBarShadowEnabled: Bool = dataProvider.isDrawBarShadowEnabled
let dataSetOffset = (barData.dataSetCount - 1)
let groupSpace = barData.groupSpace
let groupSpaceHalf = groupSpace / 2.0
let barSpace = dataSet.barSpace
let barSpaceHalf = barSpace / 2.0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
let barWidth: CGFloat = 0.5
let phaseY = animator.phaseY
var barRect = CGRect()
var barShadow = CGRect()
var y: Double
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)); j < count; j++)
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
// calculate the x-position, depending on datasetcount
let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(e.xIndex) + groupSpaceHalf
let values = e.values
if (!containsStacks || values == nil)
{
y = e.value
let bottom = x - barWidth + barSpaceHalf
let top = x + barWidth - barSpaceHalf
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY
}
else
{
left *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = viewPortHandler.contentLeft
barShadow.origin.y = barRect.origin.y
barShadow.size.width = viewPortHandler.contentWidth
barShadow.size.height = barRect.size.height
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
CGContextFillRect(context, barRect)
}
else
{
let vals = values!
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value
let bottom = x - barWidth + barSpaceHalf
let top = x + barWidth - barSpaceHalf
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY
}
else
{
left *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
barShadow.origin.x = viewPortHandler.contentLeft
barShadow.origin.y = barRect.origin.y
barShadow.size.width = viewPortHandler.contentWidth
barShadow.size.height = barRect.size.height
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// fill the stack
for (var k = 0; k < vals.count; k++)
{
let value = vals[k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let bottom = x - barWidth + barSpaceHalf
let top = x + barWidth - barSpaceHalf
var right: CGFloat, left: CGFloat
if isInverted
{
left = y >= yStart ? CGFloat(y) : CGFloat(yStart)
right = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
else
{
right = y >= yStart ? CGFloat(y) : CGFloat(yStart)
left = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
// multiply the height of the rect with the phase
right *= phaseY
left *= phaseY
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (k == 0 && !viewPortHandler.isInBoundsTop(barRect.origin.y + barRect.size.height))
{
// Skip to next bar
break
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsBottom(barRect.origin.y))
{
break
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor)
CGContextFillRect(context, barRect)
}
}
}
CGContextRestoreGState(context)
}
public override func prepareBarHighlight(x x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5
let top = x - barWidth + barspacehalf
let bottom = x + barWidth - barspacehalf
let left = CGFloat(y1)
let right = CGFloat(y2)
rect.origin.x = left
rect.origin.y = top
rect.size.width = right - left
rect.size.height = bottom - top
trans.rectValueToPixelHorizontal(&rect, phaseY: animator?.phaseY ?? 1.0)
}
public override func drawValues(context context: CGContext)
{
// if values are drawn
if (passesCheck())
{
guard let
dataProvider = dataProvider,
barData = dataProvider.barData,
animator = animator
else { return }
var dataSets = barData.dataSets
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
let textAlign = NSTextAlignment.Left
let valueOffsetPlus: CGFloat = 5.0
var posOffset: CGFloat
var negOffset: CGFloat
for (var dataSetIndex = 0, count = barData.dataSetCount; dataSetIndex < count; dataSetIndex++)
{
guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue }
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
let valueFont = dataSet.valueFont
let yOffset = -valueFont.lineHeight / 2.0
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let phaseY = animator.phaseY
let dataSetCount = barData.dataSetCount
let groupSpace = barData.groupSpace
// if only single values are drawn (sum)
if (!dataSet.isStacked)
{
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)); j < count; j++)
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let valuePoint = trans.getTransformedValueHorizontalBarChart(entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace)
if (!viewPortHandler.isInBoundsTop(valuePoint.y))
{
break
}
if (!viewPortHandler.isInBoundsX(valuePoint.x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(valuePoint.y))
{
continue
}
let val = e.value
let valueText = formatter.stringFromNumber(val)!
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if (isInverted)
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
drawValue(
context: context,
value: valueText,
xPos: valuePoint.x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoint.y + yOffset,
font: valueFont,
align: textAlign,
color: dataSet.valueTextColorAt(j))
}
}
else
{
// if each value of a potential stack should be drawn
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)); j < count; j++)
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let valuePoint = trans.getTransformedValueHorizontalBarChart(entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace)
let values = e.values
// we still draw stacked bars, but there is one non-stacked in between
if (values == nil)
{
if (!viewPortHandler.isInBoundsTop(valuePoint.y))
{
break
}
if (!viewPortHandler.isInBoundsX(valuePoint.x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(valuePoint.y))
{
continue
}
let val = e.value
let valueText = formatter.stringFromNumber(val)!
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if (isInverted)
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
drawValue(
context: context,
value: valueText,
xPos: valuePoint.x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoint.y + yOffset,
font: valueFont,
align: textAlign,
color: dataSet.valueTextColorAt(j))
}
else
{
let vals = values!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for (var k = 0; k < vals.count; k++)
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: CGFloat(y) * animator.phaseY, y: 0.0))
}
trans.pointValuesToPixel(&transformed)
for (var k = 0; k < transformed.count; k++)
{
let val = vals[k]
let valueText = formatter.stringFromNumber(val)!
// calculate the correct offset depending on the draw position of the value
let valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus))
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus)
if (isInverted)
{
posOffset = -posOffset - valueTextWidth
negOffset = -negOffset - valueTextWidth
}
let x = transformed[k].x + (val >= 0 ? posOffset : negOffset)
let y = valuePoint.y
if (!viewPortHandler.isInBoundsTop(y))
{
break
}
if (!viewPortHandler.isInBoundsX(x))
{
continue
}
if (!viewPortHandler.isInBoundsBottom(y))
{
continue
}
drawValue(context: context,
value: valueText,
xPos: x,
yPos: y + yOffset,
font: valueFont,
align: textAlign,
color: dataSet.valueTextColorAt(j))
}
}
}
}
}
}
}
internal override func passesCheck() -> Bool
{
guard let dataProvider = dataProvider, barData = dataProvider.barData else { return false }
return CGFloat(barData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleY
}
} | mit | 507a3d853900689c11617ea6bb7c84f8 | 41.985106 | 208 | 0.415701 | 7.024339 | false | false | false | false |
zhangliangzhi/iosStudyBySwift | ColorWar/ColorWar/INSPersistentContainer/MyColor.swift | 1 | 2040 | //
// MyColor.swift
// xxword
//
// Created by ZhangLiangZhi on 2017/4/23.
// Copyright © 2017年 xigk. All rights reserved.
//
import Foundation
import UIKit
// 背景1
let BG1_COLOR = UIColor(red: 233/255, green: 228/255, blue: 217/255, alpha: 1)
// 背景2
let BG2_COLOR = UIColor(red: 249/255, green: 247/255, blue: 242/255, alpha: 1)
// 淡蓝1
let BG3_COLOR = UIColor(red: 230/255, green: 245/255, blue: 255/255, alpha: 1)
// 淡蓝2
let BG4_COLOR = UIColor(red: 214/255, green: 238/255, blue: 255/255, alpha: 1)
// 蓝, 标题,导航头部
let BLUE_COLOR = UIColor(red: 55/255, green: 124/255, blue: 185/255, alpha: 1)
// 金
let GOLD_COLOR = UIColor(red: 222/255, green: 155/255, blue: 1/255, alpha: 1)
let TI_COLOR = UIColor(red: 249/255, green: 247/255, blue: 242/255, alpha: 1)
// 首页文字1 大字
let WZ1_COLOR = UIColor(red: 120/255, green: 105/255, blue: 90/255, alpha: 1)
// 首页文字2 小字
let WZ2_COLOR = UIColor(red: 181/255, green: 172/255, blue: 149/255, alpha: 1)
// 成功颜色
let CG_COLOR = UIColor(red: 102/255, green: 184/255, blue: 77/255, alpha: 1)
let INFO_COLOR = UIColor(red: 99/255, green: 191/255, blue: 225/255, alpha: 1) // 青色
let DEF_COLOR = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1) //
let WARN_COLOR = UIColor(red: 238/255, green: 174/255, blue: 56/255, alpha: 1) // 橙色
let DANG_COLOR = UIColor(red: 212/255, green: 84/255, blue: 76/255, alpha: 1) // 红色
// 单词颜色
let WZ4_COLOR = UIColor(red: 150/255, green: 154/255, blue: 153/255, alpha: 1)
let SX1_COLOR = UIColor(red: 218/255, green: 213/255, blue: 203/255, alpha: 1) // 深背景
let SX2_COLOR = UIColor(red: 233/255, green: 228/255, blue: 217/255, alpha: 1) // 浅背景
let SX3_COLOR = UIColor(red: 74/255, green: 85/255, blue: 105/255, alpha: 1) // 单词颜色
let SX4_COLOR = UIColor(red: 144/255, green: 144/255, blue: 144/255, alpha: 1) // 音标颜色,灰
let SX5_COLOR = UIColor(red: 181/255, green: 172/255, blue: 150/255, alpha: 1) // 背景边框的颜色
| mit | fe56d18f7727611636d4e79b9b08de43 | 37.918367 | 90 | 0.657053 | 2.444872 | false | false | false | false |
kkolli/MathGame | client/Speedy/MultiplayerGameViewController.swift | 1 | 14531 | //
// MultiplayerViewController.swift
// Speedy
//
// Created by John Chou on 2/26/15.
// Copyright (c) 2015 Krishna Kolli. All rights reserved.
//
import SpriteKit
import UIKit
import MultipeerConnectivity
import Alamofire
class MultiplayerGameViewController: UIViewController, SKPhysicsContactDelegate {
var timer: Timer!
var countDown = 3
var game_max_time = 60 // TODO - modify this somehow later
var score = 0
var peer_score = 0
var targetNumber: Int?
let TIME_DEBUG = false
var appDelegate:AppDelegate!
var scene: GameScene?
var boardController: BoardController?
var finishedInit: Bool!
var user : FBGraphUser!
var opponentFirstName: String!
var operatorsUsed: [Operator]!
var numTargetNumbersMatched: Int!
@IBOutlet weak var counterTimer: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true
self.tabBarController?.tabBar.hidden = true
println("in multiplayer view controller")
scene = GameScene(size: view.frame.size)
numTargetNumbersMatched = 0
boardController = BoardController(scene: scene!, mode: .MULTI)
boardController!.notifyScoreChanged = notifyScoreChanged
// scene!.boardController = boardController
updateTargetNumber()
operatorsUsed = []
finishedInit = false
// Configure the view.
let skView = self.view as SKView
//skView.showsFPS = true
//skView.showsNodeCount = true
//skView.showsPhysics = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = false
/* Set the scale mode to scale to fit the window */
scene!.scaleMode = .AspectFill
//scene!.scoreHandler = handleMerge
scene!.physicsWorld.contactDelegate = self
// start off frozen
scene!.freezeAction = true
skView.presentScene(scene)
// Do any additional setup after loading the view.
appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
self.user = appDelegate.user
NSNotificationCenter.defaultCenter().addObserver(self, selector: "peerChangedStateWithNotification:", name: "MPC_DidChangeStateNotification", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleReceivedDataWithNotification:", name: "MPC_DidReceiveDataNotification", object: nil)
initialCountDown(String(countDown), changedType: "init_state")
setScoreLabels()
// start the counter to go!
timer = Timer(duration: game_max_time, {(elapsedTime: Int) -> () in
if self.timer.getTime() <= 0 {
// self.GameTimerLabel.text = "done"
self.performSegueToSummary()
} else {
if self.TIME_DEBUG {
println("time printout: " + String(self.timer.getTime()))
}
if self.boardController != nil {
self.boardController?.setTimeInHeader(self.timer.getTime())
}
// self.GameTimerLabel.text = self.timer.convertIntToTime(self.timer.getTime())
}
})
// GameTimerLabel.text = timer.convertIntToTime(self.timer.getTime())
let tracker = GAI.sharedInstance().defaultTracker
tracker.set(kGAIScreenName, value: "multiplayer")
tracker.send(GAIDictionaryBuilder.createScreenView().build())
}
func performSegueToSummary() {
self.performSegueWithIdentifier("multiplayerSegueToSummary", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "multiplayerSegueToSummary" {
println("performing segue to summary inside MC Game")
let vc = segue.destinationViewController as SummaryViewController
vc.operatorsUsed = boardController!.operatorsUsed
vc.score = boardController!.score
vc.numTargetNumbersMatched = numTargetNumbersMatched
}
}
func peerChangedStateWithNotification(notification:NSNotification){
println("PEER CHANGED STATE?!?!")
let userInfo = NSDictionary(dictionary: notification.userInfo!)
let state = userInfo.objectForKey("state") as Int
let otherUserPID = userInfo.objectForKey("peerID") as MCPeerID
if state != MCSessionState.Connecting.rawValue {
// self.navigationItem.title = "Connected"
}
}
func handleReceivedDataWithNotification(notification:NSNotification){
println("received some data with notification!")
let userInfo = notification.userInfo! as Dictionary
let receivedData:NSData = userInfo["data"] as NSData
let message = NSJSONSerialization.JSONObjectWithData(receivedData, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary
let senderPeerId:MCPeerID = userInfo["peerID"] as MCPeerID
let senderDisplayName = senderPeerId.displayName
let msg_type: AnyObject? = message.objectForKey("type")
// let msg_type_init: AnyObject? = message.objectForKey("type_init")
let msg_val: AnyObject? = message.objectForKey("value")
if msg_type?.isEqualToString("score_update") == true {
// if this is a score_update, then unwrap for the score changes to the peer
peer_score = message.objectForKey("score") as Int
println("PEER SCORE IN: \(peer_score)")
setScoreLabels()
}
else if msg_type?.isEqualToString("init_state") == true && !self.finishedInit{
if opponentFirstName == nil {
opponentFirstName = message.objectForKey("first_name") as String
boardController!.setOpponentName(opponentFirstName)
}
//Do everything here for beginning countdown
var recv_counter:Int = msg_val!.integerValue
var old_counter = countDown
println("I just received value: " + String(recv_counter) + " while counter is : " + String(countDown))
if recv_counter > countDown || countDown <= 0 {
if recv_counter == 0 && self.scene!.freezeAction == true {
startGame()
}
return
}
countDown = countDown-1
setScoreLabels()
if recv_counter == 0 {
startGame()
return
}
println("counter is now at: " + String(countDown) + "ready to timeout")
timeoutCtr("timing out initialization at: " + String(msg_val!.integerValue),
resolve: {
println("finished timeout-- counter is at: " + String(self.countDown))
if(self.countDown == 0){
self.initialCountDown(String(self.countDown), changedType: "init_state")
}
else{
self.initialCountDown(String(self.countDown), changedType: "init_state")
}
},
reject: {
// handle errors
})
}
}
func startGame() {
println("about to unfreeze!")
self.timer.start()
//start the game
self.scene!.freezeAction = false
self.countDown = 0
self.initialCountDown(String(self.countDown), changedType: "init_state")
self.finishedInit = true
}
func timeoutCtr(txt: String, resolve: () -> (), reject: () -> ()) {
var delta: Int64 = 1 * Int64(NSEC_PER_SEC)/2
var time = dispatch_time(DISPATCH_TIME_NOW, delta)
dispatch_after(time, dispatch_get_main_queue(), {
println("closures are " + txt)
resolve()
});
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setTargetNumber(num: Int) {
self.targetNumber = num
}
func setScoreLabels() {
boardController!.setOpponentScore(peer_score)
// PeerCurrentScore.text = String(peer_score)
// MyCurrentScore.text = String(score)
if (countDown == 0) {
counterTimer.hidden = true
} else {
counterTimer.text = String(countDown)
}
}
/*
Just update that we've hit a target number
add some time
*/
func updateScoreAndTime() {
// if we've matched one before
println("score changing... with num: \(numTargetNumbersMatched) and old timer: \(timer.getTime())")
if numTargetNumbersMatched > 0 {
timer.addTime(timer.getExtraTimeSub())
} else {
timer.addTime(timer.getExtraTimeFirst())
}
numTargetNumbersMatched!++
println("now score changed... with num: \(numTargetNumbersMatched) and new timer: \(timer.getTime())")
}
func updateTargetNumber(){
if targetNumber != nil{
let numberCircleList = boardController!.gameCircles.filter{$0 is NumberCircle}
let numberList = numberCircleList.map{($0 as NumberCircle).number!}
targetNumber = boardController!.randomNumbers.generateTarget(numberList)
}else{
targetNumber = boardController!.randomNumbers.generateTarget()
}
// GameTargetNumLabel.text = String(targetNumber!)
}
func notifyScoreChanged() {
updateScoreAndTime()
var msg = ["type" : "score_update", "score": boardController!.score]
let messageData = NSJSONSerialization.dataWithJSONObject(msg, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
var error:NSError?
appDelegate.mpcHandler.session.sendData(messageData, toPeers: appDelegate.mpcHandler.session.connectedPeers, withMode: MCSessionSendDataMode.Reliable, error: &error)
println("just sent data: \(messageData)")
if error != nil{
println("error: \(error?.localizedDescription)")
}
}
func initialCountDown(val:String, changedType:String){
println("sending initial count down: " + val + " and name: \(user.first_name)")
var msg = ["value" : val, "type": changedType, "first_name": user.first_name]
let messageData = NSJSONSerialization.dataWithJSONObject(msg, options: NSJSONWritingOptions.PrettyPrinted, error: nil)
var error:NSError?
appDelegate.mpcHandler.session.sendData(messageData, toPeers: appDelegate.mpcHandler.session.connectedPeers, withMode: MCSessionSendDataMode.Reliable, error: &error)
if error != nil{
println("error: \(error?.localizedDescription)")
}
}
func didBeginContact(contact: SKPhysicsContact) {
var numberBody: SKPhysicsBody
var opBody: SKPhysicsBody
//A neccessary check to prevent contacts from throwing runtime errors
if !(contact.bodyA.node != nil && contact.bodyB.node != nil && contact.bodyA.node!.parent != nil && contact.bodyB.node!.parent != nil) {
return
}
if contact.bodyA.node! is NumberCircle{
numberBody = contact.bodyA
if contact.bodyB.node! is OperatorCircle{
opBody = contact.bodyB
let numberNode = numberBody.node! as NumberCircle
let opNode = opBody.node! as OperatorCircle
if !numberNode.hasNeighbor() && !opNode.hasNeighbor() {
if scene!.releaseNumber != nil && scene!.releaseOperator != nil{
println("NO")
return
}
numberNode.setNeighbor(opNode)
opNode.setNeighbor(numberNode)
let joint = scene!.createBestJoint(contact.contactPoint, nodeA: numberNode, nodeB: opNode)
scene!.physicsWorld.addJoint(joint)
scene!.currentJoint = joint
scene!.joinedNodeA = numberNode
scene!.joinedNodeB = opNode
}else{
if let leftNumberCircle = opNode.neighbor as? NumberCircle {
let opCircle = opNode
boardController!.handleMerge(leftNumberCircle, rightNumberCircle: numberNode, opCircle: opCircle)
}
}
}else{
return
}
}else if contact.bodyA.node! is OperatorCircle{
opBody = contact.bodyA
if contact.bodyB.node! is NumberCircle{
numberBody = contact.bodyB
let numberNode = numberBody.node! as NumberCircle
let opNode = opBody.node! as OperatorCircle
// all nodes touching together have no neighbors (1st contact)
if numberNode.hasNeighbor() == false && opNode.hasNeighbor() == false{
if scene!.releaseNumber != nil && scene!.releaseOperator != nil{
return
}
numberNode.setNeighbor(opNode)
opNode.setNeighbor(numberNode)
let joint = scene!.createBestJoint(contact.contactPoint, nodeA: numberNode, nodeB: opNode)
scene!.physicsWorld.addJoint(joint)
scene!.currentJoint = joint
scene!.joinedNodeA = numberNode
scene!.joinedNodeB = opNode
}else{
// if hitting all 3
if let leftNumberCircle = opNode.neighbor as? NumberCircle {
let opCircle = opNode
boardController!.handleMerge(leftNumberCircle, rightNumberCircle: numberNode, opCircle: opCircle)
}
}
}else{
return
}
}
}
}
| gpl-2.0 | a243a3ab22ef71d61693419fa008b7ad | 39.589385 | 173 | 0.583855 | 5.143717 | false | false | false | false |
ytbryan/swiftknife | project/project/MasterViewController.swift | 1 | 9472 | //
// MasterViewController.swift
// project
//
// Created by Bryan Lim on 10/22/14.
// Copyright (c) 2014 TADA. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
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: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name, inManagedObjectContext: context) as NSManagedObject
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate.date(), forKey: "timeStamp")
// Save the context.
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
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 self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
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 {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject)
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
cell.textLabel?.text = object.valueForKey("timeStamp")!.description
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath)!, atIndexPath: indexPath)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| mit | c29c62a30156154d1eb8a7dfad60b543 | 45.660099 | 360 | 0.691723 | 6.239789 | false | false | false | false |
turingcorp/gattaca | gattaca/Controller/Abstract/ControllerParent.swift | 1 | 715 | import UIKit
class ControllerParent:UIViewController
{
var orientation:UIInterfaceOrientationMask
let menu:MMenu
let session:MSession
init()
{
session = MSession()
menu = MMenu()
orientation = UIInterfaceOrientationMask.portrait
super.init(nibName:nil, bundle:nil)
}
required init?(coder:NSCoder)
{
return nil
}
override func viewDidLoad()
{
super.viewDidLoad()
let controller:CHome = CHome(session:session)
mainController(controller:controller)
}
override func loadView()
{
let viewParent:ViewParent = ViewParent(controller:self)
view = viewParent
}
}
| mit | aec44f10b24eb2a9102eb513b6c5ca7f | 19.428571 | 63 | 0.61958 | 4.931034 | false | false | false | false |
FreshLeaf8865/GoMap-Custom-Keyboard | Keyboard/Custom Views/Buttons/CharacterButton.swift | 1 | 4857 | //
// CharacterButton.swift
// ELDeveloperKeyboard
//
// Created by Eric Lin on 2014-07-02.
// Copyright (c) 2014 Eric Lin. All rights reserved.
//
import Foundation
import UIKit
/**
The methods declared in the CharacterButtonDelegate protocol allow the adopting delegate to respond to messages from the CharacterButton class, handling button presses and swipes.
*/
protocol CharacterButtonDelegate: class {
/**
Respond to the CharacterButton being pressed.
- parameter button: The CharacterButton that was pressed.
*/
func handlePressForCharacterButton(button: CharacterButton)
/**
Respond to the CharacterButton being up-swiped.
- parameter button: The CharacterButton that was up-swiped.
*/
func handleSwipeUpForButton(button: CharacterButton)
/**
Respond to the CharacterButton being down-swiped.
- parameter button: The CharacterButton that was down-swiped.
*/
func handleSwipeDownForButton(button: CharacterButton)
}
/**
CharacterButton is a KeyButton subclass associated with three characters (primary, secondary, and tertiary) as well as three gestures (press, swipe up, and swipe down).
*/
class CharacterButton: KeyButton {
// MARK: Properties
weak var delegate: CharacterButtonDelegate?
var primaryCharacter: String {
didSet {
if primaryLabel != nil {
primaryLabel.text = primaryCharacter
}
}
}
var secondaryCharacter: String {
didSet {
if secondaryLabel != nil {
secondaryLabel.text = secondaryCharacter
}
}
}
var tertiaryCharacter: String {
didSet {
if tertiaryLabel != nil {
tertiaryLabel.text = tertiaryCharacter
}
}
}
private(set) var primaryLabel: UILabel!
private(set) var secondaryLabel: UILabel!
private(set) var tertiaryLabel: UILabel!
// MARK: Constructors
init(frame: CGRect, primaryCharacter: String, secondaryCharacter: String, tertiaryCharacter: String, delegate: CharacterButtonDelegate?) {
self.primaryCharacter = primaryCharacter
self.secondaryCharacter = secondaryCharacter
self.tertiaryCharacter = tertiaryCharacter
self.delegate = delegate
super.init(frame: frame)
primaryLabel = UILabel(frame: CGRectMake(frame.width * 0.45, 0.0, 60 , frame.height ))
primaryLabel.font = UIFont(name: "HelveticaNeue", size: 20.0)
primaryLabel.textColor = UIColor(white: 0, alpha: 1.0)
primaryLabel.textAlignment = .Center
primaryLabel.text = primaryCharacter
addSubview(primaryLabel)
secondaryLabel = UILabel(frame: CGRectMake(0.0, 0.0, frame.width * 0.9, frame.height * 0.3))
secondaryLabel.font = UIFont(name: "HelveticaNeue", size: 12.0)
secondaryLabel.adjustsFontSizeToFitWidth = true
secondaryLabel.textColor = UIColor(white: 187.0/255, alpha: 1.0)
secondaryLabel.textAlignment = .Right
secondaryLabel.text = secondaryCharacter
//addSubview(secondaryLabel)
tertiaryLabel = UILabel(frame: CGRectMake(0.0, frame.height * 0.65, frame.width * 0.9, frame.height * 0.25))
tertiaryLabel.font = UIFont(name: "HelveticaNeue", size: 12.0)
tertiaryLabel.textColor = UIColor(white: 187.0/255, alpha: 1.0)
tertiaryLabel.adjustsFontSizeToFitWidth = true
tertiaryLabel.textAlignment = .Right
tertiaryLabel.text = tertiaryCharacter
//addSubview(tertiaryLabel)
addTarget(self, action: #selector(CharacterButton.buttonPressed(_:)), forControlEvents: .TouchUpInside)
let swipeUpGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(CharacterButton.buttonSwipedUp(_:)))
swipeUpGestureRecognizer.direction = .Up
addGestureRecognizer(swipeUpGestureRecognizer)
let swipeDownGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(CharacterButton.buttonSwipedDown(_:)))
swipeDownGestureRecognizer.direction = .Down
addGestureRecognizer(swipeDownGestureRecognizer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Event handlers
func buttonPressed(sender: KeyButton) {
delegate?.handlePressForCharacterButton(self)
}
func buttonSwipedUp(swipeUpGestureRecognizer: UISwipeGestureRecognizer) {
delegate?.handleSwipeUpForButton(self)
}
func buttonSwipedDown(swipeDownGestureRecognizer: UISwipeGestureRecognizer) {
delegate?.handleSwipeDownForButton(self)
}
} | apache-2.0 | 3274e5f4b60f1870d1343260bc08bcef | 34.985185 | 183 | 0.668931 | 5.048857 | false | false | false | false |
KyoheiG3/Keynode | KeynodeExample/KeynodeExample/ViewController.swift | 1 | 2025 | //
// ViewController.swift
// KeynodeExample
//
// Created by Kyohei Ito on 2014/12/11.
// Copyright (c) 2014年 kyohei_ito. All rights reserved.
//
import UIKit
import Keynode
class ViewController: UIViewController, Keynode.ControllerDelegate {
let tableSourceList: [[String]] = [[Int](0..<20).map{ "cell \($0)" }]
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var toolbar: UIView!
@IBOutlet weak var toolbarBottomSpaceConstraint: NSLayoutConstraint!
lazy var keynode: Controller = Controller(view: self.tableView)
override func viewDidLoad() {
super.viewDidLoad()
keynode.defaultInsetBottom = toolbar.bounds.height
keynode.willAnimationHandler = { [weak self] show, keyboardRect in
if let me = self {
me.toolbarBottomSpaceConstraint.constant = show ? keyboardRect.size.height : 0
}
}
keynode.animationsHandler = { [weak self] show, keyboardRect in
if let me = self {
me.toolbarBottomSpaceConstraint.constant = me.view.bounds.height - keyboardRect.origin.y
me.view.layoutIfNeeded()
}
}
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return tableSourceList.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableSourceList[section].count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = tableSourceList[indexPath.section][indexPath.row]
return cell
}
} | mit | 219329c8132dd2117649232267b9ebcb | 34.508772 | 142 | 0.674246 | 5.095718 | false | false | false | false |
tlax/looper | looper/View/Camera/More/VCameraMoreCellInfo.swift | 1 | 1222 | import UIKit
class VCameraMoreCellInfo:VCameraMoreCell
{
private weak var label:UILabel!
private let kMarginHorizontal:CGFloat = 10
override init(frame:CGRect)
{
super.init(frame:frame)
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
self.label = label
addSubview(label)
NSLayoutConstraint.equalsVertical(
view:label,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self,
margin:kMarginHorizontal)
}
required init?(coder:NSCoder)
{
return nil
}
override func config(controller:CCameraMore, model:MCameraMoreItem)
{
super.config(controller:controller, model:model)
guard
let modelInfo:MCameraMoreItemInfo = model as? MCameraMoreItemInfo
else
{
return
}
label.attributedText = modelInfo.attributedString
}
}
| mit | a31aa8c8c5adff8edbcb9325e1ca0144 | 23.44 | 77 | 0.594926 | 5.631336 | false | false | false | false |
silence0201/Swift-Study | Note/Day 02/04-元组的使用.playground/Contents.swift | 1 | 865 | //: Playground - noun: a place where people can play
import UIKit
// why 18 1.88
// 1.使用数组保存信息
let infoArray : [Any] = ["why", 18, 1.88]
let arrayName = infoArray[0] as! String
print(arrayName.characters.count)
// 2.使用字典保存信息
let infoDict : [String : Any] = ["name" : "why", "age" : 18, "height" : 1.88]
let dictName = infoDict["name"] as! String
print(dictName.characters.count)
// 3.使用元组保存信息(取出数据时,更加方便)
// 3.1.写法一:
let infoTuple0 = ("why", 18, 1.88)
let tupleName = infoTuple0.0
let tupleAge = infoTuple0.1
print(tupleName.characters.count)
infoTuple0.0
infoTuple0.1
infoTuple0.2
// 3.2.写法二:
let infoTuple1 = (name : "why",age : 18, height : 1.88)
infoTuple1.age
infoTuple1.name
infoTuple1.height
// 3.3.写法三:
let (name, age, height) = ("why", 18, 1.88)
name
age
height | mit | 2189cc2da4636ce8e2efbf85f5d0ff97 | 18.073171 | 77 | 0.681178 | 2.535714 | false | false | false | false |
jjatie/Charts | ChartsDemo-iOS/Swift/Demos/MultipleLinesChartViewController.swift | 1 | 4293 | //
// MultipleLinesChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import Charts
class MultipleLinesChartViewController: DemoBaseViewController {
@IBOutlet var chartView: LineChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Multiple Lines Chart"
options = [.toggleValues,
.toggleFilled,
.toggleCircles,
.toggleCubic,
.toggleStepped,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData]
chartView.delegate = self
chartView.chartDescription.isEnabled = false
chartView.leftAxis.isEnabled = false
chartView.rightAxis.drawAxisLineEnabled = false
chartView.xAxis.drawAxisLineEnabled = false
chartView.isDrawBordersEnabled = false
chartView.setScaleEnabled(true)
let l = chartView.legend
l.horizontalAlignment = .right
l.verticalAlignment = .top
l.orientation = .vertical
l.drawInside = false
// chartView.legend = l
sliderX.value = 20
sliderY.value = 100
slidersValueChanged(nil)
}
override func updateChartData() {
if shouldHideData {
chartView.data = nil
return
}
setDataCount(Int(sliderX.value), range: UInt32(sliderY.value))
}
// TODO: Refine data creation
func setDataCount(_ count: Int, range: UInt32) {
let colors = ChartColorTemplates.vordiplom[0 ... 2]
let block: (Int) -> ChartDataEntry = { (i) -> ChartDataEntry in
let val = Double(arc4random_uniform(range) + 3)
return ChartDataEntry(x: Double(i), y: val)
}
let dataSets = (0 ..< 3).map { i -> LineChartDataSet in
let yVals = (0 ..< count).map(block)
let set = LineChartDataSet(entries: yVals, label: "DataSet \(i)")
set.lineWidth = 2.5
set.circleRadius = 4
set.circleHoleRadius = 2
let color = colors[i % colors.count]
set.setColor(color)
set.setCircleColor(color)
return set
}
dataSets[0].lineDashLengths = [5, 5]
dataSets[0].colors = ChartColorTemplates.vordiplom
dataSets[0].circleColors = ChartColorTemplates.vordiplom
let data = LineChartData(dataSets: dataSets)
data.setValueFont(.systemFont(ofSize: 7, weight: .light))
chartView.data = data
}
override func optionTapped(_ option: Option) {
guard let data = chartView.data else { return }
switch option {
case .toggleFilled:
for case let set as LineChartDataSet in data {
set.isDrawFilledEnabled.toggle()
}
chartView.setNeedsDisplay()
case .toggleCircles:
for case let set as LineChartDataSet in data {
set.isDrawCirclesEnabled.toggle()
}
chartView.setNeedsDisplay()
case .toggleCubic:
for case let set as LineChartDataSet in data {
set.mode = (set.mode == .cubicBezier) ? .linear : .cubicBezier
}
chartView.setNeedsDisplay()
case .toggleStepped:
for case let set as LineChartDataSet in data {
set.mode = (set.mode == .stepped) ? .linear : .stepped
}
chartView.setNeedsDisplay()
default:
super.handleOption(option, forChartView: chartView)
}
}
@IBAction func slidersValueChanged(_: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
updateChartData()
}
}
| apache-2.0 | 5890133422d07d2e41c8b6dac32b6c22 | 29.439716 | 78 | 0.578751 | 5.008168 | false | false | false | false |
jeesmon/varamozhi-ios | varamozhi/Shapes.swift | 1 | 14132 | //
// Shapes.swift
// TastyImitationKeyboard
//
// Created by Alexei Baboulevitch on 10/5/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
// TODO: these shapes were traced and as such are erratic and inaccurate; should redo as SVG or PDF
///////////////////
// SHAPE OBJECTS //
///////////////////
class BackspaceShape: Shape {
override func drawCall(_ color: UIColor) {
drawBackspace(self.bounds, color: color)
}
}
class ShiftShape: Shape {
var withLock: Bool = false {
didSet {
self.overflowCanvas.setNeedsDisplay()
}
}
override func drawCall(_ color: UIColor) {
drawShift(self.bounds, color: color, withRect: self.withLock)
}
}
class GlobeShape: Shape {
override func drawCall(_ color: UIColor) {
drawGlobe(self.bounds, color: color)
}
}
class Shape: UIView {
var color: UIColor? {
didSet {
if let _ = self.color {
self.overflowCanvas.setNeedsDisplay()
}
}
}
// in case shapes draw out of bounds, we still want them to show
var overflowCanvas: OverflowCanvas!
convenience init() {
self.init(frame: CGRect.zero)
}
override required init(frame: CGRect) {
super.init(frame: frame)
self.isOpaque = false
self.clipsToBounds = false
self.overflowCanvas = OverflowCanvas(shape: self)
self.addSubview(self.overflowCanvas)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var oldBounds: CGRect?
override func layoutSubviews() {
if self.bounds.width == 0 || self.bounds.height == 0 {
return
}
if oldBounds != nil && self.bounds.equalTo(oldBounds!) {
return
}
oldBounds = self.bounds
super.layoutSubviews()
let overflowCanvasSizeRatio = CGFloat(1.25)
let overflowCanvasSize = CGSize(width: self.bounds.width * overflowCanvasSizeRatio, height: self.bounds.height * overflowCanvasSizeRatio)
self.overflowCanvas.frame = CGRect(
x: CGFloat((self.bounds.width - overflowCanvasSize.width) / 2.0),
y: CGFloat((self.bounds.height - overflowCanvasSize.height) / 2.0),
width: overflowCanvasSize.width,
height: overflowCanvasSize.height)
self.overflowCanvas.setNeedsDisplay()
}
func drawCall(_ color: UIColor) { /* override me! */ }
class OverflowCanvas: UIView {
// TODO: retain cycle? does swift even have those?
unowned var shape: Shape
init(shape: Shape) {
self.shape = shape
super.init(frame: CGRect.zero)
self.isOpaque = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
_ = CGColorSpaceCreateDeviceRGB()
ctx?.saveGState()
let xOffset = (self.bounds.width - self.shape.bounds.width) / CGFloat(2)
let yOffset = (self.bounds.height - self.shape.bounds.height) / CGFloat(2)
ctx?.translateBy(x: xOffset, y: yOffset)
self.shape.drawCall(shape.color != nil ? shape.color! : UIColor.black)
ctx?.restoreGState()
}
}
}
/////////////////////
// SHAPE FUNCTIONS //
/////////////////////
func getFactors(_ fromSize: CGSize, toRect: CGRect) -> (xScalingFactor: CGFloat, yScalingFactor: CGFloat, lineWidthScalingFactor: CGFloat, fillIsHorizontal: Bool, offset: CGFloat) {
let xSize = { () -> CGFloat in
let scaledSize = (fromSize.width / CGFloat(2))
if scaledSize > toRect.width {
return (toRect.width / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
let ySize = { () -> CGFloat in
let scaledSize = (fromSize.height / CGFloat(2))
if scaledSize > toRect.height {
return (toRect.height / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
let actualSize = min(xSize, ySize)
return (actualSize, actualSize, actualSize, false, 0)
}
func centerShape(_ fromSize: CGSize, toRect: CGRect) {
let xOffset = (toRect.width - fromSize.width) / CGFloat(2)
let yOffset = (toRect.height - fromSize.height) / CGFloat(2)
let ctx = UIGraphicsGetCurrentContext()
ctx?.saveGState()
ctx?.translateBy(x: xOffset, y: yOffset)
}
func endCenter() {
let ctx = UIGraphicsGetCurrentContext()
ctx?.restoreGState()
}
func drawBackspace(_ bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSize(width: 44, height: 32), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSize(width: 44 * xScalingFactor, height: 32 * yScalingFactor), toRect: bounds)
//// Color Declarations
let color = color
let color2 = UIColor.gray // TODO:
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 44 * xScalingFactor, y: 26 * yScalingFactor), controlPoint1: CGPoint(x: 38 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor), controlPoint1: CGPoint(x: 44 * xScalingFactor, y: 22 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 36 * xScalingFactor, y: 0 * yScalingFactor), controlPoint1: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 0 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 16 * xScalingFactor, y: 0 * yScalingFactor), controlPoint1: CGPoint(x: 32 * xScalingFactor, y: 0 * yScalingFactor), controlPoint2: CGPoint(x: 16 * xScalingFactor, y: 0 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.close()
color.setFill()
bezierPath.fill()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 20 * xScalingFactor, y: 10 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 34 * xScalingFactor, y: 22 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 10 * yScalingFactor))
bezier2Path.close()
UIColor.gray.setFill()
bezier2Path.fill()
color2.setStroke()
bezier2Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 20 * xScalingFactor, y: 22 * yScalingFactor))
bezier3Path.addLine(to: CGPoint(x: 34 * xScalingFactor, y: 10 * yScalingFactor))
bezier3Path.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 22 * yScalingFactor))
bezier3Path.close()
UIColor.red.setFill()
bezier3Path.fill()
color2.setStroke()
bezier3Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier3Path.stroke()
endCenter()
}
func drawShift(_ bounds: CGRect, color: UIColor, withRect: Bool) {
let factors = getFactors(CGSize(width: 38, height: (withRect ? 34 + 4 : 32)), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
_ = factors.lineWidthScalingFactor
centerShape(CGSize(width: 38 * xScalingFactor, height: (withRect ? 34 + 4 : 32) * yScalingFactor), toRect: bounds)
//// Color Declarations
let color2 = color
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 19 * xScalingFactor, y: 0 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 10 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 10 * xScalingFactor, y: 28 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 14 * xScalingFactor, y: 32 * yScalingFactor), controlPoint1: CGPoint(x: 10 * xScalingFactor, y: 28 * yScalingFactor), controlPoint2: CGPoint(x: 10 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor), controlPoint1: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 28 * xScalingFactor, y: 28 * yScalingFactor), controlPoint1: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 28 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor), controlPoint1: CGPoint(x: 28 * xScalingFactor, y: 26 * yScalingFactor), controlPoint2: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.close()
color2.setFill()
bezierPath.fill()
if withRect {
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRect(x: 10 * xScalingFactor, y: 34 * yScalingFactor, width: 18 * xScalingFactor, height: 4 * yScalingFactor))
color2.setFill()
rectanglePath.fill()
}
endCenter()
}
func drawGlobe(_ bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSize(width: 41, height: 40), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSize(width: 41 * xScalingFactor, height: 40 * yScalingFactor), toRect: bounds)
//// Color Declarations
let color = color
//// Oval Drawing
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 0 * xScalingFactor, y: 0 * yScalingFactor, width: 40 * xScalingFactor, height: 40 * yScalingFactor))
color.setStroke()
ovalPath.lineWidth = 1 * lineWidthScalingFactor
ovalPath.stroke()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 20 * xScalingFactor, y: -0 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 40 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 20 * xScalingFactor, y: -0 * yScalingFactor))
bezierPath.close()
color.setStroke()
bezierPath.lineWidth = 1 * lineWidthScalingFactor
bezierPath.stroke()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 0.5 * xScalingFactor, y: 19.5 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 39.5 * xScalingFactor, y: 19.5 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 0.5 * xScalingFactor, y: 19.5 * yScalingFactor))
bezier2Path.close()
color.setStroke()
bezier2Path.lineWidth = 1 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 21.63 * xScalingFactor, y: 0.42 * yScalingFactor))
bezier3Path.addCurve(to: CGPoint(x: 21.63 * xScalingFactor, y: 39.6 * yScalingFactor), controlPoint1: CGPoint(x: 21.63 * xScalingFactor, y: 0.42 * yScalingFactor), controlPoint2: CGPoint(x: 41 * xScalingFactor, y: 19 * yScalingFactor))
bezier3Path.lineCapStyle = CGLineCap.round;
color.setStroke()
bezier3Path.lineWidth = 1 * lineWidthScalingFactor
bezier3Path.stroke()
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.move(to: CGPoint(x: 17.76 * xScalingFactor, y: 0.74 * yScalingFactor))
bezier4Path.addCurve(to: CGPoint(x: 18.72 * xScalingFactor, y: 39.6 * yScalingFactor), controlPoint1: CGPoint(x: 17.76 * xScalingFactor, y: 0.74 * yScalingFactor), controlPoint2: CGPoint(x: -2.5 * xScalingFactor, y: 19.04 * yScalingFactor))
bezier4Path.lineCapStyle = CGLineCap.round;
color.setStroke()
bezier4Path.lineWidth = 1 * lineWidthScalingFactor
bezier4Path.stroke()
//// Bezier 5 Drawing
let bezier5Path = UIBezierPath()
bezier5Path.move(to: CGPoint(x: 6 * xScalingFactor, y: 7 * yScalingFactor))
bezier5Path.addCurve(to: CGPoint(x: 34 * xScalingFactor, y: 7 * yScalingFactor), controlPoint1: CGPoint(x: 6 * xScalingFactor, y: 7 * yScalingFactor), controlPoint2: CGPoint(x: 19 * xScalingFactor, y: 21 * yScalingFactor))
bezier5Path.lineCapStyle = CGLineCap.round;
color.setStroke()
bezier5Path.lineWidth = 1 * lineWidthScalingFactor
bezier5Path.stroke()
//// Bezier 6 Drawing
let bezier6Path = UIBezierPath()
bezier6Path.move(to: CGPoint(x: 6 * xScalingFactor, y: 33 * yScalingFactor))
bezier6Path.addCurve(to: CGPoint(x: 34 * xScalingFactor, y: 33 * yScalingFactor), controlPoint1: CGPoint(x: 6 * xScalingFactor, y: 33 * yScalingFactor), controlPoint2: CGPoint(x: 19 * xScalingFactor, y: 22 * yScalingFactor))
bezier6Path.lineCapStyle = CGLineCap.round;
color.setStroke()
bezier6Path.lineWidth = 1 * lineWidthScalingFactor
bezier6Path.stroke()
endCenter()
}
| gpl-2.0 | 7a019f618001f935441817021019e479 | 38.696629 | 244 | 0.654755 | 3.906025 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Sources/FeatureKYCUI/Views/ValidationFields/ValidationPickerField/ValidationPickerField.swift | 1 | 3139 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import UIKit
/// `ValidationPickerField` is a `ValidationTextField`
/// that presents a `UIPickerPicker` of `PickerItem`s instead of a keyboard.
/// At the moment, the picker only shows one component and the options passed in `options`
class ValidationPickerField: ValidationTextField, UIPickerViewDataSource, UIPickerViewDelegate {
struct PickerItem: Equatable, Identifiable {
let id: String
let title: String
}
private lazy var pickerView: UIPickerView = {
var picker = UIPickerView()
picker.sizeToFit()
return picker
}()
var onSelection: ((PickerItem?) -> Void)?
var options: [PickerItem] = [] {
didSet {
guard options != oldValue else {
return
}
pickerView.reloadAllComponents()
}
}
var selectedOption: PickerItem? {
didSet {
guard selectedOption != oldValue else {
return
}
if let newValue = selectedOption, let index = options.lastIndex(of: newValue) {
pickerView.selectRow(index, inComponent: 0, animated: false)
pickerView.delegate?.pickerView?(pickerView, didSelectRow: index, inComponent: 0)
}
text = selectedOption?.title
onSelection?(selectedOption)
}
}
override func awakeFromNib() {
super.awakeFromNib()
pickerView.delegate = self
pickerView.reloadAllComponents()
textFieldInputView = pickerView
validationBlock = { [weak self] _ in
guard let self = self else { return .invalid(.unknown) }
let hasValidData = !self.options.isEmpty && self.selectedOption != nil
let isOptional = self.optionalField
let isValid = hasValidData || isOptional
return isValid ? .valid : .invalid(.invalidSelection)
}
}
// UITextFieldDelegate
override func textFieldDidEndEditing(_ textField: UITextField) {
super.textFieldDidEndEditing(textField)
pickerView.isHidden = true
}
override func textFieldDidBeginEditing(_ textField: UITextField) {
super.textFieldDidBeginEditing(textField)
pickerView.isHidden = false
selectedOption = selectedOption ?? options.first
}
override func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
false
}
// UIPickerViewDataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
options.count
}
// UIPickerViewDelegate
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedOption = options[row]
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
options[row].title
}
}
| lgpl-3.0 | 73fc6f73be18bb91771140a546d23a0c | 30.38 | 111 | 0.634799 | 5.54417 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainNamespace/Sources/BlockchainNamespace/Tag/Tag+Error.swift | 1 | 1251 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
extension Tag {
public struct Error: Swift.Error, CustomStringConvertible, CustomDebugStringConvertible, LocalizedError {
let event: Tag.Event
let context: Tag.Context
let message: String
let file: String, line: Int
init(
event: Tag.Event,
context: Tag.Context = [:],
message: @autoclosure () -> String = "",
_ file: String = #fileID,
_ line: Int = #line
) {
self.event = event
self.context = context
self.message = message()
self.file = file
self.line = line
}
public var description: String { message }
public var errorDescription: String? { message }
public var debugDescription: String {
"\(file):\(line) \(event): \(message)"
}
}
}
extension Tag.Event {
public func error(
message: @autoclosure () -> String = "",
context: Tag.Context = [:],
file: String = #fileID,
line: Int = #line
) -> Tag.Error {
.init(event: self, context: context, message: message(), file, line)
}
}
| lgpl-3.0 | 896b9e78cfca32410a9747316df78bdf | 25.041667 | 109 | 0.5424 | 4.681648 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureDashboard/Sources/FeatureDashboardUI/Components/FiatCustodialBalanceView/FiatCustodialBalanceViewPresenter.swift | 1 | 5902 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import MoneyKit
import PlatformKit
import PlatformUIKit
import RxCocoa
import RxSwift
final class FiatCustodialBalanceViewPresenter: Equatable {
// MARK: - Types
enum PresentationStyle {
case border
case plain
}
struct Descriptors {
let currencyNameFont: UIFont
let currencyNameFontColor: UIColor
let currencyNameAccessibilityId: Accessibility
let currencyCodeFont: UIFont
let currencyCodeFontColor: UIColor
let currencyCodeAccessibilityId: Accessibility
let badgeImageAccessibilitySuffix: String
let balanceViewDescriptors: FiatBalanceViewAsset.Value.Presentation.Descriptors
}
/// Emits tap events
var tap: Signal<Void> {
tapRelay.asSignal()
}
let fiatBalanceViewPresenter: FiatBalanceViewPresenter
/// The badge showing the currency symbol
var badgeImageViewModel: Driver<BadgeImageViewModel> {
badgeRelay.asDriver()
}
/// The name of the currency showed in the balance
var currencyName: Driver<LabelContent> {
currencyNameRelay.asDriver()
}
/// The currency code of the currency showed in the balance
var currencyCode: Driver<LabelContent> {
currencyCodeRelay.asDriver()
}
var currencyType: CurrencyType {
interactor.currencyType
}
let tapRelay = PublishRelay<Void>()
let respondsToTaps: Bool
let presentationStyle: PresentationStyle
private let badgeRelay = BehaviorRelay<BadgeImageViewModel>(value: .empty)
private let currencyNameRelay = BehaviorRelay<LabelContent>(value: .empty)
private let currencyCodeRelay = BehaviorRelay<LabelContent>(value: .empty)
private let interactor: FiatCustodialBalanceViewInteractor
private let disposeBag = DisposeBag()
init(
interactor: FiatCustodialBalanceViewInteractor,
descriptors: Descriptors,
respondsToTaps: Bool,
presentationStyle: PresentationStyle
) {
self.interactor = interactor
self.respondsToTaps = respondsToTaps
self.presentationStyle = presentationStyle
fiatBalanceViewPresenter = FiatBalanceViewPresenter(
interactor: interactor.balanceViewInteractor,
descriptors: descriptors.balanceViewDescriptors
)
interactor
.fiatCurrency
.map { currency in
.primary(
image: currency.logoResource,
contentColor: .white,
backgroundColor: currency.brandColor,
cornerRadius: .roundedHigh,
accessibilityIdSuffix: descriptors.badgeImageAccessibilitySuffix
)
}
.bindAndCatch(to: badgeRelay)
.disposed(by: disposeBag)
interactor
.fiatCurrency
.map(\.code)
.map {
.init(
text: $0,
font: descriptors.currencyCodeFont,
color: descriptors.currencyCodeFontColor,
accessibility: descriptors.currencyCodeAccessibilityId
)
}
.bindAndCatch(to: currencyCodeRelay)
.disposed(by: disposeBag)
interactor
.fiatCurrency
.map(\.name)
.map {
.init(
text: $0,
font: descriptors.currencyNameFont,
color: descriptors.currencyNameFontColor,
accessibility: descriptors.currencyNameAccessibilityId
)
}
.bindAndCatch(to: currencyNameRelay)
.disposed(by: disposeBag)
}
}
extension FiatCustodialBalanceViewPresenter {
static func == (lhs: FiatCustodialBalanceViewPresenter, rhs: FiatCustodialBalanceViewPresenter) -> Bool {
lhs.interactor == rhs.interactor
}
}
extension FiatCustodialBalanceViewPresenter.Descriptors {
typealias Descriptors = FiatCustodialBalanceViewPresenter.Descriptors
typealias DashboardAccessibility = Accessibility.Identifier.Dashboard.FiatCustodialCell
static func dashboard(
baseAccessibilitySuffix: String = "",
quoteAccessibilitySuffix: String = ""
) -> Descriptors {
Descriptors(
currencyNameFont: .main(.semibold, 20.0),
currencyNameFontColor: .textFieldText,
currencyNameAccessibilityId: .id(DashboardAccessibility.currencyName),
currencyCodeFont: .main(.medium, 14.0),
currencyCodeFontColor: .descriptionText,
currencyCodeAccessibilityId: .id(DashboardAccessibility.currencyCode),
badgeImageAccessibilitySuffix: DashboardAccessibility.currencyBadgeView,
balanceViewDescriptors: .dashboard(
baseAccessibilitySuffix: baseAccessibilitySuffix,
quoteAccessibilitySuffix: quoteAccessibilitySuffix
)
)
}
static func paymentMethods(
baseAccessibilitySuffix: String = "",
quoteAccessibilitySuffix: String = ""
) -> Descriptors {
Descriptors(
currencyNameFont: .main(.semibold, 16),
currencyNameFontColor: .textFieldText,
currencyNameAccessibilityId: .id(DashboardAccessibility.currencyName),
currencyCodeFont: .main(.medium, 14),
currencyCodeFontColor: .descriptionText,
currencyCodeAccessibilityId: .id(DashboardAccessibility.currencyCode),
badgeImageAccessibilitySuffix: DashboardAccessibility.currencyBadgeView,
balanceViewDescriptors: .paymentMethods(
baseAccessibilitySuffix: baseAccessibilitySuffix,
quoteAccessibilitySuffix: quoteAccessibilitySuffix
)
)
}
}
| lgpl-3.0 | a7def710cd97c884bd23f60ecf583e20 | 33.711765 | 109 | 0.647687 | 5.912826 | false | false | false | false |
aleffert/dials | Desktop/Source/Broadcaster.swift | 1 | 1024 | //
// Broadcaster.swift
// Dials-Desktop
//
// Created by Akiva Leffert on 12/7/14.
//
//
import Cocoa
/// Just a block + equality
class Listener<A> {
let block : (A) -> Void
init(_ block : @escaping (A) -> Void) {
self.block = block
}
fileprivate func call(_ o : A) {
block(o)
}
}
class Broadcaster<A> {
private var listeners : [Listener<A>] = []
@discardableResult func addListener(_ owner : AnyObject? = nil, f : @escaping (A) -> Void) -> Listener<A> {
let l = Listener(f)
listeners.append(l)
let _ = owner?.dls_performAction(onDealloc: {[weak self] in
self?.removeListener(l)
return
})
return l
}
func removeListener(_ l : Listener<A>) {
listeners = listeners.filter { g in
return l === g
}
}
func notifyListeners(_ object : A) {
for listener in listeners {
listener.call(object)
}
}
}
| mit | 7741963c17acb913e717e6520598dcec | 19.078431 | 111 | 0.512695 | 3.893536 | false | false | false | false |
wilfreddekok/Antidote | Antidote/ChatIncomingCallCell.swift | 1 | 2565 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import SnapKit
private struct Constants {
static let LeftOffset = 20.0
static let ImageViewToLabelOffset = 5.0
static let ImageViewYOffset = -1.0
static let VerticalOffset = 8.0
}
class ChatIncomingCallCell: ChatMovableDateCell {
private var callImageView: UIImageView!
private var label: UILabel!
override func setupWithTheme(theme: Theme, model: BaseCellModel) {
super.setupWithTheme(theme, model: model)
guard let incomingModel = model as? ChatIncomingCallCellModel else {
assert(false, "Wrong model \(model) passed to cell \(self)")
return
}
label.textColor = theme.colorForType(.ChatListCellMessage)
callImageView.tintColor = theme.colorForType(.LinkText)
if incomingModel.answered {
label.text = String(localized: "chat_call_message") + String(timeInterval: incomingModel.callDuration)
}
else {
label.text = String(localized: "chat_missed_call_message")
}
}
override func createViews() {
super.createViews()
let image = UIImage.templateNamed("start-call-small")
callImageView = UIImageView(image: image)
contentView.addSubview(callImageView)
label = UILabel()
label.font = UIFont.antidoteFontWithSize(16.0, weight: .Light)
contentView.addSubview(label)
}
override func installConstraints() {
super.installConstraints()
callImageView.snp_makeConstraints {
$0.centerY.equalTo(label).offset(Constants.ImageViewYOffset)
$0.leading.equalTo(contentView).offset(Constants.LeftOffset)
}
label.snp_makeConstraints {
$0.top.equalTo(contentView).offset(Constants.VerticalOffset)
$0.bottom.equalTo(contentView).offset(-Constants.VerticalOffset)
$0.leading.equalTo(callImageView.snp_trailing).offset(Constants.ImageViewToLabelOffset)
}
}
}
// Accessibility
extension ChatIncomingCallCell {
override var accessibilityLabel: String? {
get {
return label.text
}
set {}
}
}
// ChatEditable
extension ChatIncomingCallCell {
override func shouldShowMenu() -> Bool {
return true
}
override func menuTargetRect() -> CGRect {
return label.frame
}
}
| mpl-2.0 | 1d76ca40c005d41c7bdf4558b43840d1 | 28.825581 | 114 | 0.660819 | 4.531802 | false | false | false | false |
tjw/swift | test/Interpreter/SDK/c_pointers.swift | 2 | 3434 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -o %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
#if os(macOS)
import AppKit
typealias XXColor = NSColor
#endif
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
typealias XXColor = UIColor
#endif
// Exercise some common APIs that make use of C pointer arguments.
//
// Typed C pointers
//
let rgb = CGColorSpaceCreateDeviceRGB()
let cgRed = CGColor(colorSpace: rgb, components: [1.0, 0.0, 0.0, 1.0])!
let nsRed = XXColor(cgColor: cgRed)
var r: CGFloat = 0.5, g: CGFloat = 0.5, b: CGFloat = 0.5, a: CGFloat = 0.5
#if os(macOS)
nsRed!.getRed(&r, green: &g, blue: &b, alpha: &a)
#else
nsRed.getRed(&r, green: &g, blue: &b, alpha: &a)
#endif
// CHECK-LABEL: Red is:
print("Red is:")
print("<\(r) \(g) \(b) \(a)>") // CHECK-NEXT: <1.0 0.0 0.0 1.0>
//
// Void C pointers
//
// FIXME: Array type annotation should not be required
let data = NSData(bytes: [1.5, 2.25, 3.125] as [Double],
length: MemoryLayout<Double>.size * 3)
var fromData = [0.25, 0.25, 0.25]
let notFromData = fromData
data.getBytes(&fromData, length: MemoryLayout<Double>.size * 3)
// CHECK-LABEL: Data is:
print("Data is:")
print(fromData[0]) // CHECK-NEXT: 1.5
print(fromData[1]) // CHECK-NEXT: 2.25
print(fromData[2]) // CHECK-NEXT: 3.125
// CHECK-LABEL: Independent data is:
print("Independent data is:")
print(notFromData[0]) // CHECK-NEXT: 0.25
print(notFromData[1]) // CHECK-NEXT: 0.25
print(notFromData[2]) // CHECK-NEXT: 0.25
//
// ObjC pointers
//
class Canary: NSObject {
deinit {
print("died")
}
}
var CanaryAssocObjectHandle: UInt8 = 0
// Attach an associated object with a loud deinit so we can see that the
// error died.
func hangCanary(_ o: AnyObject) {
objc_setAssociatedObject(o, &CanaryAssocObjectHandle, Canary(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
// CHECK-LABEL: NSError out:
print("NSError out:")
autoreleasepool {
do {
let s = try NSString(contentsOfFile: "/hopefully/does/not/exist\u{1B}",
encoding: String.Encoding.utf8.rawValue)
_preconditionFailure("file should not actually exist")
} catch {
print(error._code) // CHECK-NEXT: 260
hangCanary(error as NSError)
}
}
// The result error should have died with the autorelease pool
// CHECK-NEXT: died
class DumbString: NSString {
override func character(at x: Int) -> unichar { _preconditionFailure("nope") }
override var length: Int { return 0 }
convenience init(contentsOfFile s: String, encoding: String.Encoding) throws {
self.init()
throw NSError(domain: "Malicious Mischief", code: 594, userInfo: nil)
}
}
// CHECK-LABEL: NSError in:
print("NSError in:")
autoreleasepool {
do {
try DumbString(contentsOfFile: "foo", encoding: .utf8)
} catch {
print(error._domain) // CHECK-NEXT: Malicious Mischief
print(error._code) // CHECK-NEXT: 594
hangCanary(error as NSError)
}
}
// The result error should have died with the autorelease pool
// CHECK-NEXT: died
let s = "Hello World"
puts(s)
// CHECK-NEXT: Hello World
//
// C function pointers
//
var unsorted = [3, 14, 15, 9, 2, 6, 5]
qsort(&unsorted, unsorted.count, MemoryLayout.size(ofValue: unsorted[0])) { a, b in
return Int32(a!.load(as: Int.self) - b!.load(as: Int.self))
}
// CHECK-NEXT: [2, 3, 5, 6, 9, 14, 15]
print(unsorted)
| apache-2.0 | 5f2f6cded4a551b1cb05fcb13736da64 | 24.626866 | 83 | 0.662493 | 3.136073 | false | false | false | false |
dymx101/Gamers | Gamers/Service/SystemBL.swift | 1 | 1234 | //
// SystemBL.swift
// Gamers
//
// Created by 虚空之翼 on 15/9/1.
// Copyright (c) 2015年 Freedom. All rights reserved.
//
import Foundation
import Alamofire
import Bolts
import SwiftyJSON
class SystemBL: NSObject {
// 单例模式
static let sharedSingleton = SystemBL()
// 获取版本信息
func getVersion() -> BFTask {
var fetchTask = BFTask(result: nil)
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return SystemDao.getVersion()
})
fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in
if let versions = task.result as? [Version] {
for version in versions {
if version.app == "ios" {
return BFTask(result: version)
}
}
}
if let response = task.result as? Response {
return BFTask(result: response)
}
return task
})
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return task
})
return fetchTask
}
}
| apache-2.0 | 900dd6c15991d7c65f9dbdbd8af5ba87 | 22.607843 | 80 | 0.509136 | 4.758893 | false | false | false | false |
galacemiguel/bluehacks2017 | Project Civ-1/Project Civ/Networker.swift | 1 | 6033 | //
// Networker.swift
// Project Civ
//
// Created by Carlos Arcenas on 2/19/17.
// Copyright © 2017 Rogue Three. All rights reserved.
//
import Foundation
import Alamofire
class ProjectSource: NSObject {
let sourceURL = "10.101.1.28:9999"
static let sharedInstance = ProjectSource()
fileprivate var projects: [Project]?
fileprivate var longitude = Double()
fileprivate var latitude = Double()
override init() {
super.init()
}
func fetchProjects(longitude: Double, latitude: Double, completion: @escaping(_ projects: [Project]?) -> Void) {
guard projects != nil, self.longitude != longitude, self.latitude != latitude else {
Alamofire.request(URL(string:"http://\(sourceURL)/project/viewallprojects")!, method: .get, parameters: nil, encoding: URLEncoding.default, headers: ["Accept" : "application/json"]).responseJSON { response in
guard response.result.isSuccess else {
print("Error while fetching projects.")
return
}
guard let value = response.result.value as? [[String: Any]] else {
print("Malformed data received from viewallprojects service")
completion(nil)
return
}
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
for array in value {
for (key, value) in array {
print("For key \(key) we have type \(Mirror(reflecting: value).subjectType)")
}
}
let innerProjects = value.flatMap({ (dict) -> Project in
return Project(id: String(describing:(dict["id"] as? Int)!),
imageURL: "hello",
name: (dict["name"] as? String)!,
holdingOffice: (dict["local_government_name"] as? String)!,
longitude: Double((dict["longitude"] as? String)!)!,
latitude: Double((dict["latitude"] as? String)!)!,
location: (dict["local_government_name"] as? String)!,
contactNumber: (dict["contact_number"] as? String)!,
cost: Double((dict["cost"] as? String)!)!,
dateStarted: formatter.date(from: (dict["date_started"] as? String)!)!,
dateExpectedCompletion: formatter.date(from: (dict["deadline"] as? String)!)!,
projectDescription: (dict["description"] as? String)!,
upvotes: (dict["upvotes"] as? Int)!,
downvotes: (dict["downvotes"] as? Int)!)
})
completion(innerProjects)
}
return
}
}
func fetchUpdatesForProject(_ project: Project, completion: @escaping(_ projectUpdates: [ProjectUpdate]?) -> Void) {
Alamofire.request(URL(string:"http://\(sourceURL)/project/updates")!, method: .get, parameters: ["projectID" : Int(project.id)!], encoding: URLEncoding.default, headers: ["Accept" : "application/json"]).responseJSON { response in
guard response.result.isSuccess else {
print("Error while fetching project updates.")
print(response.error!)
return
}
guard let value = response.result.value as? [[String: Any]] else {
print("Malformed data received from updates service")
completion(nil)
return
}
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
for array in value {
for (key, value) in array {
print("For key \(key) we have type \(Mirror(reflecting: value).subjectType) for \(value)")
}
}
let projectUpdates = value.flatMap({ (dict) -> ProjectUpdate in
return ProjectUpdate(project: project, user: User(name: (dict["poster"] as? String)!, username: nil, imageURL: nil), title: ((dict["title"] as? String)!), message: ((dict["description"] as? String)!), imageURL: nil,
date: formatter.date(from: ((dict["dateUploaded"] as? String)!))!)
})
completion(projectUpdates)
}
return
}
func postNewProject(project: Project, completion: @escaping () -> Void) {
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
let request = Alamofire.request(URL(string: "http://\(sourceURL)/project/new")!, method: .post, parameters: ["name" : project.name, "local_government_name" : project.holdingOffice, "longitude" : String(project.longitude), "latitude" : String(project.latitude), "contact_number" : project.contactNumber, "cost" : String(project.cost), "date_started" : formatter.string(from: project.dateStarted), "deadline" : formatter.string(from: project.dateExpectedCompletion), "description" : project.projectDescription, "upvotes" : project.upvotes, "downvotes" : project.downvotes], encoding: JSONEncoding.default, headers: ["Accept" : "application/json"])
// request.validate()
request.responseJSON { response in
guard response.result.isSuccess else {
print("Error while sending projects.")
print(response.error)
print(response.result.value)
return
}
completion()
}
}
}
| mit | 9fdced8f9dbebb8546951d04da66ad4d | 45.4 | 654 | 0.521883 | 5.182131 | false | false | false | false |
cheyongzi/MGTV-Swift | MGTV-Swift/Share/BaseView/BaseView57.swift | 1 | 2058 | //
// BaseView57.swift
// MGTV-Swift
//
// Created by Che Yongzi on 16/10/13.
// Copyright © 2016年 Che Yongzi. All rights reserved.
//
import UIKit
import Kingfisher
class BaseView: UIView {
var viewData: AnyObject?
@IBOutlet var view: UIView!
@IBOutlet weak var baseImageView: BaseImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.setUPXIB()
}
func config(templateItem item: TemplateResponseItem?, isDesc: Bool, picSize: String) {
viewData = item
//名称判断
var name: String?
if !isEmpty(data: item?.mobileTitle) {
name = item?.mobileTitle
} else {
name = item?.name
}
nameLabel.text = name
//描述信息判断
if isDesc {
descLabel.isHidden = true
} else {
descLabel.isHidden = false
descLabel.text = item?.subName
}
}
func config(recommondItem item: RecommonResponseData?, isDesc: Bool, picSize: String) {
viewData = item
//名称判断
nameLabel.text = item?.name
//描述信息判断
if isDesc {
descLabel.isHidden = true
} else {
descLabel.isHidden = false
descLabel.text = item?.title
}
baseImageView.configRecommand(item: item, picSize: picSize)
}
func setUPXIB() {
Bundle.main.loadNibNamed(String(describing: type(of: self)), owner: self, options: nil)
view.frame = self.bounds
self.addSubview(view)
}
}
class BaseView57: BaseView {
//MARK: - config cell method
override func config(templateItem item: TemplateResponseItem?, isDesc: Bool, picSize: String) {
super.config(templateItem: item, isDesc: isDesc, picSize: picSize)
baseImageView.configTemplate(item: item, picSize: picSize, imageType: .Vertical)
}
}
| mit | 8d3b43902eacd12e9acf7eccedadc809 | 25.168831 | 99 | 0.591067 | 4.296375 | false | true | false | false |
CRAnimation/CRAnimation | Example/CRAnimation/Demo/WidgetDemo/S0018_CRRefresh/CRRefreshVC.swift | 1 | 4756 | //
// CRRefreshVC.swift
// CRAnimation
//
// **************************************************
// * _____ *
// * __ _ __ ___ \ / *
// * \ \/ \/ / / __\ / / *
// * \ _ / | (__ / / *
// * \/ \/ \___/ / /__ *
// * /_____/ *
// * *
// **************************************************
// Github :https://github.com/imwcl
// HomePage:http://imwcl.com
// CSDN :http://blog.csdn.net/wang631106979
//
// Created by 王崇磊 on 16/9/14.
// Copyright © 2016年 王崇磊. All rights reserved.
//
// @class CRRefreshVC
// @abstract CRRefreshVC
// @discussion CRRefreshVC
//
import UIKit
import CRRefresh
class CRRefreshVC: CRProductionBaseVC {
var tableView: UITableView = {
let table = UITableView(frame: .zero, style: .grouped)
return table
}()
var refreshs: [Refresh] = [
Refresh(model: .init(icon: #imageLiteral(resourceName: "S0001TestImage_1"), title: "NormalAnimator", subTitle: "普通刷新控件"), header: .nomalHead, footer: .nomalFoot),
Refresh(model: .init(icon: #imageLiteral(resourceName: "S0001TestImage_2"), title: "SlackLoadingAnimator", subTitle: "SlackLoading的刷新控件"), header: .slackLoading, footer: .slackLoading),
Refresh(model: .init(icon: #imageLiteral(resourceName: "S0001TestImage_3"), title: "RamotionAnimator", subTitle: "Ramotion的刷新控件"), header: .ramotion, footer: .nomalFoot),
Refresh(model: .init(icon: #imageLiteral(resourceName: "S0001TestImage_1"), title: "FastAnimator", subTitle: "FastAnimator的刷新控件"), header: .fast, footer: .nomalFoot)
]
override func viewDidLoad() {
super.viewDidLoad()
createUI()
}
override func createUI() {
super.createUI()
configView()
}
func configView() {
tableView.frame = .init(x: 0, y: 0, width: contentView.frame.width, height: contentView.frame.height)
tableView.register(UINib.init(nibName: "CRRefreshNormalCellTableViewCell", bundle: nil), forCellReuseIdentifier: "CRRefreshNormalCellTableViewCell")
contentView.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - Table view data source
extension CRRefreshVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let refresh = refreshs[indexPath.row]
let vc = CRRefreshViewController(refresh: refresh)
navigationController?.pushViewController(vc, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return refreshs.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CRRefreshNormalCellTableViewCell", for: indexPath) as! CRRefreshNormalCellTableViewCell
let refresh = refreshs[indexPath.row]
cell.config(refresh.model)
return cell
}
}
struct Refresh {
var model: Model
var header: Style
var footer: Style
struct Model {
var icon: UIImage
var title: String
var subTitle: String
}
enum Style {
// 普通刷新类
case nomalHead
case nomalFoot
// slackLoading刷新控件
case slackLoading
// ramotion动画
case ramotion
// fast动画
case fast
func commont() -> CRRefreshProtocol {
switch self {
case .nomalHead:
return NormalHeaderAnimator()
case .nomalFoot:
return NormalFooterAnimator()
case .slackLoading:
return SlackLoadingAnimator()
case .ramotion:
return RamotionAnimator(ballColor: .white, waveColor: UIColor(rgba: "#323341"))
case .fast:
return FastAnimator()
}
}
}
}
| mit | 5c85b4b767e75762dbc87278d2805f96 | 33.614815 | 193 | 0.578429 | 4.550146 | false | false | false | false |
daniele-pizziconi/AlamofireImage | Carthage/Checkouts/YLGIFImage-Swift/YLGIFImage-Swift/YLGIFImage.swift | 1 | 5432 | //
// YLGIFImage.swift
// YLGIFImage
//
// Created by Yong Li on 6/8/14.
// Copyright (c) 2014 Yong Li. All rights reserved.
//
import UIKit
import ImageIO
import MobileCoreServices
public class YLGIFImage : UIImage {
private class func isCGImageSourceContainAnimatedGIF(_ cgImageSource: CGImageSource) -> Bool {
let isGIF = UTTypeConformsTo(CGImageSourceGetType(cgImageSource)!, kUTTypeGIF)
let imgCount = CGImageSourceGetCount(cgImageSource)
return isGIF && imgCount > 1
}
private class func getCGImageSourceGifFrameDelay(_ imageSource: CGImageSource, index: UInt) -> TimeInterval {
var delay = 0.0
let imgProperties:NSDictionary = CGImageSourceCopyPropertiesAtIndex(imageSource, Int(index), nil)!
let gifProperties:NSDictionary? = imgProperties[kCGImagePropertyGIFDictionary as String] as? NSDictionary
if let property = gifProperties {
delay = property[kCGImagePropertyGIFUnclampedDelayTime as String] as! Double
if delay <= 0 {
delay = property[kCGImagePropertyGIFDelayTime as String] as! Double
}
}
return delay
}
private func createSelf(_ cgImageSource: CGImageSource!, scale: CGFloat) -> Void {
_cgImgSource = cgImageSource
let imageProperties:NSDictionary = CGImageSourceCopyProperties(_cgImgSource!, nil)!
let gifProperties: NSDictionary? = imageProperties[kCGImagePropertyGIFDictionary as String] as? NSDictionary
if let property = gifProperties {
self.loopCount = property[kCGImagePropertyGIFLoopCount as String] as! UInt
}
let numOfFrames = CGImageSourceGetCount(cgImageSource)
for i in 0..<numOfFrames {
// get frame duration
let frameDuration = YLGIFImage.getCGImageSourceGifFrameDelay(cgImageSource, index: UInt(i))
self.frameDurations.append(NSNumber(value: frameDuration))
self.totalDuration += frameDuration
//Log("dura = \(frameDuration)")
if i < Int(YLGIFImage.prefetchNum) {
// get frame
let cgimage = CGImageSourceCreateImageAtIndex(cgImageSource, i, nil)
let image: UIImage = UIImage(cgImage: cgimage!)
self.frameImages.append(image)
//Log("\(i): frame = \(image)")
} else {
self.frameImages.append(NSNull())
}
}
//Log("\(self.frameImages.count)")
}
private lazy var readFrameQueue:DispatchQueue = DispatchQueue(label: "com.ronnie.gifreadframe")
private var _scale:CGFloat = 1.0
private var _cgImgSource:CGImageSource? = nil
var totalDuration: TimeInterval = 0.0
var frameDurations = [AnyObject]()
var loopCount: UInt = 1
var frameImages:[AnyObject] = [AnyObject]()
struct YLGIFGlobalSetting {
static var prefetchNumber:UInt = 10
}
class var prefetchNum: UInt {
return YLGIFGlobalSetting.prefetchNumber
}
class func setPrefetchNum(_ number:UInt) {
YLGIFGlobalSetting.prefetchNumber = number
}
public convenience init?(named name: String!) {
guard let path = Bundle.main.path(forResource: name, ofType: nil)
else { return nil }
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path))
else { return nil }
self.init(data: data)
}
public convenience override init?(contentsOfFile path: String) {
let data = try? Data(contentsOf: URL(string: path)!)
self.init(data: data!)
}
public override init?(data: Data) {
if let cgImgSource = CGImageSourceCreateWithData(data as CFData, nil), YLGIFImage.isCGImageSourceContainAnimatedGIF(cgImgSource) {
super.init()
createSelf(cgImgSource, scale: 1.0)
} else {
super.init(data: data)
}
}
public override init?(data: Data, scale: CGFloat) {
if let cgImgSource = CGImageSourceCreateWithData(data as CFData, nil), YLGIFImage.isCGImageSourceContainAnimatedGIF(cgImgSource) {
super.init()
createSelf(cgImgSource, scale: scale)
} else {
super.init(data: data, scale: scale)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required public init(imageLiteralResourceName name: String) {
fatalError("init(imageLiteral name:) has not been implemented")
}
func getFrame(_ index: UInt) -> UIImage? {
if Int(index) >= self.frameImages.count {
return nil
}
let image:UIImage? = self.frameImages[Int(index)] as? UIImage
if self.frameImages.count > Int(YLGIFImage.prefetchNum) {
if index != 0 {
self.frameImages[Int(index)] = NSNull()
}
for i in index+1...index+YLGIFImage.prefetchNum {
let idx = Int(i)%self.frameImages.count
if self.frameImages[idx] is NSNull {
self.readFrameQueue.async{
let cgImg = CGImageSourceCreateImageAtIndex(self._cgImgSource!, idx, nil)
self.frameImages[idx] = UIImage(cgImage: cgImg!)
}
}
}
}
return image
}
}
| mit | 4f17e17629427e454a10e4ec6a3dfe3a | 36.205479 | 138 | 0.621502 | 4.769096 | false | false | false | false |
WhisperSystems/Signal-iOS | Signal/src/ViewControllers/ConversationView/Cells/AudioMessageView.swift | 1 | 10103 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import Lottie
class AudioMessageView: UIStackView {
private let attachment: TSAttachment
private var attachmentStream: TSAttachmentStream? {
guard let attachmentStream = attachment as? TSAttachmentStream else { return nil }
return attachmentStream
}
private let isIncoming: Bool
private weak var viewItem: ConversationViewItem?
private let conversationStyle: ConversationStyle
private let playPauseAnimation = AnimationView(name: "playPauseButton")
private let playbackTimeLabel = UILabel()
private let progressSlider = UISlider()
private let waveformProgress = AudioWaveformProgressView()
private var durationSeconds: CGFloat {
guard let durationSeconds = viewItem?.audioDurationSeconds else {
owsFailDebug("unexpectedly missing duration seconds")
return 0
}
return durationSeconds
}
private var elapsedSeconds: CGFloat {
guard let elapsedSeconds = viewItem?.audioProgressSeconds else {
owsFailDebug("unexpectedly missing elapsed seconds")
return 0
}
return elapsedSeconds
}
@objc
init(attachment: TSAttachment, isIncoming: Bool, viewItem: ConversationViewItem, conversationStyle: ConversationStyle) {
self.attachment = attachment
self.isIncoming = isIncoming
self.viewItem = viewItem
self.conversationStyle = conversationStyle
super.init(frame: .zero)
axis = .vertical
spacing = AudioMessageView.vSpacing
if !attachment.isVoiceMessage {
let topText: String
if let fileName = attachment.sourceFilename?.stripped, !fileName.isEmpty {
topText = fileName
} else {
topText = NSLocalizedString("GENERIC_ATTACHMENT_LABEL", comment: "A label for generic attachments.")
}
let topLabel = UILabel()
topLabel.text = topText
topLabel.textColor = conversationStyle.bubbleTextColor(isIncoming: isIncoming)
topLabel.font = AudioMessageView.labelFont
addArrangedSubview(topLabel)
}
// TODO: There is a bug with Lottie where animations lag when there are a lot
// of other things happening on screen. Since this animation generally plays
// when the progress bar / waveform is rendering we speed up the playback to
// address some of the lag issues. Once this is fixed we should update lottie
// and remove this check. https://github.com/airbnb/lottie-ios/issues/1034
playPauseAnimation.animationSpeed = 3
playPauseAnimation.backgroundBehavior = .forceFinish
playPauseAnimation.contentMode = .scaleAspectFit
playPauseAnimation.autoSetDimensions(to: CGSize(square: animationSize))
playPauseAnimation.setContentHuggingHigh()
let fillColorKeypath = AnimationKeypath(keypath: "**.Fill 1.Color")
playPauseAnimation.setValueProvider(ColorValueProvider(thumbColor.lottieColorValue), keypath: fillColorKeypath)
let waveformContainer = UIView.container()
waveformContainer.autoSetDimension(.height, toSize: AudioMessageView.waveformHeight)
waveformProgress.playedColor = playedColor
waveformProgress.unplayedColor = unplayedColor
waveformProgress.thumbColor = thumbColor
waveformContainer.addSubview(waveformProgress)
waveformProgress.autoPinEdgesToSuperviewEdges()
progressSlider.setThumbImage(UIImage(named: "audio_message_thumb")?.asTintedImage(color: thumbColor), for: .normal)
progressSlider.setMinimumTrackImage(trackImage(color: playedColor), for: .normal)
progressSlider.setMaximumTrackImage(trackImage(color: unplayedColor), for: .normal)
waveformContainer.addSubview(progressSlider)
progressSlider.autoPinWidthToSuperview()
progressSlider.autoSetDimension(.height, toSize: 12)
progressSlider.autoVCenterInSuperview()
playbackTimeLabel.textColor = conversationStyle.bubbleSecondaryTextColor(isIncoming: isIncoming)
playbackTimeLabel.font = UIFont.ows_dynamicTypeCaption1.ows_monospaced()
playbackTimeLabel.setContentHuggingHigh()
let playerStack = UIStackView(arrangedSubviews: [playPauseAnimation, waveformContainer, playbackTimeLabel])
playerStack.isLayoutMarginsRelativeArrangement = true
playerStack.layoutMargins = UIEdgeInsets(
top: AudioMessageView.vMargin,
leading: hMargin,
bottom: AudioMessageView.vMargin,
trailing: hMargin
)
playerStack.spacing = hSpacing
addArrangedSubview(playerStack)
waveformContainer.autoAlignAxis(.horizontal, toSameAxisOf: playPauseAnimation)
updateContents(animated: false)
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Scrubbing
@objc var isScrubbing = false
@objc
func isPointInScrubbableRegion(_ point: CGPoint) -> Bool {
// If we have a waveform but aren't done sampling it, don't allow scrubbing yet.
if let waveform = attachmentStream?.audioWaveform(), !waveform.isSamplingComplete {
return false
}
let locationInSlider = convert(point, to: waveformProgress)
return locationInSlider.x >= 0 && locationInSlider.x <= waveformProgress.width()
}
@objc func scrubToLocation(_ point: CGPoint) -> TimeInterval {
let sliderContainer = convert(waveformProgress.frame, from: waveformProgress.superview)
var newRatio = CGFloatClamp01(CGFloatInverseLerp(point.x, sliderContainer.minX, sliderContainer.maxX))
// When in RTL mode, the slider moves in the opposite direction so inverse the ratio.
if CurrentAppContext().isRTL {
newRatio = 1 - newRatio
}
visibleProgressRatio = newRatio
return TimeInterval(newRatio * durationSeconds)
}
// MARK: - Contents
private static var labelFont: UIFont = .ows_dynamicTypeCaption2
private static var waveformHeight: CGFloat = 35
private static var vMargin: CGFloat = 4
private var animationSize: CGFloat = 28
private var iconSize: CGFloat = 24
private var hMargin: CGFloat = 0
private var hSpacing: CGFloat = 12
private static var vSpacing: CGFloat = 2
private lazy var playedColor: UIColor = isIncoming ? .init(rgbHex: 0x92caff) : .ows_white
private lazy var unplayedColor: UIColor =
isIncoming ? Theme.secondaryColor.withAlphaComponent(0.3) : UIColor.ows_white.withAlphaComponent(0.6)
private lazy var thumbColor: UIColor = isIncoming ? Theme.secondaryColor : .ows_white
@objc
static var bubbleHeight: CGFloat {
return labelFont.lineHeight + waveformHeight + vSpacing + (vMargin * 2)
}
@objc
func updateContents() {
updateContents(animated: true)
}
func updateContents(animated: Bool) {
updatePlaybackState(animated: animated)
updateAudioProgress()
showDownloadProgressIfNecessary()
}
private var audioProgressRatio: CGFloat {
guard durationSeconds > 0 else { return 0 }
return elapsedSeconds / durationSeconds
}
private var visibleProgressRatio: CGFloat {
get {
return waveformProgress.value
}
set {
waveformProgress.value = newValue
progressSlider.value = Float(newValue)
updateElapsedTime(durationSeconds * newValue)
}
}
private func updatePlaybackState(animated: Bool = true) {
let isPlaying = viewItem?.audioPlaybackState == .playing
let destination: AnimationProgressTime = isPlaying ? 1 : 0
if animated {
playPauseAnimation.play(toProgress: destination)
} else {
playPauseAnimation.currentProgress = destination
}
}
private func updateElapsedTime(_ elapsedSeconds: CGFloat) {
let timeRemaining = Int(durationSeconds - elapsedSeconds)
playbackTimeLabel.text = OWSFormat.formatDurationSeconds(timeRemaining)
}
private func updateAudioProgress() {
guard !isScrubbing else { return }
visibleProgressRatio = audioProgressRatio
if let waveform = attachmentStream?.audioWaveform() {
waveformProgress.audioWaveform = waveform
waveformProgress.isHidden = false
progressSlider.isHidden = true
} else {
waveformProgress.isHidden = true
progressSlider.isHidden = false
}
}
private func showDownloadProgressIfNecessary() {
guard let attachmentPointer = viewItem?.attachmentPointer else { return }
// We don't need to handle the "tap to retry" state here,
// only download progress.
guard .failed != attachmentPointer.state else { return }
// TODO: Show "restoring" indicator and possibly progress.
guard .restoring != attachmentPointer.pointerType else { return }
guard attachmentPointer.uniqueId.count > 1 else {
return owsFailDebug("missing unique id")
}
// Add the download view to the play pause animation. This view
// will get recreated once the download completes so we don't
// have to worry about resetting anything.
let downloadView = MediaDownloadView(attachmentId: attachmentPointer.uniqueId, radius: iconSize * 0.5)
playPauseAnimation.animation = nil
playPauseAnimation.addSubview(downloadView)
downloadView.autoSetDimensions(to: CGSize(square: iconSize))
downloadView.autoCenterInSuperview()
}
private func trackImage(color: UIColor) -> UIImage? {
return UIImage(named: "audio_message_track")?
.asTintedImage(color: color)?
.resizableImage(withCapInsets: UIEdgeInsets(top: 0, leading: 2, bottom: 0, trailing: 2))
}
}
| gpl-3.0 | 59fa644fe38e5dd8ef1b1429f93241b4 | 37.857692 | 124 | 0.68643 | 5.281234 | false | false | false | false |
nathawes/swift | test/IRGen/multi_file_resilience.swift | 8 | 2599 | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-swift-frontend -emit-module -enable-library-evolution \
// RUN: -emit-module-path=%t/resilient_struct.swiftmodule \
// RUN: -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -module-name main -I %t -emit-ir -primary-file %s %S/Inputs/OtherModule.swift | %FileCheck %s -DINT=i%target-ptrsize
// Check that we correctly handle resilience when parsing as SIL + SIB.
// RUN: %target-swift-frontend -emit-sib -module-name main %S/Inputs/OtherModule.swift -I %t -o %t/other.sib
// RUN: %target-swift-frontend -emit-silgen -module-name main -primary-file %s %S/Inputs/OtherModule.swift -I %t -o %t/main.sil
// RUN: %target-swift-frontend -emit-ir -module-name main -primary-file %t/main.sil %t/other.sib -I %t | %FileCheck %s -DINT=i%target-ptrsize
// This is a single-module version of the test case in
// multi_module_resilience.
// rdar://39763787
// CHECK-LABEL: define {{(dllexport |protected )?}}swiftcc void @"$s4main7copyFoo3fooAA0C0VAE_tF"
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s4main3FooVMa"([[INT]] 0)
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[VWT:%.*]] = load i8**,
// Allocate 'copy'.
// CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable*
// CHECK: [[SIZE_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8
// CHECK: [[SIZE:%.*]] = load [[INT]], [[INT]]* [[SIZE_ADDR]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, [[INT]] [[SIZE]],
// CHECK: [[COPY:%.*]] = bitcast i8* [[ALLOCA]] to [[FOO:%T4main3FooV]]*
// Perform 'initializeWithCopy' via the VWT instead of trying to inline it.
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK: [[T1:%.*]] = load i8*, i8** [[T0]],
// CHECK: [[COPYFN:%.*]] = bitcast i8* [[T1]] to %swift.opaque* (%swift.opaque*, %swift.opaque*, %swift.type*)*
// CHECK: [[DEST:%.*]] = bitcast [[FOO]]* [[COPY]] to %swift.opaque*
// CHECK: [[SRC:%.*]] = bitcast [[FOO]]* %1 to %swift.opaque*
// CHECK: call %swift.opaque* [[COPYFN]](%swift.opaque* noalias [[DEST]], %swift.opaque* noalias [[SRC]], %swift.type* [[METADATA]])
// Perform 'initializeWithCopy' via the VWT.
// CHECK: [[DEST:%.*]] = bitcast [[FOO]]* %0 to %swift.opaque*
// CHECK: [[SRC:%.*]] = bitcast [[FOO]]* [[COPY]] to %swift.opaque*
// CHECK: call %swift.opaque* [[COPYFN]](%swift.opaque* noalias [[DEST]], %swift.opaque* noalias [[SRC]], %swift.type* [[METADATA]])
public func copyFoo(foo: Foo) -> Foo {
let copy = foo
return copy
}
| apache-2.0 | 27ed22da610d25072fdfc5bf3690288c | 59.44186 | 147 | 0.636014 | 3.135103 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.