repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kesun421/firefox-ios | Push/PushCrypto.swift | 7 | 14173 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import FxA
/// Class to wrap ecec which does the encryption, decryption and key generation with OpenSSL.
/// This supports aesgcm and the newer aes128gcm.
/// For each standard of decryption, two methods are supplied: one with Data parameters and return value,
/// and one with a String based one.
class PushCrypto {
// Stateless, we provide a singleton for convenience.
open static var sharedInstance = PushCrypto()
}
// AES128GCM
extension PushCrypto {
func aes128gcm(payload data: String, decryptWith privateKey: String, authenticateWith authKey: String) throws -> String {
guard let authSecret = authKey.base64urlSafeDecodedData,
let rawRecvPrivKey = privateKey.base64urlSafeDecodedData,
let payload = data.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let decrypted = try aes128gcm(payload: payload,
decryptWith: rawRecvPrivKey,
authenticateWith: authSecret)
guard let plaintext = decrypted.utf8EncodedString else {
throw PushCryptoError.utf8EncodingError
}
return plaintext
}
func aes128gcm(payload: Data, decryptWith rawRecvPrivKey: Data, authenticateWith authSecret: Data) throws -> Data {
var plaintextLen = ece_aes128gcm_plaintext_max_length(payload.getBytes(), payload.count) + 1
var plaintext = [UInt8](repeating: 0, count: plaintextLen)
let err = ece_webpush_aes128gcm_decrypt(
rawRecvPrivKey.getBytes(), rawRecvPrivKey.count,
authSecret.getBytes(), authSecret.count,
payload.getBytes(), payload.count,
&plaintext, &plaintextLen)
if err != ECE_OK {
throw PushCryptoError.decryptionError(errCode: err)
}
return Data(bytes: plaintext, count: plaintextLen)
}
func aes128gcm(plaintext: String, encryptWith rawRecvPubKey: String, authenticateWith authSecret: String, rs: Int, padLen: Int) throws -> String {
guard let rawRecvPubKey = rawRecvPubKey.base64urlSafeDecodedData,
let authSecret = authSecret.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let plaintextData = plaintext.utf8EncodedData
let payloadData = try aes128gcm(plaintext: plaintextData,
encryptWith: rawRecvPubKey,
authenticateWith: authSecret,
rs: rs, padLen: padLen)
guard let payload = payloadData.base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return payload
}
func aes128gcm(plaintext: Data, encryptWith rawRecvPubKey: Data, authenticateWith authSecret: Data, rs rsInt: Int, padLen: Int) throws -> Data {
let rs = UInt32(rsInt)
// rs needs to be >= 18.
assert(rsInt >= Int(ECE_AES128GCM_MIN_RS))
var payloadLen = ece_aes128gcm_payload_max_length(rs, padLen, plaintext.count) + 1
var payload = [UInt8](repeating: 0, count: payloadLen)
let err = ece_webpush_aes128gcm_encrypt(rawRecvPubKey.getBytes(), rawRecvPubKey.count,
authSecret.getBytes(), authSecret.count,
rs, padLen,
plaintext.getBytes(), plaintext.count,
&payload, &payloadLen)
if err != ECE_OK {
throw PushCryptoError.encryptionError(errCode: err)
}
return Data(bytes: payload, count: payloadLen)
}
}
// AESGCM
extension PushCrypto {
func aesgcm(ciphertext data: String, withHeaders headers: PushCryptoHeaders, decryptWith privateKey: String, authenticateWith authKey: String) throws -> String {
guard let authSecret = authKey.base64urlSafeDecodedData,
let rawRecvPrivKey = privateKey.base64urlSafeDecodedData,
let ciphertext = data.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let decrypted = try aesgcm(ciphertext: ciphertext,
withHeaders: headers,
decryptWith: rawRecvPrivKey,
authenticateWith: authSecret)
guard let plaintext = decrypted.utf8EncodedString else {
throw PushCryptoError.utf8EncodingError
}
return plaintext
}
func aesgcm(ciphertext: Data, withHeaders headers: PushCryptoHeaders, decryptWith rawRecvPrivKey: Data, authenticateWith authSecret: Data) throws -> Data {
let saltLength = Int(ECE_SALT_LENGTH)
var salt = [UInt8](repeating: 0, count: saltLength)
let rawSenderPubKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawSenderPubKey = [UInt8](repeating: 0, count: rawSenderPubKeyLength)
var rs = UInt32(0)
let paramsErr = ece_webpush_aesgcm_headers_extract_params(
headers.cryptoKey, headers.encryption,
&salt, saltLength,
&rawSenderPubKey, rawSenderPubKeyLength,
&rs)
if paramsErr != ECE_OK {
throw PushCryptoError.decryptionError(errCode: paramsErr)
}
var plaintextLen = ece_aesgcm_plaintext_max_length(rs, ciphertext.count) + 1
var plaintext = [UInt8](repeating: 0, count: plaintextLen)
let decryptErr = ece_webpush_aesgcm_decrypt(
rawRecvPrivKey.getBytes(), rawRecvPrivKey.count,
authSecret.getBytes(), authSecret.count,
&salt, salt.count,
&rawSenderPubKey, rawSenderPubKey.count,
rs,
ciphertext.getBytes(), ciphertext.count,
&plaintext, &plaintextLen)
if decryptErr != ECE_OK {
throw PushCryptoError.decryptionError(errCode: decryptErr)
}
return Data(bytes: plaintext, count: plaintextLen)
}
func aesgcm(plaintext: String, encryptWith rawRecvPubKey: String, authenticateWith authSecret: String, rs: Int, padLen: Int) throws -> (headers: PushCryptoHeaders, ciphertext: String) {
guard let rawRecvPubKey = rawRecvPubKey.base64urlSafeDecodedData,
let authSecret = authSecret.base64urlSafeDecodedData else {
throw PushCryptoError.base64DecodeError
}
let plaintextData = plaintext.utf8EncodedData
let (headers, messageData) = try aesgcm(
plaintext: plaintextData,
encryptWith: rawRecvPubKey,
authenticateWith: authSecret,
rs: rs, padLen: padLen)
guard let message = messageData.base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return (headers, message)
}
func aesgcm(plaintext: Data, encryptWith rawRecvPubKey: Data, authenticateWith authSecret: Data, rs rsInt: Int, padLen: Int) throws -> (headers: PushCryptoHeaders, data: Data) {
let rs = UInt32(rsInt)
// rs needs to be >= 3.
assert(rsInt >= Int(ECE_AESGCM_MIN_RS))
var ciphertextLength = ece_aesgcm_ciphertext_max_length(rs, padLen, plaintext.count) + 1
var ciphertext = [UInt8](repeating: 0, count: ciphertextLength)
let saltLength = Int(ECE_SALT_LENGTH)
var salt = [UInt8](repeating: 0, count: saltLength)
let rawSenderPubKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawSenderPubKey = [UInt8](repeating: 0, count: rawSenderPubKeyLength)
let encryptErr = ece_webpush_aesgcm_encrypt(rawRecvPubKey.getBytes(), rawRecvPubKey.count,
authSecret.getBytes(), authSecret.count,
rs, padLen,
plaintext.getBytes(), plaintext.count,
&salt, saltLength,
&rawSenderPubKey, rawSenderPubKeyLength,
&ciphertext, &ciphertextLength)
if encryptErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: encryptErr)
}
var cryptoKeyHeaderLength = 0
var encryptionHeaderLength = 0
let paramsSizeErr = ece_webpush_aesgcm_headers_from_params(
salt, saltLength,
rawSenderPubKey, rawSenderPubKeyLength,
rs,
nil, &cryptoKeyHeaderLength,
nil, &encryptionHeaderLength)
if paramsSizeErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: paramsSizeErr)
}
var cryptoKeyHeaderBytes = [CChar](repeating: 0, count: cryptoKeyHeaderLength)
var encryptionHeaderBytes = [CChar](repeating: 0, count: encryptionHeaderLength)
let paramsErr = ece_webpush_aesgcm_headers_from_params(
salt, saltLength,
rawSenderPubKey, rawSenderPubKeyLength,
rs,
&cryptoKeyHeaderBytes, &cryptoKeyHeaderLength,
&encryptionHeaderBytes, &encryptionHeaderLength)
if paramsErr != ECE_OK {
throw PushCryptoError.encryptionError(errCode: paramsErr)
}
guard let cryptoKeyHeader = String(data: Data(bytes: cryptoKeyHeaderBytes, count: cryptoKeyHeaderLength),
encoding: .ascii),
let encryptionHeader = String(data: Data(bytes: encryptionHeaderBytes, count: encryptionHeaderLength),
encoding: .ascii) else {
throw PushCryptoError.base64EncodeError
}
let headers = PushCryptoHeaders(encryption: encryptionHeader, cryptoKey: cryptoKeyHeader)
return (headers, Data(bytes: ciphertext, count: ciphertextLength))
}
}
extension PushCrypto {
func generateKeys() throws -> PushKeys {
// The subscription private key. This key should never be sent to the app
// server. It should be persisted with the endpoint and auth secret, and used
// to decrypt all messages sent to the subscription.
let privateKeyLength = Int(ECE_WEBPUSH_PRIVATE_KEY_LENGTH)
var rawRecvPrivKey = [UInt8](repeating: 0, count: privateKeyLength)
// The subscription public key. This key should be sent to the app server,
// and used to encrypt messages. The Push DOM API exposes the public key via
// `pushSubscription.getKey("p256dh")`.
let publicKeyLength = Int(ECE_WEBPUSH_PUBLIC_KEY_LENGTH)
var rawRecvPubKey = [UInt8](repeating: 0, count: publicKeyLength)
// The shared auth secret. This secret should be persisted with the
// subscription information, and sent to the app server. The DOM API exposes
// the auth secret via `pushSubscription.getKey("auth")`.
let authSecretLength = Int(ECE_WEBPUSH_AUTH_SECRET_LENGTH)
var authSecret = [UInt8](repeating: 0, count: authSecretLength)
let err = ece_webpush_generate_keys(
&rawRecvPrivKey, privateKeyLength,
&rawRecvPubKey, publicKeyLength,
&authSecret, authSecretLength)
if err != ECE_OK {
throw PushCryptoError.keyGenerationError(errCode: err)
}
guard let privKey = Data(bytes: rawRecvPrivKey, count: privateKeyLength).base64urlSafeEncodedString,
let pubKey = Data(bytes: rawRecvPubKey, count: publicKeyLength).base64urlSafeEncodedString,
let authKey = Data(bytes: authSecret, count: authSecretLength).base64urlSafeEncodedString else {
throw PushCryptoError.base64EncodeError
}
return PushKeys(p256dhPrivateKey: privKey, p256dhPublicKey: pubKey, auth: authKey)
}
}
struct PushKeys {
let p256dhPrivateKey: String
let p256dhPublicKey: String
let auth: String
}
enum PushCryptoError: Error {
case base64DecodeError
case base64EncodeError
case decryptionError(errCode: Int32)
case encryptionError(errCode: Int32)
case keyGenerationError(errCode: Int32)
case utf8EncodingError
}
struct PushCryptoHeaders {
let encryption: String
let cryptoKey: String
}
extension String {
/// Returns a base64 url safe decoding of the given string.
/// The string is allowed to be padded
/// What is padding?: http://stackoverflow.com/a/26632221
var base64urlSafeDecodedData: Data? {
// We call this method twice: once with the last two args as nil, 0 – this gets us the length
// of the decoded string.
let length = ece_base64url_decode(self, self.characters.count, ECE_BASE64URL_REJECT_PADDING, nil, 0)
guard length > 0 else {
return nil
}
// The second time, we actually decode, and copy it into a made to measure byte array.
var bytes = [UInt8](repeating: 0, count: length)
let checkLength = ece_base64url_decode(self, self.characters.count, ECE_BASE64URL_REJECT_PADDING, &bytes, length)
guard checkLength == length else {
return nil
}
return Data(bytes: bytes, count: length)
}
}
extension Data {
/// Returns a base64 url safe encoding of the given data.
var base64urlSafeEncodedString: String? {
let length = ece_base64url_encode(self.getBytes(), self.count, ECE_BASE64URL_OMIT_PADDING, nil, 0)
guard length > 0 else {
return nil
}
var bytes = [CChar](repeating: 0, count: length)
let checkLength = ece_base64url_encode(self.getBytes(), self.count, ECE_BASE64URL_OMIT_PADDING, &bytes, length)
guard checkLength == length else {
return nil
}
return String(data: Data(bytes: bytes, count: length), encoding: .ascii)
}
}
| mpl-2.0 | cf28c09e080e22d465807449d1f63209 | 41.301493 | 189 | 0.635029 | 4.493025 | false | false | false | false |
catloafsoft/AudioKit | AudioKit/OSX/AudioKit/Playgrounds/AudioKit for OSX.playground/Pages/Distortion.xcplaygroundpage/Contents.swift | 1 | 1940 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Distortion
//: ### This playground provides access to Apple's built-in distortion effect that they lump together into one giant Audio Unit. For clarity, the submodules to the distortion are also available as individual nodes themselves.
import XCPlayground
import AudioKit
//: This section prepares the player and the microphone
var mic = AKMicrophone()
mic.volume = 0
let micWindow = AKMicrophoneWindow(mic)
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("guitarloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
let playerWindow = AKAudioPlayerWindow(player)
//: Next, we'll connect the audio sources to distortion
let inputMix = AKMixer(mic, player)
var distortion = AKDistortion(inputMix)
//: Set the parameters of the distortion here
distortion.delay = 0.1 // Milliseconds
distortion.decay = 1.0 // Rate
distortion.delayMix = 0.5 // Normalized Value 0 - 1
//: These are the decimator-specific parameters
distortion.decimation = 0.5 // Normalized Value 0 - 1
distortion.rounding = 0.0 // Normalized Value 0 - 1
distortion.decimationMix = 0.5 // Normalized Value 0 - 1
distortion.linearTerm = 0.5 // Normalized Value 0 - 1
distortion.squaredTerm = 0.5 // Normalized Value 0 - 1
distortion.cubicTerm = 0.5 // Normalized Value 0 - 1
distortion.polynomialMix = 0.5 // Normalized Value 0 - 1
distortion.ringModFreq1 = 100 // Hertz
distortion.ringModFreq2 = 100 // Hertz
distortion.ringModBalance = 0.5 // Normalized Value 0 - 1
distortion.ringModMix = 0 // Percent
distortion.softClipGain = -6 // dB
distortion.finalMix = 0.5 // Normalized Value 0 - 1
var distortionWindow = AKDistortionWindow(distortion)
AudioKit.output = distortion
AudioKit.start()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | 742369457fc4c03b4184eeb162407079 | 36.307692 | 226 | 0.746392 | 4.033264 | false | false | false | false |
pyromobile/nubomedia-ouatclient-src | ios/LiveTales-smartphones/uoat/InviteNotificationsManagerViewController.swift | 1 | 11135 | //
// InviteNotificationsManagerViewController.swift
// uoat
//
// Created by Pyro User on 28/7/16.
// Copyright © 2016 Zed. All rights reserved.
//
import UIKit
class InviteNotificationsManagerViewController:UIViewController, UITableViewDataSource, UITableViewDelegate
{
var bgImagePath:String!
weak var user:User!
var notificationsByType:[NotificationType:[Notification]]!
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(InviteNotificationsManagerViewController.networkStatusChanged(_:)), name: NetworkWatcher.reachabilityStatusChangedNotification, object: nil)
}
deinit
{
self.user = nil
self.bgImagePath = nil
self.notifications.removeAll()
self.notificationIdsToBeConsumed.removeAll()
NSNotificationCenter.defaultCenter().removeObserver( self, name: NetworkWatcher.reachabilityStatusChangedNotification, object: nil )
print("InviteNotificationsManagerViewController - deInit....OK")
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
//load resources.
//.:Back button
let leftArrowActiveImage:UIImage = Utils.flipImage( named: "btn_next_available", orientation: .Down )
self.leftArrowImage.image = leftArrowActiveImage
if( self.bgMainImage.image == nil )
{
self.bgMainImage.image = UIImage( contentsOfFile:self.bgImagePath )!
let blurEffectView:UIVisualEffectView = Utils.blurEffectView( self.bgMainImage, radius:6 ) //3
self.bgMainImage.addSubview( blurEffectView )
}
self.notificationsTable.delegate = self
self.notificationsTable.dataSource = self
self.dumpNotifications()
self.getNickNamesFromNotifications()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool
{
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if( segue.identifier == "showFreeModeView" )
{
let controller = segue.destinationViewController as! FreeModeViewController
controller.user = self.user
controller.bgImagePath = self.bgImagePath
}
else if( segue.identifier == "showRevealView" )
{
//let controller = segue.destinationViewController as! TaleModeViewController
//controller.user = self.user
let swrevealController = segue.destinationViewController as! SWRevealViewController
swrevealController.loadView()
let navigationController = swrevealController.frontViewController as! UINavigationController
let controller = navigationController.topViewController as! TaleModeViewController
controller.user = self.user
}
}
func willAcceptInvite( sender:UIButton )
{
if( NetworkWatcher.internetAvailabe )
{
print("Accepted - \(sender.tag)")
let row:Int = sender.tag
let inviteNotificationAccepted:Notification = self.notifications[row]
if( inviteNotificationAccepted.getType() == NotificationType.PlayingRoom )
{
self.user.lobby = LobbyType.Free
}
else
{
self.user.lobby = LobbyType.Tale
}
self.user.roomId = inviteNotificationAccepted.getRoomId()
self.user.acceptedRoomInvitation = true
self.user.isNarrator = false
self.notificationIdsToBeConsumed.append( inviteNotificationAccepted.getId() )
self.notifications.removeAtIndex( row )
self.notificationsTable.reloadData()
NotificationModel.removeNotificationsById( self.notificationIdsToBeConsumed, onNotificationsReady:{
if( self.user.lobby == LobbyType.Free )
{
UIView.animateWithDuration( 0.25, animations:{ [unowned self] in
self.view.alpha = 0.0
}, completion:{ [unowned self](finished:Bool) in
self.performSegueWithIdentifier( "showFreeModeView", sender:nil )
})
}
else
{
UIView.animateWithDuration( 0.25, animations:{ [unowned self] in
self.view.alpha = 0.0
}, completion:{ [unowned self](finished:Bool) in
self.performSegueWithIdentifier( "showRevealView", sender:nil )
})
}
})
}
else
{
Utils.alertMessage( self, title:Utils.localize("attention.title"), message:Utils.localize("attention.networkWarning"), onAlertClose:nil )
}
}
func willCancelInvite( sender:UIButton )
{
if( NetworkWatcher.internetAvailabe )
{
print("Removed - \(sender.tag)")
let row:Int = sender.tag
self.notificationIdsToBeConsumed.append( self.notifications[row].getId() )
self.notifications.removeAtIndex( row )
self.notificationsTable.reloadData()
if( notifications.count == 0 )
{
NotificationModel.removeNotificationsById( self.notificationIdsToBeConsumed, onNotificationsReady:{
self.dismissViewControllerAnimated( true, completion:{} )
})
}
}
else
{
Utils.alertMessage( self, title:Utils.localize("attention.title"), message:Utils.localize("attention.networkWarning"), onAlertClose:nil )
}
}
func networkStatusChanged(notification:NSNotification)
{
print("InviteNotificationsManagerViewController::networkStatusChanged was called...")
if( NetworkWatcher.internetAvailabe )
{
Utils.alertMessage( self, title:Utils.localize("notice.title"), message:Utils.localize("notice.networkWorksAgain"), onAlertClose:nil )
}
else
{
Utils.alertMessage( self, title:Utils.localize("attention.title"), message:Utils.localize("attention.networkLost"), onAlertClose:nil )
}
}
/*=============================================================*/
/* from UITableViewDataSource */
/*=============================================================*/
func numberOfSectionsInTableView(tableView:UITableView) -> Int
{
return 1
}
func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
return self.notifications.count;
}
func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier( self.cellIdentifier, forIndexPath:indexPath ) as! NotificationsTableViewCell
let row = indexPath.row
var roomType:String = Utils.localize("inviteNotificationsManagerView.costumes")
if( self.notifications[row].getType() == NotificationType.ReadingRoom )
{
roomType = Utils.localize("inviteNotificationsManagerView.tale")
}
//User information.
cell.imageView?.image = UIImage() //TODO: foto usuario??
cell.nickNameLabel.text = self.notifications[row].nickNameFrom
cell.descriptionLabel.text = String(format:Utils.localize("inviteNotificationsManagerView.invite"),roomType)
//Actions.
cell.acceptButton.addTarget( self, action:#selector(InviteNotificationsManagerViewController.willAcceptInvite(_:)), forControlEvents:.TouchUpInside )
cell.acceptButton.tag = row
cell.cancelButton.addTarget( self, action:#selector(InviteNotificationsManagerViewController.willCancelInvite(_:)), forControlEvents:.TouchUpInside )
cell.cancelButton.tag = row
return cell
}
/*=============================================================*/
/* from UITableViewDelegate */
/*=============================================================*/
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
/*=============================================================*/
/* UI Section */
/*=============================================================*/
@IBOutlet weak var bgMainImage: UIImageView!
@IBOutlet weak var leftArrowImage: UIImageView!
@IBOutlet weak var notificationsTable: UITableView!
//---------------------------------------------------------------
// UI Actions
//---------------------------------------------------------------
@IBAction func back(sender: UIButton)
{
if( self.notificationIdsToBeConsumed.count > 0 )
{
NotificationModel.removeNotificationsById( self.notificationIdsToBeConsumed, onNotificationsReady:{
self.dismissViewControllerAnimated( true, completion:{} )
})
}
else
{
self.dismissViewControllerAnimated( true, completion:{} )
}
}
/*=============================================================*/
/* Private Section */
/*=============================================================*/
private func dumpNotifications()
{
if let invitesPlayingRoom = notificationsByType[NotificationType.PlayingRoom]
{
for notification:Notification in invitesPlayingRoom
{
self.notifications.append( notification )
}
}
if let invitesReadingRoom = notificationsByType[NotificationType.ReadingRoom]
{
for notification:Notification in invitesReadingRoom
{
self.notifications.append( notification )
}
}
}
private func getNickNamesFromNotifications()
{
NotificationModel.getNickNamesFromNotifications(self.notifications) { [weak self](notifications) in
self!.notifications = notifications
self!.notificationsTable.reloadData()
}
}
private let cellIdentifier:String = "NotificationsTableViewCell"
private var notifications:[Notification] = [Notification]()
private var notificationIdsToBeConsumed:[String] = [String]()
}
| apache-2.0 | 271de60f3f36b053d5f0d795d84a054e | 37.794425 | 223 | 0.576882 | 5.966774 | false | false | false | false |
proxpero/Placeholder | Placeholder/Future.swift | 1 | 1151 | //
// Future.swift
// Placeholder
//
// Created by Todd Olsen on 4/10/17.
// Copyright © 2017 proxpero. All rights reserved.
//
public final class Future<A> {
var callbacks: [(Result<A>) -> ()] = []
var cached: Result<A>?
init(compute: (@escaping (Result<A>) -> ()) -> ()) {
compute(self.send)
}
private func send(_ value: Result<A>) {
assert(cached == nil)
cached = value
for callback in callbacks {
callback(value)
}
callbacks = []
}
func onResult(_ callback: @escaping (Result<A>) -> ()) {
if let value = cached {
callback(value)
} else {
callbacks.append(callback)
}
}
func flatMap<B>(transform: @escaping (A) -> Future<B>) -> Future<B> {
return Future<B> { completion in
self.onResult { result in
switch result {
case .success(let value):
transform(value).onResult(completion)
case .error(let error):
completion(.error(error))
}
}
}
}
}
| mit | 92f826f428e81103e3dfb6edf942b32b | 22.469388 | 73 | 0.487826 | 4.212454 | false | false | false | false |
master-nevi/UPnAtom | Source/AV Profile/Services/RenderingControl1Service.swift | 1 | 21297 | //
// RenderingControl1Service.swift
//
// Copyright (c) 2015 David Robles
//
// 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
public class RenderingControl1Service: AbstractUPnPService {
public func listPresets(instanceID instanceID: String, success: (presetNameList: [String]) -> Void, failure: (error: NSError) -> Void) {
let arguments = ["InstanceID" : instanceID]
let parameters = SOAPRequestSerializer.Parameters(soapAction: "ListPresets", serviceURN: urn, arguments: arguments)
soapSessionManager.POST(self.controlURL.absoluteString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
let responseObject = responseObject as? [String: String]
success(presetNameList: responseObject?["CurrentPresetNameList"]?.componentsSeparatedByString(",") ?? [String]())
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error: error)
})
}
public func selectPreset(instanceID instanceID: String, presetName: String, success: () -> Void, failure:(error: NSError) -> Void) {
let arguments = [
"InstanceID" : instanceID,
"PresetName" : presetName]
let parameters = SOAPRequestSerializer.Parameters(soapAction: "SelectPreset", serviceURN: urn, arguments: arguments)
soapSessionManager.POST(controlURL.absoluteString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
success()
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error: error)
})
}
public func getBrightness(instanceID instanceID: String, success: (brightness: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "Brightness", success: { (stateVariableValue: String?) -> Void in
success(brightness: stateVariableValue)
}, failure: failure)
}
public func setBrightness(instanceID instanceID: String, brightness: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "Brightness", stateVariableValue: brightness, success: success, failure: failure)
}
public func getContrast(instanceID instanceID: String, success: (contrast: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "Contrast", success: { (stateVariableValue: String?) -> Void in
success(contrast: stateVariableValue)
}, failure: failure)
}
public func setContrast(instanceID instanceID: String, contrast: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "Contrast", stateVariableValue: contrast, success: success, failure: failure)
}
public func getSharpness(instanceID instanceID: String, success: (sharpness: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "Sharpness", success: { (stateVariableValue: String?) -> Void in
success(sharpness: stateVariableValue)
}, failure: failure)
}
public func setSharpness(instanceID instanceID: String, sharpness: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "Sharpness", stateVariableValue: sharpness, success: success, failure: failure)
}
public func getRedVideoGain(instanceID instanceID: String, success: (redVideoGain: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "RedVideoGain", success: { (stateVariableValue: String?) -> Void in
success(redVideoGain: stateVariableValue)
}, failure: failure)
}
public func setRedVideoGain(instanceID instanceID: String, redVideoGain: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "RedVideoGain", stateVariableValue: redVideoGain, success: success, failure: failure)
}
public func getGreenVideoGain(instanceID instanceID: String, success: (greenVideoGain: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "GreenVideoGain", success: { (stateVariableValue: String?) -> Void in
success(greenVideoGain: stateVariableValue)
}, failure: failure)
}
public func setGreenVideoGain(instanceID instanceID: String, greenVideoGain: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "GreenVideoGain", stateVariableValue: greenVideoGain, success: success, failure: failure)
}
public func getBlueVideoGain(instanceID instanceID: String, success: (blueVideoGain: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "BlueVideoGain", success: { (stateVariableValue: String?) -> Void in
success(blueVideoGain: stateVariableValue)
}, failure: failure)
}
public func setBlueVideoGain(instanceID instanceID: String, blueVideoGain: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "BlueVideoGain", stateVariableValue: blueVideoGain, success: success, failure: failure)
}
public func getRedVideoBlackLevel(instanceID instanceID: String, success: (redVideoBlackLevel: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "RedVideoBlackLevel", success: { (stateVariableValue: String?) -> Void in
success(redVideoBlackLevel: stateVariableValue)
}, failure: failure)
}
public func setRedVideoBlackLevel(instanceID instanceID: String, redVideoBlackLevel: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "RedVideoBlackLevel", stateVariableValue: redVideoBlackLevel, success: success, failure: failure)
}
public func getGreenVideoBlackLevel(instanceID instanceID: String, success: (greenVideoBlackLevel: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "GreenVideoBlackLevel", success: { (stateVariableValue: String?) -> Void in
success(greenVideoBlackLevel: stateVariableValue)
}, failure: failure)
}
public func setGreenVideoBlackLevel(instanceID instanceID: String, greenVideoBlackLevel: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "GreenVideoBlackLevel", stateVariableValue: greenVideoBlackLevel, success: success, failure: failure)
}
public func getBlueVideoBlackLevel(instanceID instanceID: String, success: (blueVideoBlackLevel: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "BlueVideoBlackLevel", success: { (stateVariableValue: String?) -> Void in
success(blueVideoBlackLevel: stateVariableValue)
}, failure: failure)
}
public func setBlueVideoBlackLevel(instanceID instanceID: String, blueVideoBlackLevel: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "BlueVideoBlackLevel", stateVariableValue: blueVideoBlackLevel, success: success, failure: failure)
}
public func getColorTemperature(instanceID instanceID: String, success: (colorTemperature: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "ColorTemperature", success: { (stateVariableValue: String?) -> Void in
success(colorTemperature: stateVariableValue)
}, failure: failure)
}
public func setColorTemperature(instanceID instanceID: String, colorTemperature: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "ColorTemperature", stateVariableValue: colorTemperature, success: success, failure: failure)
}
public func getHorizontalKeystone(instanceID instanceID: String, success: (horizontalKeystone: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "HorizontalKeystone", success: { (stateVariableValue: String?) -> Void in
success(horizontalKeystone: stateVariableValue)
}, failure: failure)
}
public func setHorizontalKeystone(instanceID instanceID: String, horizontalKeystone: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "HorizontalKeystone", stateVariableValue: horizontalKeystone, success: success, failure: failure)
}
public func getVerticalKeystone(instanceID instanceID: String, success: (verticalKeystone: String?) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "VerticalKeystone", success: { (stateVariableValue: String?) -> Void in
success(verticalKeystone: stateVariableValue)
}, failure: failure)
}
public func setVerticalKeystone(instanceID instanceID: String, verticalKeystone: String, success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "VerticalKeystone", stateVariableValue: verticalKeystone, success: success, failure: failure)
}
public func getMute(instanceID instanceID: String, channel: String = "Master", success: (mute: Bool) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "Mute", additionalArguments: ["Channel" : channel], isOptional: false, success: { (stateVariableValue: String?) -> Void in
success(mute: (stateVariableValue ?? "0") == "0" ? false : true)
}, failure: failure)
}
public func setMute(instanceID instanceID: String, mute: Bool, channel: String = "Master", success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "Mute", stateVariableValue: mute ? "1" : "0", additionalArguments: ["Channel" : channel], isOptional: false, success: success, failure: failure)
}
public func getVolume(instanceID instanceID: String, channel: String = "Master", success: (volume: Int) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "Volume", additionalArguments: ["Channel" : channel], success: { (stateVariableValue: String?) -> Void in
success(volume: Int(String(stateVariableValue)) ?? 0)
}, failure: failure)
}
public func setVolume(instanceID instanceID: String, volume: Int, channel: String = "Master", success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "Volume", stateVariableValue: "\(volume)", additionalArguments: ["Channel" : channel], success: success, failure: failure)
}
public func getVolumeDB(instanceID instanceID: String, channel: String = "Master", success: (volumeDB: Int) -> Void, failure:(error: NSError) -> Void) {
let arguments = [
"InstanceID" : instanceID,
"Channel" : channel]
let parameters = SOAPRequestSerializer.Parameters(soapAction: "GetVolumeDB", serviceURN: urn, arguments: arguments)
// Check if the optional SOAP action "GetVolumeDB" is supported
supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in
if isSupported {
self.soapSessionManager.POST(self.controlURL.absoluteString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
let responseObject = responseObject as? [String: String]
success(volumeDB: Int(String(responseObject?["CurrentVolume"])) ?? 0)
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error: error)
})
} else {
failure(error: createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)"))
}
}
}
public func setVolumeDB(instanceID instanceID: String, volumeDB: Int, channel: String = "Master", success: () -> Void, failure:(error: NSError) -> Void) {
let arguments = [
"InstanceID" : instanceID,
"Channel" : channel,
"DesiredVolume" : "\(volumeDB)"]
let parameters = SOAPRequestSerializer.Parameters(soapAction: "SetVolumeDB", serviceURN: urn, arguments: arguments)
// Check if the optional SOAP action "SetVolumeDB" is supported
supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in
if isSupported {
self.soapSessionManager.POST(self.controlURL.absoluteString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
success()
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error: error)
})
} else {
failure(error: createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)"))
}
}
}
public func getVolumeDBRange(instanceID instanceID: String, channel: String = "Master", success: (minimumValue: Int, maximumValue: Int) -> Void, failure:(error: NSError) -> Void) {
let arguments = [
"InstanceID" : instanceID,
"Channel" : channel]
let parameters = SOAPRequestSerializer.Parameters(soapAction: "GetVolumeDBRange", serviceURN: urn, arguments: arguments)
// Check if the optional SOAP action "getVolumeDBRange" is supported
supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in
if isSupported {
self.soapSessionManager.POST(self.controlURL.absoluteString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
let responseObject = responseObject as? [String: String]
success(minimumValue: Int(String(responseObject?["MinValue"])) ?? 0, maximumValue: Int(String(responseObject?["MaxValue"])) ?? 0)
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error: error)
})
} else {
failure(error: createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)"))
}
}
}
public func getLoudness(instanceID instanceID: String, channel: String = "Master", success: (loudness: Bool) -> Void, failure:(error: NSError) -> Void) {
getStateVariable(instanceID: instanceID, stateVariableName: "Loudness", additionalArguments: ["Channel" : channel], isOptional: false, success: { (stateVariableValue: String?) -> Void in
success(loudness: (stateVariableValue ?? "0") == "0" ? false : true)
}, failure: failure)
}
public func setLoudness(instanceID instanceID: String, loudness: Bool, channel: String = "Master", success: () -> Void, failure:(error: NSError) -> Void) {
setStateVariable(instanceID: instanceID, stateVariableName: "Loudness", stateVariableValue: loudness ? "1" : "0", additionalArguments: ["Channel" : channel], isOptional: false, success: success, failure: failure)
}
private func getStateVariable(instanceID instanceID: String, stateVariableName: String, additionalArguments: [String: String] = [String: String](), isOptional: Bool = true, success: (stateVariableValue: String?) -> Void, failure:(error: NSError) -> Void) {
let arguments = ["InstanceID" : instanceID] + additionalArguments
let parameters = SOAPRequestSerializer.Parameters(soapAction: "Get\(stateVariableName)", serviceURN: urn, arguments: arguments)
let performAction = { () -> Void in
self.soapSessionManager.POST(self.controlURL.absoluteString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
let responseObject = responseObject as? [String: String]
success(stateVariableValue: responseObject?["Current\(stateVariableName)"])
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error: error)
})
}
if isOptional {
// Check if the optional SOAP action "Get<stateVariableName>" is supported
supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in
if isSupported {
performAction()
} else {
failure(error: createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)"))
}
}
} else {
performAction()
}
}
private func setStateVariable(instanceID instanceID: String, stateVariableName: String, stateVariableValue: String, additionalArguments: [String: String] = [String: String](), isOptional: Bool = true, success: () -> Void, failure:(error: NSError) -> Void) {
let arguments = [
"InstanceID" : instanceID,
"Desired\(stateVariableName)" : stateVariableValue] +
additionalArguments
let parameters = SOAPRequestSerializer.Parameters(soapAction: "Set\(stateVariableName)", serviceURN: urn, arguments: arguments)
let performAction = { () -> Void in
self.soapSessionManager.POST(self.controlURL.absoluteString, parameters: parameters, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
success()
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error: error)
})
}
if isOptional {
// Check if the optional SOAP action "Set<stateVariableName>" is supported
supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in
if isSupported {
performAction()
} else {
failure(error: createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)"))
}
}
} else {
performAction()
}
}
}
/// for objective-c type checking
extension AbstractUPnP {
public func isRenderingControl1Service() -> Bool {
return self is RenderingControl1Service
}
}
/// overrides ExtendedPrintable protocol implementations
extension RenderingControl1Service {
override public var className: String { return "\(self.dynamicType)" }
override public var description: String {
var properties = PropertyPrinter()
properties.add(super.className, property: super.description)
return properties.description
}
}
| mit | f5b009444b0ed4774e62535e66c530cd | 60.909884 | 261 | 0.672254 | 4.786918 | false | false | false | false |
ReactiveSprint/ReactiveSprint-Swift | Example/Tests/SignalManipulationSpec.swift | 1 | 11218 | //
// SignalManipulationSpec.swift
// ReactiveSprint
//
// Created by Ahmad Baraka on 2/28/16.
// Copyright © 2016 ReactiveSprint. All rights reserved.
//
import Quick
import Nimble
import ReactiveCocoa
import Result
import ReactiveSprint
class SignalManipulationSpec: QuickSpec {
override func spec() {
var viewModel: ViewModel!
beforeEach {
viewModel = ViewModel(title: "TestViewModel")
}
///
/// Original `active` implementation and tests from
/// [ReactiveViewModel.](https://github.com/ReactiveCocoa/ReactiveViewModel)
///
describe("active property") {
it("should default to false") {
expect(viewModel.active.value) == false
}
it("should send on didBecomeActive when set to true") {
var nextEvents = 0
viewModel.didBecomeActive.startWithNext { viewModel2 in
expect(viewModel2) === viewModel
expect(viewModel.active.value) == true
nextEvents += 1
}
expect(nextEvents) == 0
viewModel.active.value = true
expect(nextEvents) == 1
// Indistinct changes should not trigger the signal again.
viewModel.active.value = true
expect(nextEvents) == 1
viewModel.active.value = false
viewModel.active.value = true
expect(nextEvents) == 2
}
it("should send on didBecomeInactive when set to false") {
var nextEvents = 0
viewModel.didBecomeInActive.startWithNext { viewModel2 in
expect(viewModel2) === viewModel
expect(viewModel.active.value) == false
nextEvents += 1
}
expect(nextEvents) == 1
viewModel.active.value = true
viewModel.active.value = false
expect(nextEvents) == 2
// Indistinct changes should not trigger the signal again.
viewModel.active.value = false
expect(nextEvents) == 2
}
context("SignalProducer forwarding") {
var values: [Int]!
var expectedValues: [Int]!
var completed = false
beforeEach {
values = [Int]()
viewModel.active.value = true
}
afterEach {
viewModel = nil
expect(completed).toEventually(beTrue())
}
it("should forward SignalProducer") {
let signal = SignalProducer<Int, NoError> { (observer, disposable) in
observer.sendNext(1)
observer.sendNext(2)
}
signal.forwardWhileActive(viewModel)
.start(Observer(failed: nil,
completed: { completed = true },
interrupted: nil,
next: { values.append($0) }))
expectedValues = [1, 2]
expect(values).toEventually(equal(expectedValues))
expect(completed) == false
viewModel.active.value = false
expect(values).toEventually(equal(expectedValues))
expect(completed) == false
viewModel.active.value = true
expectedValues = [1, 2, 1, 2]
expect(values).toEventually(equal(expectedValues))
expect(completed) == false
}
}
context("SignalProducer throttling") {
var values: [Int]!
var expectedValues: [Int]!
var completed = false
beforeEach {
values = [Int]()
viewModel.active.value = true
}
afterEach {
viewModel = nil
expect(completed).toEventually(beTrue())
}
it("should throttle SignalProducer") {
let (signal, observer) = SignalProducer<Int, NoError>.buffer(1)
signal.throttleWhileInactive(viewModel, interval: 1, onScheduler: QueueScheduler.mainQueueScheduler)
.start(Observer(failed: nil,
completed: { completed = true },
interrupted: nil,
next: {
values.append($0) }))
observer.sendNext(1)
expectedValues = [1]
expect(values) == expectedValues
expect(completed) == false
viewModel.active.value = false
observer.sendNext(2)
observer.sendNext(3)
expect(values) == expectedValues
expect(completed) == false
expectedValues = [1, 3]
expect(values).toEventually(equal(expectedValues), timeout: 2)
expect(completed) == false
// After reactivating, we should still get this event.
observer.sendNext(4)
viewModel.active.value = true
expectedValues = [1, 3, 4]
expect(values) == expectedValues
expect(completed) == false
// And now new events should be instant.
observer.sendNext(5)
expectedValues = [1, 3, 4, 5]
expect(values) == expectedValues
expect(completed) == false
observer.sendCompleted()
expect(values) == expectedValues
expect(completed) == true
}
}
context("Signal manipulation") {
var values: [Int]!
var expectedValues: [Int]!
var completed = false
beforeEach {
values = [Int]()
viewModel.active.value = true
}
afterEach {
viewModel = nil
expect(completed).toEventually(beTrue())
}
it("should forward signal") {
let (signal, observer) = Signal<Int, NoError>.pipe()
signal.forwardWhileActive(viewModel)
.observe(Observer(failed: nil,
completed: { completed = true },
interrupted: nil,
next: { values.append($0) }))
observer.sendNext(1)
observer.sendNext(2)
expectedValues = [1, 2]
expect(values).toEventually(equal(expectedValues))
expect(completed) == false
viewModel.active.value = false
observer.sendNext(1)
expect(values).toEventually(equal(expectedValues))
expect(completed) == false
viewModel.active.value = true
observer.sendNext(1)
observer.sendNext(2)
expectedValues = [1, 2, 1, 2]
expect(values).toEventually(equal(expectedValues))
expect(completed) == false
}
}
context("Signal throttling") {
var values: [Int]!
var expectedValues: [Int]!
var completed = false
beforeEach {
values = [Int]()
viewModel.active.value = true
}
afterEach {
viewModel = nil
expect(completed).toEventually(beTrue())
}
it("should throttle Signal") {
let (signal, observer) = Signal<Int, NoError>.pipe()
signal.throttleWhileInactive(viewModel, interval: 1, onScheduler: QueueScheduler.mainQueueScheduler)
.observe(Observer(failed: nil,
completed: { completed = true },
interrupted: nil,
next: { values.append($0) }))
observer.sendNext(1)
expectedValues = [1]
expect(values) == expectedValues
expect(completed) == false
viewModel.active.value = false
observer.sendNext(2)
observer.sendNext(3)
expect(values) == expectedValues
expect(completed) == false
expectedValues = [1, 3]
expect(values).toEventually(equal(expectedValues), timeout: 2)
expect(completed) == false
// After reactivating, we should still get this event.
observer.sendNext(4)
viewModel.active.value = true
expectedValues = [1, 3, 4]
expect(values) == expectedValues
expect(completed) == false
// And now new events should be instant.
observer.sendNext(5)
expectedValues = [1, 3, 4, 5]
expect(values) == expectedValues
expect(completed) == false
observer.sendCompleted()
expect(values) == expectedValues
expect(completed) == true
}
}
}
}
}
| mit | 690553bcf2f509df7110d0381a559e59 | 36.51505 | 120 | 0.40822 | 6.839634 | false | false | false | false |
dclelland/AudioKit | AudioKit/Common/Instruments/AKNoiseGenerator.swift | 1 | 4180 | //
// AKNoiseGenerator.swift
// AudioKit
//
// Created by Jeff Cooper, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
import AVFoundation
/// Noise generator that can be played polyphonically as a mix of pink and white noise
public class AKNoiseGenerator: AKPolyphonicInstrument {
/// Balance of white to pink noise
public var whitePinkMix: Double = 0 {
didSet {
for noiseVoice in voices as! [AKNoiseVoice] {
noiseVoice.whitePinkMix = whitePinkMix
}
}
}
/// Attack time
public var attackDuration: Double = 0.1 {
didSet {
for noiseVoice in voices as! [AKNoiseVoice] {
noiseVoice.adsr.attackDuration = attackDuration
}
}
}
/// Decay time
public var decayDuration: Double = 0.1 {
didSet {
for noiseVoice in voices as! [AKNoiseVoice] {
noiseVoice.adsr.decayDuration = decayDuration
}
}
}
/// Sustain Level
public var sustainLevel: Double = 0.66 {
didSet {
for noiseVoice in voices as! [AKNoiseVoice] {
noiseVoice.adsr.sustainLevel = sustainLevel
}
}
}
/// Release time
public var releaseDuration: Double = 0.5 {
didSet {
for noiseVoice in voices as! [AKNoiseVoice] {
noiseVoice.adsr.releaseDuration = releaseDuration
}
}
}
/// Initial the noise generator instrument
///
/// - parameter whitePinkMix: Balance of white to pink noise
/// - parameter voiceCount: Maximum number of simultaneous voices
///
public init(whitePinkMix: Double, voiceCount: Int) {
super.init(voice: AKNoiseVoice(whitePinkMix: whitePinkMix), voiceCount: voiceCount)
}
/// Start playback of a particular voice with MIDI style note and velocity
///
/// - parameter voice: Voice to start
/// - parameter note: MIDI Note Number
/// - parameter velocity: MIDI Velocity (0-127)
///
override internal func playVoice(voice: AKVoice, note: Int, velocity: Int) {
let noiseVoice = voice as! AKNoiseVoice
noiseVoice.whiteNoise.amplitude = Double(velocity) / 127.0
noiseVoice.pinkNoise.amplitude = Double(velocity) / 127.0
noiseVoice.start()
}
/// Stop playback of a particular voice
///
/// - parameter voice: Voice to stop
/// - parameter note: MIDI Note Number
///
override internal func stopVoice(voice: AKVoice, note: Int) {
let noise = voice as! AKNoiseVoice
noise.stop()
}
}
internal class AKNoiseVoice: AKVoice {
var whiteNoise: AKWhiteNoise
var pinkNoise: AKPinkNoise
var noiseMix: AKDryWetMixer
var adsr: AKAmplitudeEnvelope
var whitePinkMix: Double = 0 {
didSet {
noiseMix.balance = whitePinkMix
}
}
init(whitePinkMix: Double) {
whiteNoise = AKWhiteNoise()
pinkNoise = AKPinkNoise()
noiseMix = AKDryWetMixer(whiteNoise, pinkNoise, balance: whitePinkMix)
adsr = AKAmplitudeEnvelope(noiseMix,
attackDuration: 0.2,
decayDuration: 0.2,
sustainLevel: 0.8,
releaseDuration: 1.0)
self.whitePinkMix = whitePinkMix
super.init()
avAudioNode = adsr.avAudioNode
}
/// Function create an identical new node for use in creating polyphonic instruments
override func duplicate() -> AKVoice {
let copy = AKNoiseVoice(whitePinkMix: whitePinkMix)
return copy
}
/// Tells whether the node is processing (ie. started, playing, or active)
override var isStarted: Bool {
return whiteNoise.isPlaying
}
/// Function to start, play, or activate the node, all do the same thing
override func start() {
whiteNoise.start()
pinkNoise.start()
adsr.start()
}
/// Function to stop or bypass the node, both are equivalent
override func stop() {
adsr.stop()
}
}
| mit | 2a74aab9184366501788e5478f65864d | 28.638298 | 91 | 0.605408 | 4.567213 | false | false | false | false |
mpurland/SwiftCheck | SwiftCheck/Gen.swift | 1 | 13670 | //
// Gen.swift
// SwiftCheck
//
// Created by Robert Widmann on 7/31/14.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
/// `Gen` represents a generator for random arbitrary values of type `A`.
///
/// `Gen` wraps a function that, when given a random number generator and a size, can be used to
/// control the distribution of resultant values. A generator relies on its size to help control
/// aspects like the length of generated arrays and the magnitude of integral values.
public struct Gen<A> {
/// The function underlying the receiver.
///
/// +--- An RNG
/// | +--- The size of generated values.
/// | |
/// v v
let unGen : StdGen -> Int -> A
/// Generates a value.
///
/// This method exists as a convenience mostly to test generators. It will always generate with
/// size 30.
public var generate : A {
let r = newStdGen()
return unGen(r)(30)
}
/// Constructs a Generator that selects a random value from the given collection and produces
/// only that value.
///
/// The input collection is required to be non-empty.
public static func fromElementsOf<S : Indexable where S.Index : protocol<Comparable, RandomType>>(xs : S) -> Gen<S._Element> {
return Gen.fromElementsIn(xs.startIndex...xs.endIndex.advancedBy(-1)).fmap { i in
return xs[i]
}
}
/// Constructs a Generator that selects a random value from the given interval and produces only
/// that value.
///
/// The input interval is required to be non-empty.
public static func fromElementsIn<S : IntervalType where S.Bound : RandomType>(xs : S) -> Gen<S.Bound> {
assert(!xs.isEmpty, "Gen.fromElementsOf used with empty interval")
return choose((xs.start, xs.end))
}
/// Constructs a Generator that uses a given array to produce smaller arrays composed of its
/// initial segments. The size of each initial segment increases with the receiver's size
/// parameter.
///
/// The input array is required to be non-empty.
public static func fromInitialSegmentsOf<S>(xs : [S]) -> Gen<[S]> {
assert(!xs.isEmpty, "Gen.fromInitialSegmentsOf used with empty list")
return Gen<[S]>.sized { n in
let ss = xs[xs.startIndex..<max(xs.startIndex.successor(), size(xs.endIndex)(m: n))]
return Gen<[S]>.pure([S](ss))
}
}
/// Constructs a Generator that produces permutations of a given array.
public static func fromShufflingElementsOf<S>(xs : [S]) -> Gen<[S]> {
if xs.isEmpty {
return Gen<[S]>.pure([])
}
return Gen<(S, [S])>.fromElementsOf(selectOne(xs)).bind { (y, ys) in
return Gen.fromShufflingElementsOf(ys).fmap { [y] + $0 }
}
}
/// Constructs a generator that depends on a size parameter.
public static func sized(f : Int -> Gen<A>) -> Gen<A> {
return Gen(unGen: { r in
return { n in
return f(n).unGen(r)(n)
}
})
}
/// Constructs a random element in the range of two `RandomType`s.
///
/// When using this function, it is necessary to explicitly specialize the generic parameter
/// `A`. For example:
///
/// Gen<UInt32>.choose((32, 255)) >>- (Gen<Character>.pure • Character.init • UnicodeScalar.init)
public static func choose<A : RandomType>(rng : (A, A)) -> Gen<A> {
return Gen<A>(unGen: { s in
return { (_) in
let (x, _) = A.randomInRange(rng, gen: s)
return x
}
})
}
/// Constructs a Generator that randomly selects and uses a particular generator from the given
/// sequence of Generators.
///
/// If control over the distribution of generators is needed, see `Gen.frequency` or
/// `Gen.weighted`.
public static func oneOf<S : CollectionType where S.Generator.Element == Gen<A>, S.Index : protocol<RandomType, BidirectionalIndexType>>(gs : S) -> Gen<A> {
assert(gs.count != 0, "oneOf used with empty list")
return choose((gs.indices.startIndex, gs.indices.endIndex.predecessor())) >>- { x in
return gs[x]
}
}
/// Given a sequence of Generators and weights associated with them, this function randomly
/// selects and uses a Generator.
///
/// Only use this function when you need to assign uneven "weights" to each generator. If all
/// generators need to have an equal chance of being selected, use `Gen.oneOf`.
public static func frequency<S : SequenceType where S.Generator.Element == (Int, Gen<A>)>(xs : S) -> Gen<A> {
let xs: [(Int, Gen<A>)] = Array(xs)
assert(xs.count != 0, "frequency used with empty list")
return choose((1, xs.map({ $0.0 }).reduce(0, combine: +))).bind { l in
return pick(l)(lst: xs)
}
}
/// Given a list of values and weights associated with them, this function randomly selects and
/// uses a Generator wrapping one of the values.
///
/// This function operates in exactly the same manner as `Gen.frequency`, `Gen.fromElementsOf`,
/// and `Gen.fromElementsIn` but for any type rather than only Generators. It can help in cases
/// where your `Gen.from*` call contains only `Gen.pure` calls by allowing you to remove every
/// `.pure` in favor of a direct list of values.
public static func weighted<S : SequenceType where S.Generator.Element == (Int, A)>(xs : S) -> Gen<A> {
return frequency(xs.map { ($0, Gen.pure($1)) })
}
/// Zips together 2 generators of type `A` and `B` into a generator of pairs `(A, B)`.
public static func zip<A, B>(gen1 : Gen<A>, _ gen2 : Gen<B>) -> Gen<(A, B)> {
return gen1.bind { l in
return gen2.bind { r in
return Gen<(A, B)>.pure((l, r))
}
}
}
}
/// MARK: Generator Modifiers
extension Gen {
/// Shakes up the receiver's internal Random Number Generator with a seed.
public func variant<S : IntegerType>(seed : S) -> Gen<A> {
return Gen(unGen: { r in
return { n in
return self.unGen(vary(seed)(r: r))(n)
}
})
}
/// Modifies a Generator to always use a given size.
public func resize(n : Int) -> Gen<A> {
return Gen(unGen: { r in
return { (_) in
return self.unGen(r)(n)
}
})
}
/// Modifies a Generator such that it only returns values that satisfy a predicate. When the
/// predicate fails the test case is treated as though it never occured.
///
/// Because the Generator will spin until it reaches a non-failing case, executing a condition
/// that fails more often than it succeeds may result in a space leak. At that point, it is
/// better to use `suchThatOptional` or `.invert` the test case.
public func suchThat(p : A -> Bool) -> Gen<A> {
return self.suchThatOptional(p).bind { mx in
switch mx {
case .Some(let x):
return Gen.pure(x)
case .None:
return Gen.sized { n in
return self.suchThat(p).resize(n.successor())
}
}
}
}
/// Modifies a Generator such that it attempts to generate values that satisfy a predicate. All
/// attempts are encoded in the form of an `Optional` where values satisfying the predicate are
/// wrapped in `.Some` and failing values are `.None`.
public func suchThatOptional(p : A -> Bool) -> Gen<Optional<A>> {
return Gen<Optional<A>>.sized { n in
return attemptBoundedTry(self, k: 0, n: max(n, 1), p: p)
}
}
/// Modifies a Generator such that it produces arrays with a length determined by the receiver's
/// size parameter.
public func proliferate() -> Gen<[A]> {
return Gen<[A]>.sized { n in
return Gen.choose((0, n)) >>- self.proliferateSized
}
}
/// Modifies a Generator such that it produces non-empty arrays with a length determined by the
/// receiver's size parameter.
public func proliferateNonEmpty() -> Gen<[A]> {
return Gen<[A]>.sized { n in
return Gen.choose((1, max(1, n))) >>- self.proliferateSized
}
}
/// Modifies a Generator such that it only produces arrays of a given length.
public func proliferateSized(k : Int) -> Gen<[A]> {
return sequence(Array<Gen<A>>(count: k, repeatedValue: self))
}
}
/// MARK: Instances
extension Gen /*: Functor*/ {
typealias B = Swift.Any
/// Returns a new generator that applies a given function to any outputs the receiver creates.
public func fmap<B>(f : (A -> B)) -> Gen<B> {
return f <^> self
}
}
/// Fmap | Returns a new generator that applies a given function to any outputs the given generator
/// creates.
///
/// This function is most useful for converting between generators of inter-related types. For
/// example, you might have a Generator of `Character` values that you then `.proliferate()` into an
/// `Array` of `Character`s. You can then use `fmap` to convert that generator of `Array`s to a
/// generator of `String`s.
public func <^> <A, B>(f : A -> B, g : Gen<A>) -> Gen<B> {
return Gen(unGen: { r in
return { n in
return f(g.unGen(r)(n))
}
})
}
extension Gen /*: Applicative*/ {
typealias FAB = Gen<A -> B>
/// Lifts a value into a generator that will only generate that value.
public static func pure(a : A) -> Gen<A> {
return Gen(unGen: { (_) in
return { (_) in
return a
}
})
}
/// Given a generator of functions, applies any generated function to any outputs the receiver
/// creates.
public func ap<B>(fn : Gen<A -> B>) -> Gen<B> {
return fn <*> self
}
}
/// Ap | Returns a Generator that uses the first given Generator to produce functions and the second
/// given Generator to produce values that it applies to those functions. It can be used in
/// conjunction with <^> to simplify the application of "combining" functions to a large amount of
/// sub-generators. For example:
///
/// struct Foo { let b : Int; let c : Int; let d : Int }
///
/// let genFoo = curry(Foo.init) <^> Int.arbitrary <*> Int.arbitrary <*> Int.arbitrary
///
/// This combinator acts like `zip`, but instead of creating pairs it creates values after applying
/// the zipped function to the zipped value.
///
/// Promotes function application to a Generator of functions applied to a Generator of values.
public func <*> <A, B>(fn : Gen<A -> B>, g : Gen<A>) -> Gen<B> {
return fn >>- { x1 in
return g >>- { x2 in
return Gen.pure(x1(x2))
}
}
}
extension Gen /*: Monad*/ {
/// Applies the function to any generated values to yield a new generator. This generator is
/// then given a new random seed and returned.
///
/// `bind` allows for the creation of Generators that depend on other generators. One might,
/// for example, use a Generator of integers to control the length of a Generator of strings, or
/// use it to choose a random index into a Generator of arrays.
public func bind<B>(fn : A -> Gen<B>) -> Gen<B> {
return self >>- fn
}
}
/// Applies the function to any generated values to yield a new generator. This generator is
/// then given a new random seed and returned.
///
/// `bind` allows for the creation of Generators that depend on other generators. One might,
/// for example, use a Generator of integers to control the length of a Generator of strings, or
/// use it to choose a random index into a Generator of arrays.
public func >>- <A, B>(m : Gen<A>, fn : A -> Gen<B>) -> Gen<B> {
return Gen(unGen: { r in
return { n in
let (r1, r2) = r.split
let m2 = fn(m.unGen(r1)(n))
return m2.unGen(r2)(n)
}
})
}
/// Creates and returns a Generator of arrays of values drawn from each generator in the given
/// array.
///
/// The array that is created is guaranteed to use each of the given Generators in the order they
/// were given to the function exactly once. Thus all arrays generated are of the same rank as the
/// array that was given.
public func sequence<A>(ms : [Gen<A>]) -> Gen<[A]> {
return ms.reduce(Gen<[A]>.pure([]), combine: { y, x in
return x.bind { x1 in
return y.bind { xs in
return Gen<[A]>.pure([x1] + xs)
}
}
})
}
/// Flattens a generator of generators by one level.
public func join<A>(rs : Gen<Gen<A>>) -> Gen<A> {
return rs.bind { x in
return x
}
}
/// Lifts a function from some A to some R to a function from generators of A to generators of R.
public func liftM<A, R>(f : A -> R)(m1 : Gen<A>) -> Gen<R> {
return m1.bind{ x1 in
return Gen.pure(f(x1))
}
}
/// Promotes a rose of generators to a generator of rose values.
public func promote<A>(x : Rose<Gen<A>>) -> Gen<Rose<A>> {
return delay().bind { (let eval : Gen<A> -> A) in
return Gen<Rose<A>>.pure(liftM(eval)(m1: x))
}
}
/// Promotes a function returning generators to a generator of functions.
public func promote<A, B>(m : A -> Gen<B>) -> Gen<A -> B> {
return delay().bind { (let eval : Gen<B> -> B) in
return Gen<A -> B>.pure({ x in eval(m(x)) })
}
}
internal func delay<A>() -> Gen<Gen<A> -> A> {
return Gen(unGen: { r in
return { n in
return { g in
return g.unGen(r)(n)
}
}
})
}
/// MARK: - Implementation Details
import func Darwin.log
private func vary<S : IntegerType>(k : S)(r : StdGen) -> StdGen {
let s = r.split
let gen = ((k % 2) == 0) ? s.0 : s.1
return (k == (k / 2)) ? gen : vary(k / 2)(r: r)
}
private func attemptBoundedTry<A>(gen: Gen<A>, k : Int, n : Int, p: A -> Bool) -> Gen<Optional<A>> {
if n == 0 {
return Gen.pure(.None)
}
return gen.resize(2 * k + n).bind { (let x : A) -> Gen<Optional<A>> in
if p(x) {
return Gen.pure(.Some(x))
}
return attemptBoundedTry(gen, k: k.successor(), n: n - 1, p: p)
}
}
private func size<S : IntegerType>(k : S)(m : Int) -> Int {
let n = Double(m)
return Int((log(n + 1)) * Double(k.toIntMax()) / log(100))
}
private func selectOne<A>(xs : [A]) -> [(A, [A])] {
if xs.isEmpty {
return []
}
let y = xs.first!
let ys = Array(xs[1..<xs.endIndex])
return [(y, ys)] + selectOne(ys).map({ t in (t.0, [y] + t.1) })
}
private func pick<A>(n : Int)(lst : [(Int, Gen<A>)]) -> Gen<A> {
let (k, x) = lst[0]
let tl = Array<(Int, Gen<A>)>(lst[1..<lst.count])
if n <= k {
return x
}
return pick(n - k)(lst: tl)
}
| mit | 0962e7431966defc925b79470a3b800d | 32.250608 | 157 | 0.649349 | 3.239156 | false | false | false | false |
abertelrud/swift-package-manager | Sources/Basics/Observability.swift | 2 | 21531 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 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
//
//===----------------------------------------------------------------------===//
import Dispatch
import Foundation
import TSCBasic
import enum TSCUtility.Diagnostics
import protocol TSCUtility.DiagnosticDataConvertible
// this could become a struct when we remove the "errorsReported" pattern
// designed after https://github.com/apple/swift-log
// designed after https://github.com/apple/swift-metrics
// designed after https://github.com/apple/swift-distributed-tracing-baggage
public class ObservabilitySystem {
public let topScope: ObservabilityScope
/// Create an ObservabilitySystem with a handler provider providing handler such as a collector.
public init(_ handlerProvider: ObservabilityHandlerProvider) {
self.topScope = .init(
description: "top scope",
parent: .none,
metadata: .none,
diagnosticsHandler: handlerProvider.diagnosticsHandler
)
}
/// Create an ObservabilitySystem with a single diagnostics handler.
public convenience init(_ handler: @escaping (ObservabilityScope, Diagnostic) -> Void) {
self.init(SingleDiagnosticsHandler(handler))
}
private struct SingleDiagnosticsHandler: ObservabilityHandlerProvider, DiagnosticsHandler {
var diagnosticsHandler: DiagnosticsHandler { self }
let underlying: (ObservabilityScope, Diagnostic) -> Void
init(_ underlying: @escaping (ObservabilityScope, Diagnostic) -> Void) {
self.underlying = underlying
}
func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic) {
self.underlying(scope, diagnostic)
}
}
}
public protocol ObservabilityHandlerProvider {
var diagnosticsHandler: DiagnosticsHandler { get }
}
// MARK: - ObservabilityScope
public final class ObservabilityScope: DiagnosticsEmitterProtocol, CustomStringConvertible {
public let description: String
private let parent: ObservabilityScope?
private let metadata: ObservabilityMetadata?
private var diagnosticsHandler: DiagnosticsHandlerWrapper
fileprivate init(
description: String,
parent: ObservabilityScope?,
metadata: ObservabilityMetadata?,
diagnosticsHandler: DiagnosticsHandler
) {
self.description = description
self.parent = parent
self.metadata = metadata
self.diagnosticsHandler = DiagnosticsHandlerWrapper(diagnosticsHandler)
}
public func makeChildScope(description: String, metadata: ObservabilityMetadata? = .none) -> Self {
let mergedMetadata = ObservabilityMetadata.mergeLeft(self.metadata, metadata)
return .init(
description: description,
parent: self,
metadata: mergedMetadata,
diagnosticsHandler: self.diagnosticsHandler
)
}
public func makeChildScope(description: String, metadataProvider: () -> ObservabilityMetadata) -> Self {
self.makeChildScope(description: description, metadata: metadataProvider())
}
// diagnostics
public func makeDiagnosticsEmitter(metadata: ObservabilityMetadata? = .none) -> DiagnosticsEmitter {
let mergedMetadata = ObservabilityMetadata.mergeLeft(self.metadata, metadata)
return .init(scope: self, metadata: mergedMetadata)
}
public func makeDiagnosticsEmitter(metadataProvider: () -> ObservabilityMetadata) -> DiagnosticsEmitter {
self.makeDiagnosticsEmitter(metadata: metadataProvider())
}
// FIXME: we want to remove this functionality and move to more conventional error handling
//@available(*, deprecated, message: "this pattern is deprecated, transition to error handling instead")
public var errorsReported: Bool {
self.diagnosticsHandler.errorsReported
}
// FIXME: we want to remove this functionality and move to more conventional error handling
//@available(*, deprecated, message: "this pattern is deprecated, transition to error handling instead")
public var errorsReportedInAnyScope: Bool {
if self.errorsReported {
return true
}
return parent?.errorsReportedInAnyScope ?? false
}
// DiagnosticsEmitterProtocol
public func emit(_ diagnostic: Diagnostic) {
var diagnostic = diagnostic
diagnostic.metadata = ObservabilityMetadata.mergeLeft(self.metadata, diagnostic.metadata)
self.diagnosticsHandler.handleDiagnostic(scope: self, diagnostic: diagnostic)
}
private struct DiagnosticsHandlerWrapper: DiagnosticsHandler {
private let underlying: DiagnosticsHandler
private var _errorsReported = ThreadSafeBox<Bool>(false)
init(_ underlying: DiagnosticsHandler) {
self.underlying = underlying
}
public func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic) {
if diagnostic.severity == .error {
self._errorsReported.put(true)
}
self.underlying.handleDiagnostic(scope: scope, diagnostic: diagnostic)
}
var errorsReported: Bool {
self._errorsReported.get() ?? false
}
}
}
// MARK: - Diagnostics
public protocol DiagnosticsHandler {
func handleDiagnostic(scope: ObservabilityScope, diagnostic: Diagnostic)
}
// helper protocol to share default behavior
public protocol DiagnosticsEmitterProtocol {
func emit(_ diagnostic: Diagnostic)
}
extension DiagnosticsEmitterProtocol {
public func emit(_ diagnostics: [Diagnostic]) {
for diagnostic in diagnostics {
self.emit(diagnostic)
}
}
public func emit(severity: Diagnostic.Severity, message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(.init(severity: severity, message: message, metadata: metadata))
}
public func emit(error message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(.init(severity: .error, message: message, metadata: metadata))
}
public func emit(error message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) {
self.emit(error: message.description, metadata: metadata)
}
public func emit(_ error: Error, metadata: ObservabilityMetadata? = .none) {
self.emit(.error(error, metadata: metadata))
}
public func emit(warning message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(severity: .warning, message: message, metadata: metadata)
}
public func emit(warning message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) {
self.emit(warning: message.description, metadata: metadata)
}
public func emit(info message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(severity: .info, message: message, metadata: metadata)
}
public func emit(info message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) {
self.emit(info: message.description, metadata: metadata)
}
public func emit(debug message: String, metadata: ObservabilityMetadata? = .none) {
self.emit(severity: .debug, message: message, metadata: metadata)
}
public func emit(debug message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) {
self.emit(debug: message.description, metadata: metadata)
}
/// trap a throwing closure, emitting diagnostics on error and returning the value returned by the closure
public func trap<T>(_ closure: () throws -> T) -> T? {
do {
return try closure()
} catch Diagnostics.fatalError {
// FIXME: (diagnostics) deprecate this with Diagnostics.fatalError
return nil
} catch {
self.emit(error)
return nil
}
}
/// trap a throwing closure, emitting diagnostics on error and returning boolean representing success
@discardableResult
public func trap(_ closure: () throws -> Void) -> Bool {
do {
try closure()
return true
} catch Diagnostics.fatalError {
// FIXME: (diagnostics) deprecate this with Diagnostics.fatalError
return false
} catch {
self.emit(error)
return false
}
}
}
// TODO: consider using @autoclosure to delay potentially expensive evaluation of data when some diagnostics may be filtered out
public struct DiagnosticsEmitter: DiagnosticsEmitterProtocol {
private let scope: ObservabilityScope
private let metadata: ObservabilityMetadata?
fileprivate init(scope: ObservabilityScope, metadata: ObservabilityMetadata?) {
self.scope = scope
self.metadata = metadata
}
public func emit(_ diagnostic: Diagnostic) {
var diagnostic = diagnostic
diagnostic.metadata = ObservabilityMetadata.mergeLeft(self.metadata, diagnostic.metadata)
self.scope.emit(diagnostic)
}
}
public struct Diagnostic: CustomStringConvertible {
public let severity: Severity
public let message: String
public internal (set) var metadata: ObservabilityMetadata?
public init(severity: Severity, message: String, metadata: ObservabilityMetadata?) {
self.severity = severity
self.message = message
self.metadata = metadata
}
public var description: String {
return "[\(self.severity)]: \(self.message)"
}
public static func error(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .error, message: message, metadata: metadata)
}
public static func error(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .error, message: message.description, metadata: metadata)
}
public static func error(_ error: Error, metadata: ObservabilityMetadata? = .none) -> Self {
var metadata = metadata ?? ObservabilityMetadata()
if metadata.underlyingError == nil {
metadata.underlyingError = .init(error)
}
let message: String
// FIXME: this brings in the TSC API still
// FIXME: string interpolation seems brittle
if let diagnosticData = error as? DiagnosticData {
message = "\(diagnosticData)"
} else if let convertible = error as? DiagnosticDataConvertible {
message = "\(convertible.diagnosticData)"
} else if let localizedError = error as? LocalizedError {
message = localizedError.errorDescription ?? localizedError.localizedDescription
} else {
message = "\(error)"
}
return Self(severity: .error, message: message, metadata: metadata)
}
public static func warning(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .warning, message: message, metadata: metadata)
}
public static func warning(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .warning, message: message.description, metadata: metadata)
}
public static func info(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .info, message: message, metadata: metadata)
}
public static func info(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .info, message: message.description, metadata: metadata)
}
public static func debug(_ message: String, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .debug, message: message, metadata: metadata)
}
public static func debug(_ message: CustomStringConvertible, metadata: ObservabilityMetadata? = .none) -> Self {
Self(severity: .debug, message: message.description, metadata: metadata)
}
public enum Severity: Comparable {
case error
case warning
case info
case debug
internal var naturalIntegralValue: Int {
switch self {
case .debug:
return 0
case .info:
return 1
case .warning:
return 2
case .error:
return 3
}
}
public static func < (lhs: Self, rhs: Self) -> Bool {
return lhs.naturalIntegralValue < rhs.naturalIntegralValue
}
}
}
// MARK: - ObservabilityMetadata
/// Provides type-safe access to the ObservabilityMetadata's values.
/// This API should ONLY be used inside of accessor implementations.
///
/// End users should use "accessors" the key's author MUST define rather than using this subscript, following this pattern:
///
/// extension ObservabilityMetadata {
/// var testID: String? {
/// get {
/// self[TestIDKey.self]
/// }
/// set {
/// self[TestIDKey.self] = newValue
/// }
/// }
/// }
///
/// enum TestIDKey: ObservabilityMetadataKey {
/// typealias Value = String
/// }
///
/// This is in order to enforce a consistent style across projects and also allow for fine grained control over
/// who may set and who may get such property. Just access control to the Key type itself lacks such fidelity.
///
/// Note that specific baggage and context types MAY (and usually do), offer also a way to set baggage values,
/// however in the most general case it is not required, as some frameworks may only be able to offer reading.
// FIXME: we currently require that Value conforms to CustomStringConvertible which sucks
// ideally Value would conform to Equatable but that has generic requirement
// luckily, this is about to change so we can clean this up soon
public struct ObservabilityMetadata: CustomDebugStringConvertible {
public typealias Key = ObservabilityMetadataKey
private var _storage = [AnyKey: Any]()
public init() {}
public subscript<Key: ObservabilityMetadataKey>(_ key: Key.Type) -> Key.Value? {
get {
guard let value = self._storage[AnyKey(key)] else { return nil }
// safe to force-cast as this subscript is the only way to set a value.
return (value as! Key.Value)
}
set {
self._storage[AnyKey(key)] = newValue
}
}
/// The number of items in the baggage.
public var count: Int {
self._storage.count
}
/// A Boolean value that indicates whether the baggage is empty.
public var isEmpty: Bool {
self._storage.isEmpty
}
/// Iterate through all items in this `ObservabilityMetadata` by invoking the given closure for each item.
///
/// The order of those invocations is NOT guaranteed and should not be relied on.
///
/// - Parameter body: The closure to be invoked for each item stored in this `ObservabilityMetadata`,
/// passing the type-erased key and the associated value.
public func forEach(_ body: (AnyKey, Any) throws -> Void) rethrows {
try self._storage.forEach { key, value in
try body(key, value)
}
}
public func merging(_ other: ObservabilityMetadata) -> ObservabilityMetadata {
var merged = ObservabilityMetadata()
self.forEach { (key, value) in
merged._storage[key] = value
}
other.forEach { (key, value) in
merged._storage[key] = value
}
return merged
}
public var debugDescription: String {
var items = [String]()
self._storage.forEach { key, value in
items.append("\(key.keyType.self): \(String(describing: value))")
}
return items.joined(separator: ", ")
}
// FIXME: this currently requires that Value conforms to CustomStringConvertible which sucks
// ideally Value would conform to Equatable but that has generic requirement
// luckily, this is about to change so we can clean this up soon
/*
public static func == (lhs: ObservabilityMetadata, rhs: ObservabilityMetadata) -> Bool {
if lhs.count != rhs.count {
return false
}
var equals = true
lhs.forEach { (key, value) in
if rhs._storage[key]?.description != value.description {
equals = false
return
}
}
return equals
}*/
fileprivate static func mergeLeft(_ lhs: ObservabilityMetadata?, _ rhs: ObservabilityMetadata?) -> ObservabilityMetadata? {
switch (lhs, rhs) {
case (.none, .none):
return .none
case (.some(let left), .some(let right)):
return left.merging(right)
case (.some(let left), .none):
return left
case (.none, .some(let right)):
return right
}
}
/// A type-erased `ObservabilityMetadataKey` used when iterating through the `ObservabilityMetadata` using its `forEach` method.
public struct AnyKey {
/// The key's type represented erased to an `Any.Type`.
public let keyType: Any.Type
init<Key: ObservabilityMetadataKey>(_ keyType: Key.Type) {
self.keyType = keyType
}
}
}
public protocol ObservabilityMetadataKey {
/// The type of value uniquely identified by this key.
associatedtype Value
}
extension ObservabilityMetadata.AnyKey: Hashable {
public static func == (lhs: Self, rhs: Self) -> Bool {
ObjectIdentifier(lhs.keyType) == ObjectIdentifier(rhs.keyType)
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self.keyType))
}
}
extension ObservabilityMetadata {
public var underlyingError: Error? {
get {
self[UnderlyingErrorKey.self]
}
set {
self[UnderlyingErrorKey.self] = newValue
}
}
private enum UnderlyingErrorKey: Key {
typealias Value = Error
}
public struct UnderlyingError: CustomStringConvertible {
let underlying: Error
public init (_ underlying: Error) {
self.underlying = underlying
}
public var description: String {
String(describing: self.underlying)
}
}
}
// MARK: - Compatibility with TSC Diagnostics APIs
@available(*, deprecated, message: "temporary for transition DiagnosticsEngine -> DiagnosticsEmitter")
extension ObservabilityScope {
public func makeDiagnosticsEngine() -> DiagnosticsEngine {
return .init(handlers: [{ Diagnostic($0).map{ self.diagnosticsHandler.handleDiagnostic(scope: self, diagnostic: $0) } }])
}
}
@available(*, deprecated, message: "temporary for transition DiagnosticsEngine -> DiagnosticsEmitter")
extension Diagnostic {
init?(_ diagnostic: TSCBasic.Diagnostic) {
var metadata = ObservabilityMetadata()
if !(diagnostic.location is UnknownLocation) {
metadata.legacyDiagnosticLocation = .init(diagnostic.location)
}
metadata.legacyDiagnosticData = .init(diagnostic.data)
switch diagnostic.behavior {
case .error:
self = .error(diagnostic.message.text, metadata: metadata)
case .warning:
self = .warning(diagnostic.message.text, metadata: metadata)
case .note:
self = .info(diagnostic.message.text, metadata: metadata)
case .remark:
self = .info(diagnostic.message.text, metadata: metadata)
case .ignored:
return nil
}
}
}
@available(*, deprecated, message: "temporary for transition DiagnosticsEngine -> DiagnosticsEmitter")
extension ObservabilityMetadata {
public var legacyDiagnosticLocation: DiagnosticLocationWrapper? {
get {
self[LegacyLocationKey.self]
}
set {
self[LegacyLocationKey.self] = newValue
}
}
private enum LegacyLocationKey: Key {
typealias Value = DiagnosticLocationWrapper
}
public struct DiagnosticLocationWrapper: CustomStringConvertible {
let underlying: DiagnosticLocation
public init (_ underlying: DiagnosticLocation) {
self.underlying = underlying
}
public var description: String {
self.underlying.description
}
}
}
@available(*, deprecated, message: "temporary for transition DiagnosticsEngine -> DiagnosticsEmitter")
extension ObservabilityMetadata {
var legacyDiagnosticData: DiagnosticDataWrapper? {
get {
self[LegacyDataKey.self]
}
set {
self[LegacyDataKey.self] = newValue
}
}
private enum LegacyDataKey: Key {
typealias Value = DiagnosticDataWrapper
}
struct DiagnosticDataWrapper: CustomStringConvertible {
let underlying: DiagnosticData
public init (_ underlying: DiagnosticData) {
self.underlying = underlying
}
public var description: String {
self.underlying.description
}
}
}
| apache-2.0 | 850ce39c7f009ad6195da4cbaa2fe0a5 | 34.12398 | 132 | 0.655381 | 5.017711 | false | false | false | false |
hoffmanjon/SwiftyBones3 | Sources/SwiftyBones_Components/MiscComponents/SBLed.swift | 2 | 3176 | //
// SBLed.swift
// SwiftyBones Component Library
//
// Created by Jon Hoffman on 5/7/16.
//
/**
This type represents a LED connected to a Digital GPIO port. The SBLed type is a value type.
Initialize:
let runningLed = try SBLed(header: .P9, pin: 11, componentName: "Running LED")
or
let runningLed = try SBLed(gpio: SBDigitalGPIO(id: "gpio30", direction: .OUT), componentName: "Running LED")
Methods:
turnLedOn() -> Bool: Turns the LED on
turnLedOff() -> Bool: Turns the LED off
*/
struct SBLed: SBComponentOutProtocol {
let componentName: String
let gpio: SBDigitalGPIO
/**
Initlizes the SBLed type using a SBDigitalGPIO type and a name.
- Parameter gpio: An instances of a SBDigitalGPIO type
- Parameter componentName: A name for this instance that identifies it like "Power on led" or "Error led"
- Throws: ComponentErrors.InvalidGPIOType if the gpio parameter is not an instance of the SBDigitalGPIO type
*/
init(gpio: GPIO?,componentName: String) throws {
guard gpio != nil else {
throw ComponentErrors.GPIOCanNotBeNil
}
if let testGpio = gpio as? SBDigitalGPIO {
self.gpio = testGpio
self.componentName = componentName
} else {
throw ComponentErrors.InvalidGPIOType("\(componentName): Expecting SBDigitalGPIO Type")
}
}
/**
Initlizes the SBLed type using the pin defined by the header and pin parameters for the LED. The component name defines a name for the LED.
- Parameter header: The header of the pin that the LED is connected too
- Parameter pin: The pin that the LED is connected too
- Parameter componentName: A name for this instance that identifies it like "Power on led" or "Error led"
- Throws: ComponentErrors.InvalidGPIOType if the gpio parameter is not an instance of the SBDigitalGPIO type
*/
init(header: BBExpansionHeader, pin: Int, componentName: String) throws {
if let gpio = SBDigitalGPIO(header: header, pin: pin, direction: .OUT) {
self.gpio = gpio
self.componentName = componentName
} else {
throw ComponentErrors.GPIOCanNotBeNil
}
}
/**
Sets the raw value to the GPIO pin.
- Parameter value: This is the value to set. It can be either 0 or 1
- Returns: true if the value was successfully written
*/
func setRawValue(value: Int) -> Bool {
guard value >= 0 && value <= 1 else {
return false
}
let newValue = (value == 1) ? DigitalGPIOValue.HIGH : DigitalGPIOValue.LOW
if !gpio.setValue(value: newValue) {
return false
}
return true
}
/**
Turns the LED on by setting the GPIO pin high
- Returns: true if the value was successfully written
*/
func turnLedOn() -> Bool {
return setRawValue(value: 1)
}
/**
Turns the LED off by setting the GPIO pin low
- Returns: true if the value was successfully written
*/
func turnLedOff() -> Bool {
return setRawValue(value: 0)
}
}
| mit | 38990449501471f14030dc674c6eeb36 | 35.090909 | 145 | 0.639169 | 4.184453 | false | false | false | false |
RobotRebels/SwiftLessons | students_trashspace/Den/HW2.playground/Contents.swift | 1 | 10973 | //: Playground - noun: a place where people can play
import UIKit
class Rumpf {
// все что их объединяет - одна фабрика изготовления в истино лучшей стране - III Рейхе
static var factory = "Junkers"
// общий метод получения фабрики изготовления
static func getFactory() -> String {
return self.factory
}
// общий метод изменения фабрики изготовления
static func setFactory(newname: String) {
self.factory = newname
}
// свойства фюзеляжа, которые можно безвозбранно менять (кол-во бомб, цвет)
var color = "White"
private var bombNumber = 0
// свойства фюзеляжа, которые недоступны для редактированию извне. Любые поптыки будут пресекаться анальной карой
private var model = "U2"
private var fabric = "Steel"
private var length = 0.0
private var width = 0.0
private var weight = 0
private var maxBombNumber = 1
// закрытые методы работы c фюзеляжеv (нихуя лезть всем поряд и делать в моем фюзеляже дырки)
private func openDoor() {
print ("Door is open")
}
private func closeDoor() {
print ("Door is closed")
}
// Публичный метод установки аварийности в самолете
func setAlarmIn () {
openDoor()
print ("Ahtung!!! Hi Hitler")
}
// Публичная загрузка бомб для установки нового порядка в мире
func downloadBombs(number: Int) {
openDoor()
if (number + bombNumber >= maxBombNumber) {
print ("\(maxBombNumber - bombNumber) bombs downloaded!")
bombNumber = maxBombNumber
} else {
bombNumber = bombNumber + number
print ("\(number) bombs downloaded!")
}
closeDoor()
}
func getBombCount() -> Int {
return bombNumber
}
// Публичная бомбардировка!!!
func bombardment () {
openDoor()
bombNumber = 0;
print("Hi Hitler!!!")
closeDoor()
}
// публичнй метод покраски. Гитлер разрешал красить в любой кроме розового! Ибо розовый - цвет самого фюррера!
func setColor(color: String){
if color == "Pink" {
print ("You will be died!!! Pink is Hitler color!!!")
} else {
self.color = color
}
}
// Инициализатор
init(model: String, fabric: String, length: Double, width: Double, weight: Int, maxbombNumber: Int) {
self.model = model
self.fabric = fabric
self.length = length
self.weight = weight
self.width = width
self.maxBombNumber = bombNumber
}
init(length: Double, weight: Int, maxbombNumber: Int ) {
self.length = length
self.weight = weight
self.maxBombNumber = maxbombNumber
}
}
class Shassi {
// static - все такие параметры применимы к классу как таковому
static var sertifacateInCompany: String = "Sert 36/1"
static var maxExplutationTime: Int = 6
//private - все такие параметры экземпляра класса недоступны извне
private var wheelWeight: Float {
get {
return Float(count) * diametr / 10.0
}
}
private var tireWeight: Float {
get {
return tireRadius * 10
}
}
private var tireRadius: Float
private var openPosition: Bool = true
private var diametr: Float
private var brand: String
private var yearsOld: Int
private var count: Int
//метод, который относится к классу как таковому
static func companyStandarts() {
print("Our actualy standarts for Shassi: Sertificated - \(sertifacateInCompany) and max explutation time - \(maxExplutationTime) years")
}
private func canUseThisShassi() -> Bool {
if (Shassi.maxExplutationTime < yearsOld) {
return false
} else {
return true
}
}
//исходим из того, что эти данные мы сможем где то использовать
func weightCalculate() -> Float {
return tireWeight + wheelWeight
}
func isShassiOpen() -> Bool {
print(openPosition)
return openPosition
}
func changeOpenPosition() {
if (openPosition == true) {
openPosition = false
print("shassi is closed!")
} else {
openPosition = true
print("shassi is opened!")
}
}
func maxWeight() -> Float {
return (Float(diametr) * wheelWeight * Float(count)) / (Float((yearsOld)+1) / 10.0)
}
func ageRisk() -> Bool {
let ageRisk = canUseThisShassi()
if ageRisk == true {
print("We can use it!")
return ageRisk
} else {
print("Oh no, we must replace this soon!")
return ageRisk
}
}
init(_brand: String) {
diametr = 10.0
count = 2
yearsOld = 0
brand = "Standart wheel" + _brand
tireRadius = diametr + 4.2
}
init(_diametr: Float, _count: Int, _type: String, _yearsOld: Int) {
diametr = _diametr
count = _count
brand = _type
yearsOld = _yearsOld
tireRadius = diametr + 4.2
}
}
class Pilot {
//переменные для всего класса
static var pilotRasa: String = "Human" // пилоты у нас пипл с планеты Земля
static var gender: String = "Male" // Все пилоты мужики, феминистки негодуют
static let minimalAge:Int = 18 // даже если гуманоид, то пилотом может быть с 18-ти
static let maximumAge: Int = 75
// переменные доступные только внутри класса
private var flightHours: Float = 0.0
private var aviationTye: String = "commercial aviation" // все пилоты не только мужики, но и только гражданская авиация. Девочки рыдают
private static var licens: String = "PPL" //тип лицензии. изменять вне класса нельзя. Параметр применяется для всего класса
//Публичные переменные, которые можно изменить за рамками класса
private var fullName: String = ""
private var educationDegree: String = ""
private var universityName: String = ""
init(_fullName: String, education: String, university: String) {
fullName = _fullName
educationDegree = education
universityName = university
}
func getPilotFlightHours() -> Float {
return flightHours
}
// Функция проверят может ли кто-то быть пилотом. Доступна и вне класса. Вопрос должна ли что-то еще возвращать данная функция.
func checkCanBePilot(race: String, pilotAge: Int) {
if (race == "German") {
print("Hi Gidra!")
}
if ((pilotAge > Pilot.minimalAge) && (pilotAge < Pilot.maximumAge)) {
print ("Пилот не малорик, можно доверить самолет!")
} else {
print ("Пилот еще не дорос до больших игрушек, сорян :(")
}
}
// Функфия доступна в рамках класса и возвращает общее количество часов кторое налетал пилот
func addNewHours(pilotNewHours: Float) {
flightHours += pilotNewHours
}
}
class Engine {
private var power: Int = 0
private var isRun: Bool = false
var serialNumber: String
init(_serialNumer: String, _power: Int) {
power = _power
serialNumber = _serialNumer
}
func turnOn() {
isRun = true
}
func turnOff() {
isRun = false
}
}
class RollsRoysEngine: Engine {
var garanteeAge: Int = 20
}
class Plane {
// композиция (более строгая компоновка объектов)
var fusilage: Rumpf = Rumpf(length: 100.0, weight: 10, maxbombNumber: 80)
var arrayEngine: [Engine] = []
var shassi: Shassi = Shassi(_brand: "BMW")
// аггрегация (менее строгая. Объект внедренный может сууществовать независимо)
var pilot: Pilot?
func setPilot(newPilot: Pilot) {
pilot = newPilot
}
func takeOff() -> Bool {
if shassi.isShassiOpen() {
for engine in arrayEngine {
engine.turnOn()
}
print("TAKE OFF: Vzuuuh")
} else {
print("Something is go wrong")
return false
}
shassi.changeOpenPosition()
return true
}
func takeOn() {
if !shassi.isShassiOpen() {
shassi.changeOpenPosition()
}
print("TAKE ON: Vzuuuh")
for engine in arrayEngine {
engine.turnOff()
}
}
init(dict: [String: AnyObject]) {
fusilage = dict["fusilage"] as? Rumpf ?? Rumpf(length: 75.0, weight: 10, maxbombNumber: 80)
arrayEngine.append(dict["engine"] as? Engine ?? Engine(_serialNumer: "123", _power: 100))
arrayEngine.append(dict["engine2"] as? Engine ?? Engine(_serialNumer: "123", _power: 100))
arrayEngine.append(dict["engine3"] as? Engine ?? Engine(_serialNumer: "123", _power: 100))
}
}
var paramsDict: [String: AnyObject] = [
"engine": Engine(_serialNumer: "321", _power: 100),
"engine2": Engine(_serialNumer: "222", _power: 75),
"engine3": Engine(_serialNumer: "232", _power: 75),
"shassi": Shassi(_brand: "AD")
]
var plane: Plane = Plane(dict: paramsDict)
var pilot: Pilot = Pilot(_fullName:"Alekseychuk Deniska", education: "High", university: "MEPHI")
plane.setPilot(newPilot: pilot)
plane.fusilage.downloadBombs(number: 30)
plane.takeOff()
plane.fusilage.bombardment()
plane.takeOn()
| mit | 08d6dc3ea9274682c28cb9c6be22b8d3 | 26.973529 | 145 | 0.596152 | 3.417535 | false | false | false | false |
muyang00/YEDouYuTV | YEDouYuZB/YEDouYuZB/Live/ViewModels/LiveViewModel.swift | 1 | 857 | //
// LiveViewModel.swift
// YEDouYuZB
//
// Created by yongen on 2017/5/24.
// Copyright © 2017年 yongen. All rights reserved.
//
import UIKit
import SwiftyJSON
class LiveViewModel: NSObject {
lazy var anchors : [LiveModel] = [LiveModel]()
}
extension LiveViewModel {
func loadData(_ finishedCallBack : @escaping() -> ()) {
NetworkTools.requestData(.get, URLString: "http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1") {
(result) in
let json = JSON(result)
let dataArray = json["lives"]
for dict in dataArray {
if let dict = dict.1.dictionaryObject {
let model = LiveModel(dict: dict)
self.anchors.append(model)
}
}
finishedCallBack()
}
}
}
| apache-2.0 | f1e87420df39427ca53c35e9a16591b3 | 24.117647 | 123 | 0.559719 | 4.165854 | false | false | false | false |
nathawes/swift | test/IRGen/prespecialized-metadata/class-inmodule-2argument-1super-2argument-run.swift | 10 | 3481 | // RUN: %target-run-simple-swift(%S/Inputs/main.swift %S/Inputs/consume-logging-metadata-value.swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// Executing on the simulator within __abort_with_payload with "No ABI plugin located for triple x86_64h-apple-ios -- shared libraries will not be registered!"
// UNSUPPORTED: CPU=x86_64 && OS=ios
// UNSUPPORTED: CPU=x86_64 && OS=tvos
// UNSUPPORTED: CPU=x86_64 && OS=watchos
// UNSUPPORTED: CPU=i386 && OS=watchos
// UNSUPPORTED: use_os_stdlib
class WeakMutableInstanceMethodBox<Input, Output> {
let line: UInt
init(line: UInt = #line) {
self.line = line
}
private var work: ((Input) -> Output?)?
func bind<T: AnyObject>(to object: T, method: @escaping (T) -> (Input) -> Output?) {
self.work = { [weak object] input in
guard let object = object else { return nil }
return method(object)(input)
}
}
func call(_ input: Input) -> Output? {
return work?(input)
}
}
extension WeakMutableInstanceMethodBox : CustomStringConvertible {
var description: String {
"\(type(of: self)) @ \(line)"
}
}
class MyWeakMutableInstanceMethodBox<Input, Output> : WeakMutableInstanceMethodBox<Input, Output> {
override init(line: UInt = #line) {
super.init(line: line)
}
}
@inline(never)
func consume<Input, Output>(base: WeakMutableInstanceMethodBox<Input, Output>) {
consume(base)
}
func consume<Input, Output>(derived: MyWeakMutableInstanceMethodBox<Input, Output>) {
consume(derived)
}
func doit() {
// CHECK: [[SUPERCLASS_METADATA_INT_BOOL_ADDRESS:[0-9a-f]+]] WeakMutableInstanceMethodBox<Int, Bool> @ 63
consume(WeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUPERCLASS_METADATA_INT_BOOL_ADDRESS]] WeakMutableInstanceMethodBox<Int, Bool> @ 65
consume(base: WeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUPERCLASS_METADATA_DOUBLE_FLOAT_ADDRESS:[0-9a-f]+]] WeakMutableInstanceMethodBox<Double, Float> @ 67
consume(WeakMutableInstanceMethodBox<Double, Float>())
// CHECK: [[SUPERCLASS_METADATA_DOUBLE_FLOAT_ADDRESS]] WeakMutableInstanceMethodBox<Double, Float> @ 69
consume(base: WeakMutableInstanceMethodBox<Double, Float>())
// CHECK: [[SUBCLASS_METADATA_INT_BOOL_ADDRESS:[0-9a-f]+]] MyWeakMutableInstanceMethodBox<Int, Bool> @ 72
consume(MyWeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUPERCLASS_METADATA_INT_BOOL_ADDRESS]] MyWeakMutableInstanceMethodBox<Int, Bool> @ 74
consume(base: MyWeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUBCLASS_METADATA_INT_BOOL_ADDRESS]] MyWeakMutableInstanceMethodBox<Int, Bool> @ 76
consume(derived: MyWeakMutableInstanceMethodBox<Int, Bool>())
// CHECK: [[SUBCLASS_METADATA_DOUBLE_FLOAT_ADDRESS:[0-9a-f]+]] MyWeakMutableInstanceMethodBox<Double, Float>
consume(MyWeakMutableInstanceMethodBox<Double, Float>())
// CHECK: [[SUPERCLASS_METADATA_DOUBLE_FLOAT_ADDRESS]] MyWeakMutableInstanceMethodBox<Double, Float>
consume(base: MyWeakMutableInstanceMethodBox<Double, Float>())
// CHECK: [[SUBCLASS_METADATA_DOUBLE_FLOAT_ADDRESS]] MyWeakMutableInstanceMethodBox<Double, Float>
consume(derived: MyWeakMutableInstanceMethodBox<Double, Float>())
}
| apache-2.0 | aa04ec3675ac975783cd691084aa010f | 39.952941 | 190 | 0.711864 | 4.148987 | false | false | false | false |
BMWB/RRArt-Swift-Test | RRArt-Swift/RRArt-Swift/Classes/Utils/Manager/AlamofireManager/ApiConfig.swift | 1 | 714 | //
// ApiConfig.swift
// RRArt-Swift
//
// Created by 王天骥 on 16/4/27.
// Copyright © 2016年 com.yibei.renrenmeishu. All rights reserved.
//
let kBaseUrl = "http://app.renrenmeishu.com";
///oss路径
let kOssUploadUrl = "http://img.renrenmeishu.com"
let kOssDownloadUrl = "http://res.renrenmeishu.com"
let kPort20100 = "20100"
let kShopProductsClassinfoUrl = "/v1/products/classinfo"
let kLessonChannelsUrl = "/v1/channels/list"
let kLessonOrgsListUrl = "/v1/orgs/list"
let kLessonVideosListUrl = "/v1/videos/list"
let kLessonArticlesListUrl = "/v1/articles/list"
let kLessonImagesListUrl = "/v1/images/list" | apache-2.0 | 961b95378327f061cbeb2094f2079e7f | 30.909091 | 66 | 0.64194 | 2.770751 | false | false | false | false |
stomp1128/TIY-Assignments | 19 -Forecaster/CityWeatherTableViewController.swift | 1 | 4894 | //
// CityWeatherTableViewController.swift
// Forecaster
//
// Created by Chris Stomp on 10/29/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
protocol ChooseCityViewControllerDelegate {
func didReceiveZip(zip: String)
}
protocol APIControllerProtocol {
func didReceiveAPIResults(results: NSArray)
func didReceiveDarkSkyAPIResults(results: NSDictionary, city: City)
}
class CityWeatherTableViewController: UITableViewController {
var cities = [City]()
var weather: Weather?
var city: City?
var api: APIController!
override func viewDidLoad() {
super.viewDidLoad()
api = APIController(delegate: self)
title = "Forecaster"
self.navigationItem.leftBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cities.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CityWeatherCell", forIndexPath: indexPath) as! CityWeatherCell
let city = cities[indexPath.row]
cell.cityLabel?.text = city.cityName
if city.weather != nil {
cell.weatherCondition.text = city.weather!.condition
let fullTemp = String(city.weather!.temperature).componentsSeparatedByString(".")
var formattedTemp = Int(fullTemp[0])
let decimalPlace = fullTemp[1]
if Int(decimalPlace) > 50 {
formattedTemp! += 1
}
cell.temperature.text = String(formattedTemp!)
cell.icon?.image = UIImage(named: city.weather!.icon)
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ZipSegue" {
let zipVC = segue.destinationViewController as! ChooseCityViewController
zipVC.delegate = self
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let city = cities[indexPath.row]
let detailVC = storyboard?.instantiateViewControllerWithIdentifier("WeatherDetail") as! WeatherDetailViewController
detailVC.city = city
navigationController?.pushViewController(detailVC, animated: true)
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
cities.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
}
extension CityWeatherTableViewController: ChooseCityViewControllerDelegate {
func didReceiveZip(zip: String) {
self.dismissViewControllerAnimated(true, completion: nil)
api = APIController(delegate: self)
api.searchForCity(zip)
}
}
extension CityWeatherTableViewController: APIControllerProtocol {
// MARK: - API Controller Protocol
func didReceiveAPIResults(results: NSArray) {
dispatch_async(dispatch_get_main_queue(), {
//self.cities.append(City.citiesWithJson(results))
let city = City.citiesWithJson(results)
self.cities.append(city)
let api = APIController(delegate: self)
api.searchForWeather(city)
print(results)
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
func didReceiveDarkSkyAPIResults(currently: NSDictionary, city: City) {
dispatch_async(dispatch_get_main_queue(),
{
let weather = Weather.WeatherWithJson(currently)
for eachCity in self.cities {
if city.cityName == eachCity.cityName {
eachCity.weather = weather
}
}
print(currently)
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
}
| cc0-1.0 | ec703475bda7adb5384b5ebfb3fc79af | 32.513699 | 157 | 0.630697 | 5.604811 | false | false | false | false |
mbrandonw/swift-fp | swift-fp/Optional.swift | 1 | 1656 | import Foundation
/**
Getters
*/
func isNone <A> (x: A?) -> Bool {
switch x {
case .Some: return false
case .None: return true
}
}
func isSome <A> (x: A?) -> Bool {
return !isNone(x)
}
func fromSome <A> (x: A?) -> A {
return x!
}
/**
Constant nil function
*/
func nilFunction <A, B> (x: A) -> B? {
return nil
}
/**
Flatten
*/
func flatten <A> (x: A??) -> A? {
if let x = x {
return x
}
return nil
}
/**
Functor
*/
func fmap <A, B> (f: A -> B) -> A? -> B? {
return {x in
switch x {
case let .Some(x): return f(x)
case .None: return nil
}
}
}
/**
Monad
*/
func bind <A, B> (x: A?) -> (A -> B?) -> B? {
return {f in
switch x {
case let .Some(x): return f(x)
case .None: return nil
}
}
}
infix operator >>= {associativity left}
func >>= <A, B> (x: A?, f: A -> B?) -> B? {
return bind(x)(f)
}
postfix operator >>= {}
postfix func >>= <A, B> (x: A?) -> (A -> B?) -> B? {
return bind(x)
}
prefix operator >>= {}
prefix func >>= <A, B> (f: A -> B?) -> A? -> B? {
return {x in
return bind(x)(f)
}
}
func join <A> (x: A??) -> A? {
return flatten(x)
}
/**
Applicative
*/
func pure <A> (x: A) -> A? {
return x
}
func ap <A, B> (f: (A -> B)?) -> A? -> B? {
switch f {
case let .Some(f): return fmap(f)
case .None: return nilFunction
}
}
infix operator <*> {associativity left}
func <*> <A, B> (f: (A -> B)?, x: A?) -> B? {
return ap(f)(x)
}
postfix operator <*> {}
postfix func <*> <A, B> (f: (A -> B)?) -> A? -> B? {
return ap(f)
}
prefix operator <*> {}
prefix func <*> <A, B> (x: A?) -> (A -> B)? -> B? {
return {f in
return ap(f)(x)
}
}
| mit | 0b7386dde278af6f03b366d0cb38f5ee | 13.785714 | 52 | 0.480676 | 2.539877 | false | false | false | false |
azukinohiroki/positionmaker2 | positionmaker2/FigureView.swift | 1 | 12522 | //
// FigureView.swift
// positionmaker2
//
// Created by Hiroki Taoka on 2015/06/11.
// Copyright (c) 2015年 azukinohiroki. All rights reserved.
//
import Foundation
import UIKit
import SCLAlertView
import SwiftHSVColorPicker
protocol FigureViewDelegate : class {
func startTouch(_ view: FigureView, touch: UITouch) -> UIView?
func endTouch(_ view: FigureView, beganPoint: CGPoint)
}
private extension Selector {
static let handleTap = #selector(FigureView.handleTap(sender:))
static let handleLongPress = #selector(FigureView.handleLongPress(sender:))
static let handleDoubleTap = #selector(FigureView.handleDoubleTap(sender:))
}
class FigureView: UIView, UITextFieldDelegate, SphereMenuDelegate {
private var _figure: Figure!
private var _parent: UIView?
private var _vc: ViewController!
private var _r: CGFloat = 1.0, _g: CGFloat = 1.0, _b: CGFloat = 1.0, _a: CGFloat = 1.0
private let _label: UITextField!
weak var delegate: FigureViewDelegate? = nil
var selected: Bool = false {
didSet {
// self.selected ? self.backgroundColor = UIColor.lightGrayColor() : setColor(_figure)
if self.selected {
_r = 0.7
_g = 0.7
_b = 0.7
setNeedsDisplay()
} else {
setColor(_figure)
}
}
}
required init?(coder aDecoder: NSCoder) {
_label = UITextField()
super.init(coder: aDecoder)
}
init(figure: Figure, vc: ViewController, frame: CGRect) {
_label = UITextField()
super.init(frame: frame)
initFigureView(figure, vc: vc, frame: frame)
}
init(figure: Figure, vc: ViewController) {
let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 30, height: 30))
_label = UITextField()
super.init(frame: frame)
initFigureView(figure, vc: vc, frame: frame)
}
private func initFigureView(_ figure: Figure, vc: ViewController, frame: CGRect) {
_vc = vc
setFigure(figure)
// _startingPoint = frame.origin
let gr = UITapGestureRecognizer(target: self, action: .handleTap)
gr.numberOfTapsRequired = 1
gr.numberOfTouchesRequired = 1
addGestureRecognizer(gr)
let long = UILongPressGestureRecognizer(target: self, action: .handleLongPress)
long.minimumPressDuration = 0.8
addGestureRecognizer(long)
let dbl = UITapGestureRecognizer(target: self, action: .handleDoubleTap)
dbl.numberOfTapsRequired = 2
dbl.numberOfTouchesRequired = 1
addGestureRecognizer(dbl)
_label.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
_label.isUserInteractionEnabled = false
_label.delegate = self
addSubview(_label)
self.backgroundColor = UIColor.clear
}
private func setFigure(_ figure: Figure) {
_figure = figure
setColor(figure)
}
private func setColor(_ figure: Figure) {
let color = figure.color.intValue
_r = CGFloat((color >> 16) & 0xFF) / 255.0
_g = CGFloat((color >> 8) & 0xFF) / 255.0
_b = CGFloat( color & 0xFF) / 255.0
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
let ctx: CGContext = UIGraphicsGetCurrentContext()!
ctx.setFillColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)
ctx.setStrokeColor(red: _r, green: _g, blue: _b, alpha: _a)
ctx.strokeEllipse(in: CGRect(x: 0, y: 0, width: frame.size.width*0.9, height: frame.size.height*0.9))
ctx.fillEllipse(in: CGRect(x: 0, y: 0, width: frame.size.width*0.9, height: frame.size.height*0.9))
ctx.setFillColor(red: _r, green: _g, blue: _b, alpha: _a)
ctx.fillEllipse(in: CGRect(x: 0, y: 0, width:frame.size.width*0.9, height: frame.size.height*0.8))
}
func toDictionary() -> Dictionary<String, Any> {
var f = Dictionary<String, Any>()
f["id"] = _figure.id
f["name"] = _figure.name
f["color"] = _figure.color
return ["figure":f, "x":self.frame.origin.x, "y":self.frame.origin.y, "h":self.frame.size.height, "w":self.frame.size.width,
"a":_a, "selected":selected]
}
func getId() -> NSNumber {
return _figure.id
}
static func fromDictionary(_ dic: Dictionary<String, Any>, _ vc: ViewController) -> FigureView {
let tmp = dic["figure"] as! Dictionary<String, Any>
let f = Figure.defaultFigure()
f.id = tmp["id"] as! NSNumber
f.name = tmp["name"] as! String
f.color = tmp["color"] as! NSNumber
let frame = CGRect(x: dic["x"] as! CGFloat, y: dic["y"] as! CGFloat, width: dic["w"] as! CGFloat, height: dic["h"] as! CGFloat)
let fv = FigureView(figure: f, vc: vc, frame: frame)
fv._a = dic["a"] as! CGFloat
fv.selected = dic["selected"] as! Bool
return fv
}
// MARK: UI event delegate
@objc func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .ended && !_moved {
selected = !selected
// println("tapped+\(selected)")
}
}
private var _longPressed = false
@objc func handleLongPress(sender: UILongPressGestureRecognizer) {
if sender.state == .began {
if _moved { return; }
_longPressed = true
let alert = SCLAlertView()
alert.addButton("削除") {
self.removeFromSuperview()
self._vc.removeFVFromList(self)
ActionLogController.instance().addDelete(fv: self, origin: self._beganPoint, vc: self._vc)
// FIXME: DBとの連携
}
alert.addButton("色変更") {
let start = UIImage(named: "start")
let image1 = UIImage(named: "icon-facebook")
let image2 = UIImage(named: "icon-email")
let image3 = UIImage(named: "icon-twitter")
let images:[UIImage] = [image1!,image2!,image3!]
let menu = SphereMenu(startPoint: CGPoint(x: 160, y: 320), startImage: start!, submenuImages:images, tapToDismiss:true)
menu.delegate = self
self._vc.baseView.addSubview(menu)
}
/*alert.addButton("色変更2") {
var colorWell:ColorWell = ColorWell()
var colorPicker:ColorPicker = ColorPicker()
var huePicker:HuePicker = HuePicker()
// Setup
var pickerController = ColorPickerController(svPickerView: colorPicker, huePickerView: huePicker, colorWell: colorWell)
pickerController.color = UIColor.redColor()
// get color:
pickerController.color
// get color updates:
pickerController.onColorChange = {(color, finished) in
if finished {
self.view.backgroundColor = UIColor.whiteColor() // reset background color to white
} else {
self.view.backgroundColor = color // set background color to current selected color (finger is still down)
}
}
}*/
alert.showWarning("メニュー", subTitle: "選択してください", closeButtonTitle: "CANCEL")
} else if sender.state == .ended {
_longPressed = false
}
}
private var _lastLabel = ""
@objc func handleDoubleTap(sender: UITapGestureRecognizer) {
selected = false
_label.isUserInteractionEnabled = true
if _label.canBecomeFirstResponder {
_label.becomeFirstResponder()
_lastLabel = _label.text!
}
}
func setLabel(_ text: String) {
_label.text = text
fitFontSize(_label)
}
private var _beganPoint: CGPoint = CGPoint.zero
private var _lastTouched: CGPoint = CGPoint.zero
private var _moved: Bool = false
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
_moved = false
if let del = delegate {
if let touch = touches.first as UITouch? {
_parent = del.startTouch(self, touch: touch)
_lastTouched = touch.location(in: _parent)
_beganPoint = frame.origin
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let parent = _parent {
if let touch = touches.first as UITouch? {
let point = touch.location(in: parent)
let dx = _lastTouched.x - point.x
let dy = _lastTouched.y - point.y
_moved = !(dx <= 0 && dy <= 0)
let center = self.center
self.center = CGPoint(x: center.x - dx, y: center.y - dy)
moveOthers(dx, dy)
_lastTouched = point
}
}
}
func moveOthers(_ dx: CGFloat, _ dy: CGFloat) {
for fv in _vc.figureViews {
if !fv.selected || fv == self { continue }
let center = fv.center
fv.center = CGPoint(x: center.x - dx, y: center.y - dy)
RecordPlayController.instance().figureMoved(figureView: fv)
}
}
override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
// super.touchesCancelled(touches, withEvent: event)
endTouch()
_parent = nil;
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// super.touchesEnded(touches, withEvent: event)
endTouch()
_parent = nil;
}
private var _overlapFVs: [FigureView] = []
func endTouch() {
if !_longPressed && _moved {
delegate?.endTouch(self, beganPoint: _beganPoint)
let alc = ActionLogController.instance()
alc.addMove(from: _beganPoint, moved: self, figureViews: _vc.figureViews)
}
// center = PositionController.instance().getArrangedPosition(center)
PositionController.instance().arrangePosition(self, figureViews: _vc.figureViews)
checkOverlaps()
checkOthersOverlap()
_moved = false
RecordPlayController.instance().figureMoved(figureView: self)
}
func checkOverlaps() {
let oldOverlaps = _overlapFVs
for fv in oldOverlaps {
fv.requestDeleteFV(self)
}
_overlapFVs = [FigureView]()
for fv in _vc.figureViews {
if self == fv { continue; }
if self.frame.contains(fv.center) {
// if CGRectIntersectsRect(self.frame, fv.frame) {
_overlapFVs.append(fv)
self.alpha = 0.5
fv.alpha = 0.5
}
}
if _overlapFVs.isEmpty {
self.alpha = 1
} else {
for fv in _overlapFVs {
fv.requestAddFV(self)
}
_overlapFVs.append(self)
}
}
func checkOthersOverlap() {
for fv in _vc.figureViews {
if !fv.selected || self == fv { continue }
fv.checkOverlaps()
}
}
func requestAddFV(_ fv: FigureView) {
if _overlapFVs.isEmpty {
_overlapFVs = [self, fv]
} else {
_overlapFVs.append(fv)
}
}
func requestDeleteFV(_ fv: FigureView) {
if _overlapFVs.isEmpty {
return
} else {
_overlapFVs = _overlapFVs.filter() { $0 != fv }
if _overlapFVs.count == 1 {
_overlapFVs.removeAll(keepingCapacity: true)
alpha = 1
}
}
}
// MARK: UITextFieldDelegate
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
textField.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.isUserInteractionEnabled = false
fitFontSize(textField)
ActionLogController.instance().addLabelChange(from: _lastLabel, to: textField.text!, fv: self)
}
private func fitFontSize(_ textField: UITextField) {
let frame = textField.frame
textField.sizeToFit()
if checkFontSize(textField, frame) {
textField.frame = frame
return
}
textField.frame = frame
var font = textField.font!.pointSize
if font < 1 {
textField.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
return
}
font -= 1
textField.font = UIFont.systemFont(ofSize: font)
fitFontSize(textField)
}
private func checkFontSize(_ tf: UITextField, _ frame: CGRect) -> Bool {
let size1 = tf.frame.size
let size2 = frame.size
return size1.equalTo(size2) || (size1.width < size2.width && size1.height < size2.height)
}
// MARK: SphereMenuDelegate
func sphereDidSelected(_ index: Int, menu: SphereMenu) {
NSLog("sphereDidSelected:%d", index)
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(3 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
menu.hide()
// }
}
}
| mit | 295f798b52a92d3e768523a16acd4609 | 26.654102 | 131 | 0.619147 | 3.931904 | false | false | false | false |
BBBInc/AlzPrevent-ios | researchline/LoginViewController.swift | 1 | 3048 | //
// LoginViewController.swift
// researchline
//
// Created by riverleo on 2015. 11. 8..
// Copyright © 2015년 bbb. All rights reserved.
//
import UIKit
import Alamofire
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var doneBarButtonItem: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBarHidden = false
}
// MARK: IBAction Methods
@IBAction func editChangedTextField(sender: UITextField) {
doneBarButtonItem.enabled = !emailTextField.text!.isEmpty && !passwordTextField.text!.isEmpty
}
@IBAction func passwordChanged(sender: AnyObject) {
doneBarButtonItem.enabled = !emailTextField.text!.isEmpty && !passwordTextField.text!.isEmpty
}
@IBAction func touchUpInsideDoneBarButtonItem(sender: UIBarButtonItem) {
sender.enabled = false
Alamofire.request(.POST, Constants.login,
parameters: [
"email": emailTextField.text ?? "",
"password": passwordTextField.text ?? ""
],
headers: [
"deviceKey": Constants.deviceKey,
"deviceType": Constants.deviceType
])
.responseJSON { (response: Response) -> Void in
debugPrint(response)
sender.enabled = true
switch response.result {
case .Success:
switch response.response!.statusCode {
case 200:
// save the sign key
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(response.result.value!["signKey"]!, forKey: "signKey")
userDefaults.setObject(self.emailTextField.text, forKey: "email")
Constants.userDefaults.setObject(Constants.STEP_FINISHED, forKey: "registerStep")
// shows tab bar
let storyboard = UIStoryboard(name: "TabBar", bundle: nil)
let controller = storyboard.instantiateInitialViewController()!
self.presentViewController(controller, animated: true, completion: nil)
break
default:
let alertView = UIAlertView(title: nil, message: response.result.value!["message"] as? String, delegate: nil, cancelButtonTitle: "Okay")
alertView.show()
break
}
break
case .Failure:
let alertView = UIAlertView(title: "Server Error", message: nil, delegate: nil, cancelButtonTitle: "Okay")
alertView.show()
break
}
}
}
} | bsd-3-clause | 244d4b506935abd56288f152c5a2e4de | 37.556962 | 160 | 0.552709 | 5.970588 | false | false | false | false |
hollyschilling/EssentialElements | EssentialElements/EssentialElements/Interface/ContainerAnimators/ContainerAnimator.swift | 1 | 2464 | //
// ContainerAnimator.swift
// EssentialElements
//
// Created by Holly Schilling on 6/24/16.
// Copyright © 2016 Better Practice Solutions. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
open class ContainerAnimator {
public enum AnimationDirection {
case forward
case reverse
}
open fileprivate(set) var containerView : UIView
open weak var currentContentView : UIView?
open var animationDuration : TimeInterval = 0.3
open var animationOptions : UIViewAnimationOptions = .beginFromCurrentState
open var animationDirection : AnimationDirection = .forward
public required init(containerView aView : UIView) {
containerView = aView
}
open func transition(_ newContentView: UIView?, animated: Bool, completion: ((Bool) -> Void)? = nil) {
if let oldContentView = currentContentView {
oldContentView.removeFromSuperview()
}
if let newContentView = newContentView {
newContentView.frame = containerView.bounds
newContentView.translatesAutoresizingMaskIntoConstraints = true
containerView.addSubview(newContentView)
currentContentView = newContentView
}
completion?(true)
// fatalError("Subclasses must implement \(#function) and not call super")
}
}
| mit | 5f206bc3712ed6facf54c780d3f14cd1 | 37.484375 | 106 | 0.704019 | 5.047131 | false | false | false | false |
petester42/RxSwift | RxExample/RxExample/Examples/SimpleValidation/SimpleValidationViewController.swift | 2 | 2203 | //
// SimpleValidation.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
let minimalUsernameLength = 5
let minimalPasswordLength = 5
class SimpleValidationViewController : ViewController {
@IBOutlet weak var usernameOutlet: UITextField!
@IBOutlet weak var usernameValidOutlet: UILabel!
@IBOutlet weak var passwordOutlet: UITextField!
@IBOutlet weak var passwordValidOutlet: UILabel!
@IBOutlet weak var doSomethingOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
usernameValidOutlet.text = "Username has to be at least \(minimalUsernameLength) characters"
passwordValidOutlet.text = "Username has to be at least \(minimalPasswordLength) characters"
let usernameValid = usernameOutlet.rx_text
.map { $0.characters.count >= minimalUsernameLength }
.shareReplay(1) // without this map would be executed once for each binding, rx is stateless by default
let passwordValid = passwordOutlet.rx_text
.map { $0.characters.count >= minimalPasswordLength }
.shareReplay(1)
let everythingValid = combineLatest(usernameValid, passwordValid) { $0 && $1 }
.shareReplay(1)
usernameValid
.bindTo(passwordOutlet.rx_enabled)
.addDisposableTo(disposeBag)
usernameValid
.bindTo(usernameValidOutlet.rx_hidden)
.addDisposableTo(disposeBag)
passwordValid
.bindTo(passwordValidOutlet.rx_hidden)
.addDisposableTo(disposeBag)
everythingValid
.bindTo(doSomethingOutlet.rx_enabled)
.addDisposableTo(disposeBag)
doSomethingOutlet.rx_tap
.subscribeNext(showAlert)
.addDisposableTo(disposeBag)
}
func showAlert() {
let alertView = UIAlertView(
title: "RxExample",
message: "This is wonderful",
delegate: nil,
cancelButtonTitle: "OK"
)
alertView.show()
}
} | mit | cfaf5f1869b775fa7e1dd3896b877845 | 27.24359 | 115 | 0.65713 | 5.004545 | false | false | false | false |
caobo56/Juyou | JuYou/JuYou/ThirdParty/Reflect/Dict2Model/Reflect+Parse.swift | 1 | 6563 | //
// Reflect+Parse.swift
// Reflect
//
// Created by 成林 on 15/8/23.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
extension Reflect{
class func parsePlist(name: String) -> Self?{
let path = NSBundle.mainBundle().pathForResource(name+".plist", ofType: nil)
if path == nil {return nil}
let dict = NSDictionary(contentsOfFile: path!)
if dict == nil {return nil}
return parse(dict: dict!)
}
class func parses(arr arr: NSArray) -> [Reflect]{
var models: [Reflect] = []
for (_ , dict) in arr.enumerate(){
let model = self.parse(dict: dict as! NSDictionary)
models.append(model)
}
return models
}
class func parse(dict dict: NSDictionary) -> Self{
let model = self.init()
let mappingDict = model.mappingDict()
let ignoreProperties = model.ignorePropertiesForParse()
model.properties { (name, type, value) -> Void in
let dataDictHasKey = dict[name] != nil
let mappdictDictHasKey = mappingDict?[name] != nil
let needIgnore = ignoreProperties == nil ? false : (ignoreProperties!).contains(name)
if (dataDictHasKey || mappdictDictHasKey) && !needIgnore {
let key = mappdictDictHasKey ? mappingDict![name]! : name
if !type.isArray {
if !type.isReflect {
if type.typeClass == Bool.self { //bool
model.setValue(dict[key]?.boolValue, forKeyPath: name)
}else{
if !dict[key]!.isEqual(NSNull()) {
model.setValue(dict[key], forKeyPath: name)
}
}
}else{
//这里是模型
//首选判断字典中是否有值
let dictValue = dict[key]
if dictValue != nil { //字典中有模型
let modelValue = model.valueForKeyPath(key)
if modelValue != nil { //子模型已经初始化
model.setValue((type.typeClass as! Reflect.Type).parse(dict: dict[key] as! NSDictionary), forKeyPath: name)
}else{ //子模型没有初始化
//先主动初始化
let cls = ClassFromString(type.typeName)
model.setValue((cls as! Reflect.Type).parse(dict: dict[key] as! NSDictionary), forKeyPath: name)
}
}
}
}else{
if let res = type.isAggregate(){
var arrAggregate = []
if res is Int.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.Int, ins: 0)
}else if res is Float.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.Float, ins: 0.0)
}else if res is Double.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.Double, ins: 0.0)
}else if res is String.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.String, ins: "")
}else if res is NSNumber.Type {
arrAggregate = parseAggregateArray(dict[key] as! NSArray, basicType: ReflectType.BasicType.NSNumber, ins: NSNumber())
}else{
arrAggregate = dict[key] as! [AnyObject]
}
model.setValue(arrAggregate, forKeyPath: name)
}else{
let elementModelType = ReflectType.makeClass(type) as! Reflect.Type
let dictKeyArr = dict[key] as! NSArray
var arrM: [Reflect] = []
for (_, value) in dictKeyArr.enumerate() {
let elementModel = elementModelType.parse(dict: value as! NSDictionary)
arrM.append(elementModel)
}
model.setValue(arrM, forKeyPath: name)
}
}
}
}
model.parseOver()
return model
}
class func parseAggregateArray<T>(arrDict: NSArray,basicType: ReflectType.BasicType, ins: T) -> [T]{
var intArrM: [T] = []
if arrDict.count == 0 {return intArrM}
for (_, value) in arrDict.enumerate() {
var element: T = ins
let v = "\(value)"
if T.self is Int.Type {
element = Int(Float(v)!) as! T
}
else if T.self is Float.Type {element = v.floatValue as! T}
else if T.self is Double.Type {element = v.doubleValue as! T}
else if T.self is NSNumber.Type {element = NSNumber(double: v.doubleValue!) as! T}
else{element = value as! T}
intArrM.append(element)
}
return intArrM
}
func mappingDict() -> [String: String]? {return nil}
func ignorePropertiesForParse() -> [String]? {return nil}
}
| apache-2.0 | 59994ec5058c6a2df0d7d2c5d2596efb | 34.31694 | 145 | 0.417608 | 5.605377 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Crypto/Trust/MXTrustLevelSource.swift | 1 | 3105 | //
// Copyright 2022 The Matrix.org Foundation C.I.C
//
// 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
#if DEBUG
/// Convenience struct which transforms `MatrixSDKCrypto` trust levels
/// into `MatrixSDK` `MXUserTrustLevel`, `MXDeviceTrustLevel` and `MXUsersTrustLevelSummary` formats.
struct MXTrustLevelSource {
private let userIdentitySource: MXCryptoUserIdentitySource
private let devicesSource: MXCryptoDevicesSource
init(userIdentitySource: MXCryptoUserIdentitySource, devicesSource: MXCryptoDevicesSource) {
self.userIdentitySource = userIdentitySource
self.devicesSource = devicesSource
}
func userTrustLevel(userId: String) -> MXUserTrustLevel {
let isVerified = userIdentitySource.isUserVerified(userId: userId)
// `MatrixSDKCrypto` does not distinguish local and cross-signed
// verification status for users
return .init(
crossSigningVerified: isVerified,
locallyVerified: isVerified
)
}
func deviceTrustLevel(userId: String, deviceId: String) -> MXDeviceTrustLevel? {
guard let device = devicesSource.device(userId: userId, deviceId: deviceId) else {
return nil
}
return .init(
localVerificationStatus: device.locallyTrusted ? .verified : .unverified,
crossSigningVerified: device.crossSigningTrusted
)
}
func trustLevelSummary(userIds: [String]) -> MXUsersTrustLevelSummary? {
guard let devices = trustedDevices(userIds: userIds) else {
return nil
}
return .init(
trustedUsersProgress: trustedUsers(userIds: userIds),
andTrustedDevicesProgress: devices
)
}
private func trustedUsers(userIds: [String]) -> Progress {
let verifiedUsers = userIds.filter {
userIdentitySource.isUserVerified(userId: $0)
}
let progress = Progress(totalUnitCount: Int64(userIds.count))
progress.completedUnitCount = Int64(verifiedUsers.count)
return progress
}
private func trustedDevices(userIds: [String]) -> Progress? {
let devices = userIds.flatMap {
devicesSource.devices(userId: $0)
}
let trustedDevices = devices.filter {
$0.crossSigningTrusted || $0.locallyTrusted
}
let progress = Progress(totalUnitCount: Int64(devices.count))
progress.completedUnitCount = Int64(trustedDevices.count)
return progress
}
}
#endif
| apache-2.0 | eed3758cfec7d6ebcc0b4050ba798e13 | 34.284091 | 101 | 0.675684 | 4.676205 | false | false | false | false |
IvanVorobei/Sparrow | sparrow/downloader/SPDownloader.swift | 1 | 1959 | // 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
struct SPDownloader {
static func downloadImageFrom(link: String, withComplection complection: @escaping (UIImage?) -> () = {_ in }) {
guard let url = URL(string: link) else {
complection(nil)
return
}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else {
complection(nil)
return
}
complection(image)
}.resume()
}
}
| mit | f0f7d7c6f504cb690243a45902d006ef | 41.565217 | 116 | 0.665986 | 4.846535 | false | false | false | false |
malaonline/iOS | mala-ios/View/TeacherDetail/TeacherDetailsPhotosCell.swift | 1 | 2990 | //
// TeacherDetailsPhotosCell.swift
// mala-ios
//
// Created by Elors on 1/5/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
import Kingfisher
class TeacherDetailsPhotosCell: MalaBaseCell {
// MARK: - Property
/// 图片URL数组
var photos: [String] = [] {
didSet {
// 加载图片URL数据
photoCollection.urls = photos
}
}
// MARK: - Components
private lazy var detailButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(asset: .rightArrow), for: UIControlState())
button.setTitle("更多", for: UIControlState())
button.setTitleColor(UIColor(named: .HeaderTitle), for: UIControlState())
button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: -24)
button.addTarget(self, action: #selector(TeacherDetailsPhotosCell.detailButtonDidTap), for: .touchUpInside)
return button
}()
/// 图片滚动浏览视图
private lazy var photoCollection: ThemePhotoCollectionView = {
let collection = ThemePhotoCollectionView(frame: CGRect.zero, collectionViewLayout: CommonFlowLayout(type: .detailPhotoView))
return collection
}()
// MARK: - Constructed
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func setupUserInterface() {
// SubViews
headerView.addSubview(detailButton)
content.addSubview(photoCollection)
// Autolayout
detailButton.snp.makeConstraints { (maker) -> Void in
maker.height.equalTo(13)
maker.right.equalTo(headerView).offset(-12)
maker.centerY.equalTo(headerView)
}
content.snp.updateConstraints { (maker) -> Void in
maker.top.equalTo(headerView.snp.bottom).offset(10)
maker.left.equalTo(contentView)
maker.right.equalTo(contentView)
maker.bottom.equalTo(contentView).offset(-10)
}
photoCollection.snp.makeConstraints { (maker) in
maker.left.equalTo(content)
maker.right.equalTo(content)
maker.top.equalTo(content)
maker.height.equalTo(MalaLayout_DetailPhotoWidth)
maker.bottom.equalTo(content)
}
}
// MARK: - Events Response
/// 查看相册按钮点击事件
@objc private func detailButtonDidTap() {
// 相册
NotificationCenter.default.post(name: MalaNotification_PushPhotoBrowser, object: "browser")
}
}
| mit | b88faa58dbd141ae05deb06b0159515d | 31.865169 | 133 | 0.632137 | 4.628165 | false | false | false | false |
sonsongithub/numsw | Playgrounds/sandbox/sandbox/SelectTableViewController.swift | 1 | 2201 | //
// SelectTableViewController.swift
// sandbox
//
// Created by sonson on 2017/04/07.
// Copyright © 2017年 sonson. All rights reserved.
//
#if os(iOS)
import UIKit
import NumswRenderer
class SelectTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? RenderScrollViewController {
func makeRenderer() -> ChartRenderer {
let points1 = DummyData.points1()
let points2 = DummyData.points2()
var chart = Chart()
chart.elements = [
.line(LineGraph(points: points1)),
.line(LineGraph(points: points2))
]
chart.computeViewport()
return ChartRenderer(chart: chart)
}
vc.append(renderer: makeRenderer())
vc.append(renderer: makeRenderer())
vc.append(renderer: makeRenderer())
} else if let vc = segue.destination as? RendererDebugViewController {
func makeRenderer() -> ChartRenderer {
let points1 = DummyData.points1()
let points2 = DummyData.points2()
var chart = Chart()
chart.elements = [
.line(LineGraph(points: points1)),
.line(LineGraph(points: points2))
]
chart.computeViewport()
return ChartRenderer(chart: chart)
}
vc.renderer = makeRenderer()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 1 {
DummyData.runHoldExample()
self.navigationController?.pushViewController(NumswPlayground.shared.viewController, animated: true)
}
}
}
#endif
| mit | 9bc228c07d08fa87cbfe2ff64f29bda6 | 31.323529 | 112 | 0.544131 | 5.283654 | false | false | false | false |
hujiaweibujidao/Gank | Gank/Model/GankModel.swift | 2 | 873 | //
// GankModel.swift
// Gank
//
// Created by AHuaner on 2017/2/13.
// Copyright © 2017年 CoderAhuan. All rights reserved.
//
import UIKit
class GankModel: NSObject {
var id: String?
var publishedAt: String?
var desc: String?
var url: String?
var user: String?
var type: String?
// 在bmob服务器的唯一标示
var objectId: String?
convenience init(bmob: BmobObject) {
self.init()
self.id = bmob.object(forKey: "gankId") as? String
self.desc = bmob.object(forKey: "gankDesc") as? String
self.publishedAt = bmob.object(forKey: "gankPublishAt") as? String
self.url = bmob.object(forKey: "gankUrl") as? String
self.type = bmob.object(forKey: "gankType") as? String
self.user = bmob.object(forKey: "gankUser") as? String
self.objectId = bmob.objectId
}
}
| mit | 35b891ffe6a49065eed1fad87f0b0003 | 26.483871 | 74 | 0.629108 | 3.354331 | false | false | false | false |
Codeido/swift-basics | Playground Codebase/Generics.playground/section-1.swift | 1 | 1288 | // Playground - noun: a place where people can play
import UIKit
//Generic code enables you to write flexible, reusable functions and types that can work with any type.
// Generic function, which swaps two any values.
func swapTwoValues<T>(inout a: T, inout b: T) {
let temporaryA = a
a = b
b = temporaryA
}
// Generic collection type called `Stack`.
struct Stack<T> {
var elements = T[]()
mutating func push(element: T) {
elements.append(element)
}
mutating func pop() -> T {
return elements.removeLast()
}
}
//We can use certain type constraints on the types with generic functions and generic types. Use where after the type name to specify a list of requirements.
// Generic function, which checks that the sequence contains a specified value.
func containsValue<
T where T: Sequence, T.GeneratorType.Element: Equatable>
(sequence: T, valueToFind: T.GeneratorType.Element) -> Bool {
for value in sequence {
if value == valueToFind {
return true
}
}
return false
}
//In the simple cases, you can omit where and simply write the protocol or class name after a colon. Writing <T: Sequence> is the same as writing <T where T: Sequence>. | gpl-2.0 | cf09bea951fc4b4c1d3de03da43f7ce7 | 31.225 | 168 | 0.660714 | 4.410959 | false | false | false | false |
tonyarnold/Bond | Sources/Bond/Data Structures/TreeProtocol+Differ.swift | 1 | 2954 | //
// The MIT License (MIT)
//
// Copyright (c) 2019 DeclarativeHub/Bond
//
// 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 Differ
public extension TreeProtocol {
public func diff(_ other: Self, sourceRoot: IndexPath = [], destinationRoot: IndexPath = [], areEqual: @escaping (Children.Element, Children.Element) -> Bool) -> OrderedCollectionDiff<IndexPath> {
let traces = children.outputDiffPathTraces(to: other.children, isEqual: areEqual)
let diff = Diff(traces: traces)
var collectionDiff = OrderedCollectionDiff(from: diff, sourceRoot: sourceRoot, destinationRoot: destinationRoot)
for trace in traces {
if trace.from.x + 1 == trace.to.x && trace.from.y + 1 == trace.to.y {
// match point x -> y, diff children
let childA = children[trace.from.x]
let childB = other.children[trace.from.y]
let childDiff = childA.diff(
childB,
sourceRoot: sourceRoot.appending(trace.from.x),
destinationRoot: destinationRoot.appending(trace.from.y),
areEqual: areEqual
)
collectionDiff.merge(childDiff)
} else if trace.from.y < trace.to.y {
// inserted, do nothing
} else {
// deleted, do nothing
}
}
return collectionDiff
}
}
extension OrderedCollectionDiff where Index == IndexPath {
public init(from diff: Diff, sourceRoot: IndexPath, destinationRoot: IndexPath) {
self.init()
for element in diff.elements {
switch element {
case .insert(let at):
inserts.append(destinationRoot.appending(at))
case .delete(let at):
deletes.append(sourceRoot.appending(at))
}
}
}
}
| mit | a25d04ea7831797653cb95114b160642 | 40.605634 | 200 | 0.644211 | 4.523737 | false | false | false | false |
nguyenantinhbk77/practice-swift | Games/CookieCrunch/CookieCrunch/CookieCrunch/GameScene.swift | 3 | 14877 | //
// GameScene.swift
// CookieCrunch
//
// Created by Domenico on 11/8/14
import SpriteKit
class GameScene: SKScene {
var level:Level!
var selectionSprite = SKSpriteNode()
let TileWidth: CGFloat = 32.0
let TileHeight: CGFloat = 36.0
let gameLayer: SKNode = SKNode()
let cookiesLayer:SKNode = SKNode()
let tilesLayer = SKNode()
/// The column and row numbers of the cookie that the player
/// first touched when she started her swipe movement
var swipeFromColumn: Int?
var swipeFromRow: Int?
// Sounds
let swapSound = SKAction.playSoundFileNamed("Chomp.wav", waitForCompletion: false)
let invalidSwapSound = SKAction.playSoundFileNamed("Error.wav", waitForCompletion: false)
let matchSound = SKAction.playSoundFileNamed("Ka-Ching.wav", waitForCompletion: false)
let fallingCookieSound = SKAction.playSoundFileNamed("Scrape.wav", waitForCompletion: false)
let addCookieSound = SKAction.playSoundFileNamed("Drip.wav", waitForCompletion: false)
/// Closure
var swipeHandler: ((Swap) -> ())?
override init(size: CGSize) {
super.init(size: size)
swipeFromColumn = nil
swipeFromRow = nil
anchorPoint = CGPoint(x: 0.5, y: 0.5)
let background = SKSpriteNode(imageNamed: "Background")
self.addChild(background)
self.addChild(gameLayer)
let layerPosition = CGPoint(
x: -TileWidth * CGFloat(NumColumns) / 2,
y: -TileHeight * CGFloat(NumRows) / 2)
self.cookiesLayer.position = layerPosition
tilesLayer.position = layerPosition
gameLayer.addChild(cookiesLayer)
}
/// This loops through all the rows and columns.
/// If there is a tile at that grid square, then it creates a new tile sprite and adds it to the tiles layer
func addTiles() {
for row in 0..<NumRows {
for column in 0..<NumColumns {
if let tile = level.tileAtColumn(column, row: row) {
let tileNode = SKSpriteNode(imageNamed: "Tile")
tileNode.position = pointForColumn(column, row: row)
tilesLayer.addChild(tileNode)
}
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToView(view: SKView) {
}
/// This method takes a CGPoint that is relative to the cookiesLayer and converts it into column and row numbers
func convertPoint(point: CGPoint) -> (success: Bool, column: Int, row: Int) {
if point.x >= 0 && point.x < CGFloat(NumColumns)*TileWidth &&
point.y >= 0 && point.y < CGFloat(NumRows)*TileHeight {
return (true, Int(point.x / TileWidth), Int(point.y / TileHeight))
} else {
return (false, 0, 0) // invalid location
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
// It converts the touch location to a point relative to the cookiesLayer
let touch = touches.anyObject() as UITouch
let location = touch.locationInNode(cookiesLayer)
// finds out if the touch is inside a square on the level grid
let (success, column, row) = convertPoint(location)
if success {
// the method verifies that the touch is on a cookie rather than on an empty square
if let cookie = level.cookieAtColumn(column, row: row) {
// it records the column and row where the swipe started so you can compare them later to find the direction of the swipe
swipeFromColumn = column
swipeFromRow = row
// Show highlighted cookie
showSelectionIndicatorForCookie(cookie)
}
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
// either the swipe began outside the valid area or the game has already swapped the cookies and you need to ignore the rest of the motion
if swipeFromColumn == nil { return }
// calculate the row and column numbers currently under the player’s finger
let touch = touches.anyObject() as UITouch
let location = touch.locationInNode(cookiesLayer)
let (success, column, row) = convertPoint(location)
if success {
// Direction of the player’s swipe by simply comparing the new column and row numbers to the previous ones
var horzDelta = 0, vertDelta = 0
if column < swipeFromColumn! { // swipe left
horzDelta = -1
} else if column > swipeFromColumn! { // swipe right
horzDelta = 1
} else if row < swipeFromRow! { // swipe down
vertDelta = -1
} else if row > swipeFromRow! { // swipe up
vertDelta = 1
}
// The method only performs the swap if the player swiped out of the old square
if horzDelta != 0 || vertDelta != 0 {
trySwapHorizontal(horzDelta, vertical: vertDelta)
// Remove highlighted cookie
hideSelectionIndicator()
// By setting swipeFromColumn back to nil, the game will ignore the rest of this swipe motion
swipeFromColumn = nil
}
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
swipeFromColumn = nil
swipeFromRow = nil
// If the user just taps on the screen rather than swipes, you want to fade out the highlighted sprite
if selectionSprite.parent != nil && swipeFromColumn != nil {
hideSelectionIndicator()
}
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
touchesEnded(touches, withEvent: event)
}
// Check if there are two cookies to swap
func trySwapHorizontal(horzDelta: Int, vertical vertDelta: Int) {
// calculate the column and row numbers of the cookie to swap with
let toColumn = swipeFromColumn! + horzDelta
let toRow = swipeFromRow! + vertDelta
// Checking for the user swiping outside the grid
if toColumn < 0 || toColumn >= NumColumns { return }
if toRow < 0 || toRow >= NumRows { return }
// Check if there is a cookie in the position
if let toCookie = level.cookieAtColumn(toColumn, row: toRow) {
if let fromCookie = level.cookieAtColumn(swipeFromColumn!, row: swipeFromRow!) {
// valid swap!
// Handle the swap using the swipeHandler closure
if let handler = swipeHandler {
let swap = Swap(cookieA: fromCookie, cookieB: toCookie)
handler(swap)
}
}
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
/// Adding the sprites to the scene
func addSpritesForCookies(cookies:Set<Cookie>){
for cookie in cookies{
let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName)
sprite.position = pointForColumn(cookie.column, row: cookie.row)
cookiesLayer.addChild(sprite)
cookie.sprite = sprite
}
}
func pointForColumn(column:Int, row:Int) -> CGPoint{
return CGPoint(
x:CGFloat(column)*TileWidth + TileWidth / 2,
y: CGFloat(row)*TileHeight + TileHeight / 2
)
}
func showSelectionIndicatorForCookie(cookie: Cookie) {
if selectionSprite.parent != nil {
selectionSprite.removeFromParent()
}
if let sprite = cookie.sprite {
// It gets the name of the highlighted sprite image from the Cookie object and puts the corresponding texture on the selection sprite
let texture = SKTexture(imageNamed: cookie.cookieType.highlightedSpriteName)
selectionSprite.size = texture.size()
selectionSprite.runAction(SKAction.setTexture(texture))
// add the selection sprite as a child of the cookie sprite so that it moves along with the cookie sprite in the swap animation
sprite.addChild(selectionSprite)
// sprite visible by setting its alpha to 1
selectionSprite.alpha = 1.0
}
}
// It removes the selection sprite by fading it out
func hideSelectionIndicator() {
selectionSprite.runAction(SKAction.sequence([
SKAction.fadeOutWithDuration(0.3),
SKAction.removeFromParent()]))
}
/// Animating the swap of two cookies
func animateSwap(swap: Swap, completion: () -> ()) {
let spriteA = swap.cookieA.sprite!
let spriteB = swap.cookieB.sprite!
spriteA.zPosition = 100
spriteB.zPosition = 90
let Duration: NSTimeInterval = 0.3
let moveA = SKAction.moveTo(spriteB.position, duration: Duration)
moveA.timingMode = .EaseOut
spriteA.runAction(moveA, completion: completion)
let moveB = SKAction.moveTo(spriteA.position, duration: Duration)
moveB.timingMode = .EaseOut
spriteB.runAction(moveB)
runAction(swapSound)
}
// it slides the cookies to their new positions and then immediately flips them back.
func animateInvalidSwap(swap: Swap, completion: () -> ()) {
let spriteA = swap.cookieA.sprite!
let spriteB = swap.cookieB.sprite!
spriteA.zPosition = 100
spriteB.zPosition = 90
let Duration: NSTimeInterval = 0.2
let moveA = SKAction.moveTo(spriteB.position, duration: Duration)
moveA.timingMode = .EaseOut
let moveB = SKAction.moveTo(spriteA.position, duration: Duration)
moveB.timingMode = .EaseOut
spriteA.runAction(SKAction.sequence([moveA, moveB]), completion: completion)
spriteB.runAction(SKAction.sequence([moveB, moveA]))
runAction(invalidSwapSound)
}
// loops through all the chains and all the cookies in each chain, and then triggers the animations
func animateMatchedCookies(chains: Set<Chain>, completion: () -> ()) {
for chain in chains {
for cookie in chain.cookies {
if let sprite = cookie.sprite {
if sprite.actionForKey("removing") == nil {
let scaleAction = SKAction.scaleTo(0.1, duration: 0.3)
scaleAction.timingMode = .EaseOut
sprite.runAction(SKAction.sequence([scaleAction, SKAction.removeFromParent()]),
withKey:"removing")
}
}
}
}
runAction(matchSound)
runAction(SKAction.waitForDuration(0.3), completion: completion)
}
// animate the sprites of falling cookies
func animateFallingCookies(columns: [[Cookie]], completion: () -> ()) {
var longestDuration: NSTimeInterval = 0
for array in columns {
for (idx, cookie) in enumerate(array) {
let newPosition = pointForColumn(cookie.column, row: cookie.row)
// The higher up the cookie is, the bigger the delay on the animation
let delay = 0.05 + 0.15*NSTimeInterval(idx)
// the duration of the animation is based on how far the cookie has to fall (0.1 seconds per tile)
let sprite = cookie.sprite!
let duration = NSTimeInterval(((sprite.position.y - newPosition.y) / TileHeight) * 0.1)
// You calculate which animation is the longest
longestDuration = max(longestDuration, duration + delay)
// You perform the animation, which consists of a delay, a movement and a sound effect
let moveAction = SKAction.moveTo(newPosition, duration: duration)
moveAction.timingMode = .EaseOut
sprite.runAction(
SKAction.sequence([
SKAction.waitForDuration(delay),
SKAction.group([moveAction, fallingCookieSound])]))
}
}
// You wait until all the cookies have fallen down before allowing the gameplay to continue
runAction(SKAction.waitForDuration(longestDuration), completion: completion)
}
// animate new cookies on the top
func animateNewCookies(columns: [[Cookie]], completion: () -> ()) {
var longestDuration: NSTimeInterval = 0
for array in columns {
// The new cookie sprite should start out just above the first tile in this column.
// An easy way to find the row number of this tile is to look at the row of
//the first cookie in the array, which is always the top-most one for this column
let startRow = array[0].row + 1
for (idx, cookie) in enumerate(array) {
// Create a new sprite for the cookie
let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName)
sprite.position = pointForColumn(cookie.column, row: startRow)
cookiesLayer.addChild(sprite)
cookie.sprite = sprite
// The higher the cookie, the longer you make the delay
let delay = 0.1 + 0.2 * NSTimeInterval(array.count - idx - 1)
// animation’s duration based on far the cookie has to fall
let duration = NSTimeInterval(startRow - cookie.row) * 0.1
longestDuration = max(longestDuration, duration + delay)
// animate the sprite falling down and fading in
let newPosition = pointForColumn(cookie.column, row: cookie.row)
let moveAction = SKAction.moveTo(newPosition, duration: duration)
moveAction.timingMode = .EaseOut
sprite.alpha = 0
sprite.runAction(
SKAction.sequence([
SKAction.waitForDuration(delay),
SKAction.group([
SKAction.fadeInWithDuration(0.05),
moveAction,
addCookieSound])
]))
}
}
runAction(SKAction.waitForDuration(longestDuration), completion: completion)
}
}
| mit | 4ceabf01f72f9b052fa110909dfadc96 | 41.127479 | 146 | 0.592294 | 5.221559 | false | false | false | false |
adelang/DoomKit | Sources/Graphic.swift | 1 | 5077 | //
// Graphic.swift
// DoomKit
//
// Created by Arjan de Lang on 03-01-15.
// Copyright (c) 2015 Blue Depths Media. All rights reserved.
//
import Cocoa
var __graphicsCache = [String: Graphic]()
open class Graphic {
open var width: Int16 = 0
open var height: Int16 = 0
open var xOffset: Int16 = 0
open var yOffset: Int16 = 0
var _pixelData: [UInt8?] = []
var _cachedImage: NSImage?
open class func graphicWithLumpName(_ lumpName: String, inWad wad: Wad) -> Graphic? {
if lumpName == "-" {
return nil
}
if let graphic = __graphicsCache[lumpName] {
return graphic
}
for lump in wad.lumps {
if lump.name == lumpName {
if let data = lump.data {
var dataPointer = 0
var width: Int16 = 0
(data as NSData).getBytes(&width, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size))
dataPointer += MemoryLayout<Int16>.size
var height: Int16 = 0
(data as NSData).getBytes(&height, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size))
dataPointer += MemoryLayout<Int16>.size
var xOffset: Int16 = 0
(data as NSData).getBytes(&xOffset, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size))
dataPointer += MemoryLayout<Int16>.size
var yOffset: Int16 = 0
(data as NSData).getBytes(&yOffset, range: NSMakeRange(dataPointer, MemoryLayout<Int16>.size))
dataPointer += MemoryLayout<Int16>.size
var pixelData = [UInt8?](repeating: nil, count: (Int(width) * Int(height)))
var columnPointers: [UInt32] = []
for _ in (0 ..< width) {
var columnPointer: UInt32 = 0
(data as NSData).getBytes(&columnPointer, range: NSMakeRange(dataPointer, MemoryLayout<UInt32>.size))
columnPointers.append(columnPointer)
dataPointer += MemoryLayout<UInt32>.size
}
var x: Int16 = 0
for _ in columnPointers {
readPoles: while(true) {
var y: UInt8 = 0
(data as NSData).getBytes(&y, range: NSMakeRange(dataPointer, MemoryLayout<UInt8>.size))
dataPointer += MemoryLayout<UInt8>.size
if y == 255 {
break readPoles
}
var numberOfPixels: UInt8 = 0
(data as NSData).getBytes(&numberOfPixels, range: NSMakeRange(dataPointer, MemoryLayout<UInt8>.size))
dataPointer += MemoryLayout<UInt8>.size
// Ignore first byte
dataPointer += MemoryLayout<UInt8>.size
var pixelIndex = Int(y) + Int(x * height)
for _ in (0 ..< numberOfPixels) {
var paletteIndex: UInt8 = 0
(data as NSData).getBytes(&paletteIndex, range: NSMakeRange(dataPointer, MemoryLayout<UInt8>.size))
pixelData[pixelIndex] = paletteIndex
pixelIndex += 1
dataPointer += MemoryLayout<UInt8>.size
}
// Also ignore last byte
dataPointer += MemoryLayout<UInt8>.size
}
x += 1
}
let graphic = Graphic(width: width, height: height, xOffset: xOffset, yOffset: yOffset, pixelData: pixelData)
__graphicsCache[lumpName] = graphic
return graphic
}
}
}
print("Unable to find graphic with name '\(lumpName)'")
return nil
}
open class func flatWithLumpName(_ lumpName: String, inWad wad: Wad) -> Graphic? {
if lumpName == "-" {
return nil
}
if let graphic = __graphicsCache[lumpName] {
return graphic
}
for lump in wad.lumps {
if lump.name == lumpName {
if let data = lump.data {
let width: Int16 = 64
let height: Int16 = 64
let xOffset: Int16 = 0
let yOffset: Int16 = 0
var pixelData = [UInt8](repeating: 0, count: (Int(width) * Int(height)))
(data as NSData).getBytes(&pixelData, range: NSMakeRange(0, MemoryLayout<UInt8>.size * Int(width) * Int(height)))
let graphic = Graphic(width: width, height: height, xOffset: xOffset, yOffset: yOffset, pixelData: pixelData)
__graphicsCache[lumpName] = graphic
return graphic
}
}
}
print("Unable to find graphic with name '\(lumpName)'")
return nil
}
public init(width: Int16, height: Int16, xOffset: Int16, yOffset: Int16, pixelData: [UInt8?]) {
self.width = width
self.height = height
self.xOffset = xOffset
self.yOffset = yOffset
self._pixelData = pixelData
}
open func imageWithPalette(_ palette: Palette) -> NSImage {
if let image = _cachedImage {
return image
}
let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(width), pixelsHigh: Int(height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: Int(4 * width), bitsPerPixel: 32)
let image = NSImage()
image.addRepresentation(bitmap!)
var pixelIndex = 0
for x in 0 ..< Int(width) {
for y in 0 ..< Int(height) {
let paletteIndex = _pixelData[pixelIndex]
pixelIndex += 1
let color: NSColor
if let paletteIndex = paletteIndex {
color = palette.colors[Int(paletteIndex)]
} else {
color = NSColor.clear
}
bitmap?.setColor(color, atX: x, y: y)
}
}
_cachedImage = image
return image
}
}
| mit | 5ea55f9b8f3334adf850a5f93e3a36dc | 28.011429 | 264 | 0.647627 | 3.582922 | false | false | false | false |
prot3ct/Ventio | Ventio/Ventio/Controllers/EventDetailsViewController.swift | 1 | 925 | import UIKit
import RxSwift
import Cosmos
class EventDetailsViewController: UIViewController
{
@IBOutlet weak var eventTitle: UILabel!
@IBOutlet weak var eventDescription: UILabel!
@IBOutlet weak var eventDate: UILabel!
@IBOutlet weak var eventTime: UILabel!
@IBOutlet weak var eventCreator: UILabel!
internal var currentEvent: EventProtocol!
override func viewDidLoad()
{
super.viewDidLoad()
self.eventTitle.text = currentEvent.title
self.eventDescription.text = currentEvent.description
self.eventDate.text = currentEvent.date
self.eventTime.text = currentEvent.time
self.eventCreator.text = currentEvent.creator
self.eventDescription.layer.borderWidth = CGFloat(1.0)
self.eventDescription.layer.cornerRadius = CGFloat(5.0)
}
@IBAction func onDeleteClicked(_ sender: Any) {
// TO DO
}
}
| apache-2.0 | bdc7c2818559a11999dff63e60b8f096 | 29.833333 | 63 | 0.694054 | 4.648241 | false | false | false | false |
trill-lang/LLVMSwift | Sources/LLVM/Triple.swift | 1 | 41733 | #if SWIFT_PACKAGE
import cllvm
import llvmshims
#endif
/// A `Triple` provides an abstraction over "Target Triples".
///
/// A Target Triple encodes information about the target of a
/// compilation session including the underlying processor architecture, OS,
/// platform vendor, and additional information about the runtime environment.
///
/// A target triple is usually specified at the command line as a `-` delimited
/// string in the format:
///
/// <arch><sub>-<vendor>-<sys>-<abi>
///
/// For example:
///
/// nvptx64-nvidia-cuda
/// x86_64-unknown-linux-gnu
/// x86_64-apple-ios8.3-simulator
///
/// For this reason, `Triple` provides an initializer that parses strings in
/// this format.
public struct Triple: Equatable {
/// The raw target triple string.
public let data: String
/// The target's architecture.
public let architecture: Architecture
/// The target's vendor.
public let vendor: Vendor
/// The target's operating system.
public let os: OS
/// The target's environment.
public let environment: Environment
/// The target's object file format.
public let objectFormat: ObjectFormat
/// Returns the default target triple for the host machine.
public static let `default`: Triple = {
guard let raw = LLVMGetDefaultTargetTriple() else {
return Triple("")
}
defer { LLVMDisposeMessage(raw) }
return Triple(String(cString: raw))
}()
/// Create a target triple from known components.
///
/// - Parameters:
/// - architecture: The target's architecture. If none is specified,
/// an unknown architecture is assumed.
/// - vendor: The target's vendor. If none is specified,
/// an unknown vendor is assumed.
/// - os: The target's operating system. If none is specified,
/// an unknown operating system is assumed.
/// - environment: The target's environment. If none is specified,
/// an unknown environment is assumed.
/// - objectFormat: The target's object file format. If none is specified,
/// an unknown object file format is assumed.
public init(
architecture: Architecture = .unknown,
vendor: Vendor = .unknown,
os: OS = .unknown,
environment: Environment = .unknown,
objectFormat: ObjectFormat = .unknown
) {
self.data = [
architecture.rawValue,
vendor.rawValue,
os.rawValue,
environment.rawValue
].joined(separator: "-")
self.architecture = architecture
self.vendor = vendor
self.os = os
self.environment = environment
self.objectFormat = (objectFormat == .unknown)
? ObjectFormat.default(for: architecture, os: os)
: objectFormat
}
/// Create a target triple by parsing a string in the standard LLVM
/// triple format.
///
/// The expected format of a target triple string is as follows:
///
/// <arch><sub>-<vendor>-<sys>-<abi>
///
/// - Parameter str: The target triple format string to parse.
public init(_ str: String) {
var parch: Architecture = .unknown
var pvendor: Vendor = .unknown
var pos: OS = .unknown
var penvironment: Environment = .unknown
var pobjectFormat: ObjectFormat = .unknown
let components = str.split(separator: "-", maxSplits: 3, omittingEmptySubsequences: false)
if components.count > 0 {
parch = Architecture(parse: components[0])
if components.count > 1 {
pvendor = Vendor(parse: components[1])
if components.count > 2 {
pos = OS(parse: components[2])
if components.count > 3 {
penvironment = Environment(parse: components[3])
pobjectFormat = ObjectFormat(parse: components[3])
}
}
} else {
switch components[0] {
case let x where x.starts(with: "mipsn32"):
penvironment = .gnuABIN32
case let x where x.starts(with: "mips64"):
penvironment = .gnuABI64
case let x where x.starts(with: "mipsisa64"):
penvironment = .gnuABI64
case let x where x.starts(with: "mipsisa32"):
penvironment = .gnu
case "mips", "mipsel", "mipsr6", "mipsr6el":
penvironment = .gnu
default:
penvironment = .unknown
}
pvendor = .unknown
}
} else {
parch = .unknown
}
if pobjectFormat == .unknown {
pobjectFormat = ObjectFormat.default(for: parch, os: pos)
}
self.data = str
self.architecture = parch
self.vendor = pvendor
self.os = pos
self.environment = penvironment
self.objectFormat = pobjectFormat
}
/// Create a target triple from string components.
///
/// The environment is assumed to be unknown and the object file format is
/// determined from a combination of the given target architecture and
/// operating system.
///
/// - Parameters:
/// - arch: The target's architecture.
/// - vendor: The target's vendor
/// - os: The target's operating system.
public init(arch: String, vendor: String, os: String) {
self.data = [arch, vendor, os].joined(separator: "-")
self.architecture = Architecture(parse: Substring(arch))
self.vendor = Vendor(parse: Substring(vendor))
self.os = OS(parse: Substring(os))
self.environment = .unknown
self.objectFormat = ObjectFormat.default(for: self.architecture, os: self.os)
}
/// Create a target triple from string components.
///
/// - Parameters:
/// - arch: The target's architecture.
/// - vendor: The target's vendor
/// - os: The target's operating system.
/// - environment: The target's environment.
public init(arch: String, vendor: String, os: String, environment: String) {
self.data = [arch, vendor, os, environment].joined(separator: "-")
self.architecture = Architecture(parse: Substring(arch))
self.vendor = Vendor(parse: Substring(vendor))
self.os = OS(parse: Substring(os))
self.environment = Environment(parse: Substring(environment))
self.objectFormat = ObjectFormat(parse: Substring(environment))
}
public static func == (lhs: Triple, rhs: Triple) -> Bool {
return lhs.data == rhs.data
&& lhs.architecture == rhs.architecture
&& lhs.vendor == rhs.vendor
&& lhs.os == rhs.os
&& lhs.environment == rhs.environment
&& lhs.objectFormat == rhs.objectFormat
}
/// Normalizes a target triple format string.
///
/// The normalization process converts an arbitrary machine specification
/// into the canonical triple form. In particular, it handles the
/// common case in which otherwise valid components are in the wrong order.
///
/// Examples:
///
/// Triple.normalize("---") == "unknown-unknown-unknown-unknown"
/// Triple.normalize("-pc-i386") == "i386-pc-unknown"
/// Triple.normalize("a-b-c-i386") == "i386-a-b-c"
///
/// - Parameter string: The target triple format string.
/// - Returns: A normalized target triple string.
public static func normalize(_ string: String) -> String {
guard let data = LLVMNormalizeTargetTriple(string) else {
return ""
}
defer { LLVMDisposeMessage(data) }
return String(cString: data)
}
/// Returns the architecture component of the triple, if it exists.
///
/// If the environment component does not exist, the empty string is returned.
public var architectureName: Substring {
let split = self.data.split(separator: "-", maxSplits: 3, omittingEmptySubsequences: false)
guard split.count > 0 else {
return ""
}
return split[0]
}
/// Returns the vendor component of the triple, if it exists.
///
/// If the environment component does not exist, the empty string is returned.
public var vendorName: Substring {
let split = self.data.split(separator: "-", maxSplits: 3, omittingEmptySubsequences: false)
guard split.count > 1 else {
return ""
}
return split[1]
}
/// Returns the operating system component of the triple, if it exists.
///
/// If the environment component does not exist, the empty string is returned.
public var osName: Substring {
let split = self.data.split(separator: "-", maxSplits: 3, omittingEmptySubsequences: false)
guard split.count > 2 else {
return ""
}
return split[2]
}
/// Returns the environment component of the triple, if it exists.
///
/// If the environment component does not exist, the empty string is returned.
public var environmentName: Substring {
let split = self.data.split(separator: "-", maxSplits: 3, omittingEmptySubsequences: false)
guard split.count > 3 else {
return ""
}
return split[3]
}
}
extension Triple {
/// Returns whether this environment is a simulator.
public var isSimulatorEnvironment: Bool {
return self.environment == .simulator
}
/// Returns whether this environment is a Windows OS in an MSVC environment.
public var isKnownWindowsMSVCEnvironment: Bool {
return self.os.isWindows && self.environment == .msvc
}
/// Checks if the environment could be MSVC.
public var isWindowsMSVCEnvironment: Bool {
return self.isKnownWindowsMSVCEnvironment ||
(self.os.isWindows && self.environment == .unknown)
}
/// Returns whether this environment is a Windows OS in a CoreCLR environment.
public var isWindowsCoreCLREnvironment: Bool {
return self.os.isWindows && self.environment == .coreCLR
}
/// Returns whether this environment is a Windows OS in an
/// Itanium environment.
public var isWindowsItaniumEnvironment: Bool {
return self.os.isWindows && self.environment == .itanium
}
/// Returns whether this environment is a Windows OS in a Cygnus environment.
public var isWindowsCygwinEnvironment: Bool {
return self.os.isWindows && self.environment == .cygnus
}
/// Returns whether this environment is a Windows OS in a GNU environment.
public var isWindowsGNUEnvironment: Bool {
return self.os.isWindows && self.environment == .gnu
}
/// Returns whether the OS uses glibc.
public var isOSGlibc: Bool {
return (self.os == .linux || self.os == .kFreeBSD ||
self.os == .hurd) &&
!self.isAndroid
}
/// Tests for either Cygwin or MinGW OS
public var isOSCygMing: Bool {
return self.isWindowsCygwinEnvironment || self.isWindowsGNUEnvironment
}
/// Is this a "Windows" OS targeting a "MSVCRT.dll" environment.
public var isOSMSVCRT: Bool {
return self.isWindowsMSVCEnvironment || self.isWindowsGNUEnvironment ||
self.isWindowsItaniumEnvironment
}
/// Returns whether the OS uses the ELF binary format.
public var isOSBinFormatELF: Bool {
return self.objectFormat == .elf
}
/// Returns whether the OS uses the COFF binary format.
public var isOSBinFormatCOFF: Bool {
return self.objectFormat == .coff
}
/// Returns whether the environment is MachO.
public var isOSBinFormatMachO: Bool {
return self.objectFormat == .machO
}
/// Returns whether the OS uses the Wasm binary format.
public var isOSBinFormatWasm: Bool {
return self.objectFormat == .wasm
}
/// Returns whether the OS uses the XCOFF binary format.
public var isOSBinFormatXCOFF: Bool {
return self.objectFormat == .xcoff
}
/// Returns whether the target is the PS4 CPU
public var isPS4CPU: Bool {
return self.architecture == .x86_64 &&
self.vendor == .scei &&
self.os == .ps4
}
/// Returns whether the target is the PS4 platform
public var isPS4: Bool {
return self.vendor == .scei &&
self.os == .ps4
}
/// Returns whether the target is Android
public var isAndroid: Bool {
return self.environment == .android
}
/// Returns whether the environment is musl-libc
public var isMusl: Bool {
return self.environment == .musl ||
self.environment == .muslEABI ||
self.environment == .muslEABIHF
}
/// Returns whether the target is NVPTX (32- or 64-bit).
public var isNVPTX: Bool {
return self.architecture == .nvptx || self.architecture == .nvptx64
}
/// Returns whether the target is Thumb (little and big endian).
public var isThumb: Bool {
return self.architecture == .thumb || self.architecture == .thumbeb
}
/// Returns whether the target is ARM (little and big endian).
public var isARM: Bool {
return self.architecture == .arm || self.architecture == .armeb
}
/// Returns whether the target is AArch64 (little and big endian).
public var isAArch64: Bool {
return self.architecture == .aarch64 || self.architecture == .aarch64_be
}
/// Returns whether the target is MIPS 32-bit (little and big endian).
public var isMIPS32: Bool {
return self.architecture == .mips || self.architecture == .mipsel
}
/// Returns whether the target is MIPS 64-bit (little and big endian).
public var isMIPS64: Bool {
return self.architecture == .mips64 || self.architecture == .mips64el
}
/// Returns whether the target is MIPS (little and big endian, 32- or 64-bit).
public var isMIPS: Bool {
return self.isMIPS32 || self.isMIPS64
}
/// Returns whether the target supports comdat
public var supportsCOMDAT: Bool {
return !self.isOSBinFormatMachO
}
/// Returns whether the target uses emulated TLS as default.
public var hasDefaultEmulatedTLS: Bool {
return self.isAndroid || self.os.isOpenBSD || self.isWindowsCygwinEnvironment
}
}
// MARK: Triple Data
extension Triple {
/// Represents an architecture known to LLVM.
public enum Architecture: String, CaseIterable {
/// An unknown architecture or hardware platform.
case unknown = "unknown"
/// ARM (little endian): arm, armv.*, xscale
case arm = "arm"
/// ARM (big endian): armeb
case armeb = "armeb"
/// AArch64 (little endian): aarch64
case aarch64 = "aarch64"
/// AArch64 (big endian): aarch64_be
case aarch64_be = "aarch64_be"
/// ARC: Synopsys ARC
case arc = "arc"
/// AVR: Atmel AVR microcontroller
case avr = "avr"
/// eBPF or extended BPF or 64-bit BPF (little endian)
case bpfel = "bpfel"
/// eBPF or extended BPF or 64-bit BPF (big endian)
case bpfeb = "bpfeb"
/// Hexagon: hexagon
case hexagon = "hexagon"
/// MIPS: mips, mipsallegrex, mipsr6
case mips = "mips"
/// MIPSEL: mipsel, mipsallegrexe, mipsr6el
case mipsel = "mipsel"
/// MIPS64: mips64, mips64r6, mipsn32, mipsn32r6
case mips64 = "mips64"
/// MIPS64EL: mips64el, mips64r6el, mipsn32el, mipsn32r6el
case mips64el = "mips64el"
/// MSP430: msp430
case msp430 = "msp430"
/// PPC: powerpc
case ppc = "ppc"
/// PPC64: powerpc64, ppu
case ppc64 = "ppc64"
/// PPC64LE: powerpc64le
case ppc64le = "ppc64le"
/// R600: AMD GPUs HD2XXX - HD6XXX
case r600 = "r600"
/// AMDGCN: AMD GCN GPUs
case amdgcn = "amdgcn"
/// RISC-V (32-bit): riscv32
case riscv32 = "riscv32"
/// RISC-V (64-bit): riscv64
case riscv64 = "riscv64"
/// Sparc: sparc
case sparc = "sparc"
/// Sparcv9: Sparcv9
case sparcv9 = "sparcv9"
/// Sparc: (endianness = little). NB: 'Sparcle' is a CPU variant
case sparcel = "sparcel"
/// SystemZ: s390x
case systemz = "systemz"
/// TCE (http://tce.cs.tut.fi/): tce
case tce = "tce"
/// TCE little endian (http://tce.cs.tut.fi/): tcele
case tcele = "tcele"
/// Thumb (little endian): thumb, thumbv.*
case thumb = "thumb"
/// Thumb (big endian): thumbeb
case thumbeb = "thumbeb"
/// X86: i[3-9]86
case x86 = "x86"
/// X86-64: amd64, x86_64
case x86_64 = "x86_64"
/// XCore: xcore
case xcore = "xcore"
/// NVPTX: 32-bit
case nvptx = "nvptx"
/// NVPTX: 64-bit
case nvptx64 = "nvptx64"
/// le32: generic little-endian 32-bit CPU (PNaCl)
case le32 = "le32"
/// le64: generic little-endian 64-bit CPU (PNaCl)
case le64 = "le64"
/// AMDIL
case amdil = "amdil"
/// AMDIL with 64-bit pointers
case amdil64 = "amdil64"
/// AMD HSAIL
case hsail = "hsail"
/// AMD HSAIL with 64-bit pointers
case hsail64 = "hsail64"
/// SPIR: standard portable IR for OpenCL 32-bit version
case spir = "spir"
/// SPIR: standard portable IR for OpenCL 64-bit version
case spir64 = "spir64"
/// Kalimba: generic kalimba
case kalimba = "kalimba"
/// SHAVE: Movidius vector VLIW processors
case shave = "shave"
/// Lanai: Lanai 32-bit
case lanai = "lanai"
/// WebAssembly with 32-bit pointers
case wasm32 = "wasm32"
/// WebAssembly with 64-bit pointers
case wasm64 = "wasm64"
/// 32-bit RenderScript
case renderscript32 = "renderscript32"
/// 64-bit RenderScript
case renderscript64 = "renderscript64"
fileprivate init(parse archName: Substring) {
func parseBPFArch(_ ArchName: Substring) -> Architecture {
if ArchName == "bpf" {
#if _endian(little)
return .bpfel
#elseif _endian(big)
return .bpfeb
#else
#error("Unknown endianness?")
#endif
} else if ArchName == "bpf_be" || ArchName == "bpfeb" {
return .bpfeb
} else if ArchName == "bpf_le" || ArchName == "bpfel" {
return .bpfel
} else {
return .unknown
}
}
func parseARMArch(_ ArchName: Substring) -> Architecture {
enum ARMISA {
case invalid
case arm
case thumb
case aarch64
}
func parseISA(_ Arch: Substring) -> ARMISA {
switch Arch {
case let x where x.starts(with: "aarch64"):
return .aarch64
case let x where x.starts(with: "arm64"):
return .aarch64
case let x where x.starts(with: "thumb"):
return .thumb
case let x where x.starts(with: "arm"):
return .arm
default:
return .invalid
}
}
enum EndianKind {
case invalid
case little
case big
}
func parseArchEndian(_ Arch: Substring) -> EndianKind {
if (Arch.starts(with: "armeb") || Arch.starts(with: "thumbeb") ||
Arch.starts(with: "aarch64_be")) {
return .big
}
if Arch.starts(with: "arm") || Arch.starts(with: "thumb") {
if Arch.hasSuffix("eb") {
return .big
} else {
return .little
}
}
if Arch.starts(with: "aarch64") {
return .little
}
return .invalid
}
let isa = parseISA(archName)
let endian = parseArchEndian(archName)
var arch = Architecture.unknown
switch endian {
case .little:
switch isa {
case .arm:
arch = .arm
case .thumb:
arch = .thumb
case .aarch64:
arch = .aarch64
case .invalid:
break
}
case .big:
switch isa {
case .arm:
arch = .armeb
case .thumb:
arch = .thumbeb
case .aarch64:
arch = .aarch64_be
case .invalid:
break
}
case .invalid:
break
}
let ownedStr = String(archName)
guard let rawArch = LLVMGetARMCanonicalArchName(ownedStr, ownedStr.count) else {
fatalError()
}
let archName = String(cString: rawArch)
guard !archName.isEmpty else {
return .unknown
}
// Thumb only exists in v4+
if isa == .thumb && (ArchName.starts(with: "v2") || ArchName.starts(with: "v3")) {
return .unknown
}
// Thumb only for v6m
let Profile = LLVMARMParseArchProfile(archName, archName.count)
let Version = LLVMARMParseArchVersion(archName, archName.count)
if Profile == LLVMARMProfileKindM && Version == 6 {
if endian == .big {
return .thumbeb
} else {
return .thumb
}
}
return arch
}
switch archName {
case "i386", "i486", "i586", "i686":
self = .x86
// FIXME: Do we need to support these?
case "i786", "i886", "i986":
self = .x86
case "amd64", "x86_64", "x86_64h":
self = .x86_64
case "powerpc", "ppc", "ppc32":
self = .ppc
case "powerpc64", "ppu", "ppc64":
self = .ppc64
case "powerpc64le", "ppc64le":
self = .ppc64le
case "xscale":
self = .arm
case "xscaleeb":
self = .armeb
case "aarch64":
self = .aarch64
case "aarch64_be":
self = .aarch64_be
case "arc":
self = .arc
case "arm64":
self = .aarch64
case "arm":
self = .arm
case "armeb":
self = .armeb
case "thumb":
self = .thumb
case "thumbeb":
self = .thumbeb
case "avr":
self = .avr
case "msp430":
self = .msp430
case "mips", "mipseb", "mipsallegrex", "mipsisa32r6", "mipsr6":
self = .mips
case "mipsel", "mipsallegrexel", "mipsisa32r6el", "mipsr6el":
self = .mipsel
case "mips64", "mips64eb", "mipsn32", "mipsisa64r6", "mips64r6", "mipsn32r6":
self = .mips64
case "mips64el", "mipsn32el", "mipsisa64r6el", "mips64r6el", "mipsn32r6el":
self = .mips64el
case "r600":
self = .r600
case "amdgcn":
self = .amdgcn
case "riscv32":
self = .riscv32
case "riscv64":
self = .riscv64
case "hexagon":
self = .hexagon
case "s390x", "systemz":
self = .systemz
case "sparc":
self = .sparc
case "sparcel":
self = .sparcel
case "sparcv9", "sparc64":
self = .sparcv9
case "tce":
self = .tce
case "tcele":
self = .tcele
case "xcore":
self = .xcore
case "nvptx":
self = .nvptx
case "nvptx64":
self = .nvptx64
case "le32":
self = .le32
case "le64":
self = .le64
case "amdil":
self = .amdil
case "amdil64":
self = .amdil64
case "hsail":
self = .hsail
case "hsail64":
self = .hsail64
case "spir":
self = .spir
case "spir64":
self = .spir64
case let x where x.starts(with: "kalimba"):
self = .kalimba
case "lanai":
self = .lanai
case "shave":
self = .shave
case "wasm32":
self = .wasm32
case "wasm64":
self = .wasm64
case "renderscript32":
self = .renderscript32
case "renderscript64":
self = .renderscript64
default:
if archName.starts(with: "arm") || archName.starts(with: "thumb") || archName.starts(with: "aarch64") {
self = parseARMArch(archName)
} else if archName.starts(with: "bpf") {
self = parseBPFArch(archName)
} else {
self = .unknown
}
}
}
/// Returns the prefix for a family of related architectures.
public var prefix: String {
switch self {
case .aarch64, .aarch64_be:
return "aarch64"
case .arc:
return "arc"
case .arm, .armeb, .thumb, .thumbeb:
return "arm"
case .avr:
return "avr"
case .ppc64, .ppc64le, .ppc:
return "ppc"
case .mips, .mipsel, .mips64, .mips64el:
return "mips"
case .hexagon:
return "hexagon"
case .amdgcn:
return "amdgcn" case .r600:
return "r600"
case .bpfel, .bpfeb:
return "bpf"
case .sparcv9, .sparcel, .sparc:
return "sparc"
case .systemz:
return "s390"
case .x86, .x86_64:
return "x86"
case .xcore:
return "xcore"
// NVPTX intrinsics are namespaced under nvvm.
case .nvptx, .nvptx64:
return "nvvm"
case .le32:
return "le32"
case .le64:
return "le64"
case .amdil, .amdil64:
return "amdil"
case .hsail, .hsail64:
return "hsail"
case .spir, .spir64:
return "spir" case .kalimba:
return "kalimba"
case .lanai:
return "lanai"
case .shave:
return "shave"
case .wasm32, .wasm64:
return "wasm"
case .riscv32, .riscv64:
return "riscv"
default:
return ""
}
}
/// Returns the width in bits for a pointer on this architecture.
public var pointerBitWidth: Int {
switch self {
case .unknown:
return 0
case .avr, .msp430:
return 16
case .arc: fallthrough
case .arm: fallthrough
case .armeb: fallthrough
case .hexagon: fallthrough
case .le32: fallthrough
case .mips: fallthrough
case .mipsel: fallthrough
case .nvptx: fallthrough
case .ppc: fallthrough
case .r600: fallthrough
case .riscv32: fallthrough
case .sparc: fallthrough
case .sparcel: fallthrough
case .tce: fallthrough
case .tcele: fallthrough
case .thumb: fallthrough
case .thumbeb: fallthrough
case .x86: fallthrough
case .xcore: fallthrough
case .amdil: fallthrough
case .hsail: fallthrough
case .spir: fallthrough
case .kalimba: fallthrough
case .lanai: fallthrough
case .shave: fallthrough
case .wasm32: fallthrough
case .renderscript32:
return 32
case .aarch64: fallthrough
case .aarch64_be: fallthrough
case .amdgcn: fallthrough
case .bpfel: fallthrough
case .bpfeb: fallthrough
case .le64: fallthrough
case .mips64: fallthrough
case .mips64el: fallthrough
case .nvptx64: fallthrough
case .ppc64: fallthrough
case .ppc64le: fallthrough
case .riscv64: fallthrough
case .sparcv9: fallthrough
case .systemz: fallthrough
case .x86_64: fallthrough
case .amdil64: fallthrough
case .hsail64: fallthrough
case .spir64: fallthrough
case .wasm64: fallthrough
case .renderscript64:
return 64
}
}
}
/// Represents a vendor known to LLVM.
public enum Vendor: String, CaseIterable {
/// An unknown vendor.
case unknown = "unknown"
/// Apple
case apple = "Apple"
/// PC
case pc = "PC"
/// SCEI
case scei = "SCEI"
/// BGP
case bgp = "BGP"
/// BGQ
case bgq = "BGQ"
/// Freescale
case freescale = "Freescale"
/// IBM
case ibm = "IBM"
/// ImaginationTechnologies
case imaginationTechnologies = "ImaginationTechnologies"
/// MipsTechnologies
case mipsTechnologies = "MipsTechnologies"
/// NVIDIA
case nvidia = "NVIDIA"
/// CSR
case csr = "CSR"
/// Myriad
case myriad = "Myriad"
/// AMD
case amd = "AMD"
/// Mesa
case mesa = "Mesa"
/// SUSE
case suse = "SUSE"
/// OpenEmbedded
case openEmbedded = "OpenEmbedded"
fileprivate init(parse VendorName: Substring) {
switch VendorName {
case "apple":
self = .apple
case "pc":
self = .pc
case "scei":
self = .scei
case "bgp":
self = .bgp
case "bgq":
self = .bgq
case "fsl":
self = .freescale
case "ibm":
self = .ibm
case "img":
self = .imaginationTechnologies
case "mti":
self = .mipsTechnologies
case "nvidia":
self = .nvidia
case "csr":
self = .csr
case "myriad":
self = .myriad
case "amd":
self = .amd
case "mesa":
self = .mesa
case "suse":
self = .suse
case "oe":
self = .openEmbedded
default:
self = .unknown
}
}
}
/// Represents an operating system known to LLVM.
public enum OS: String, CaseIterable {
/// An unknown operating system.
case unknown = "UnknownOS"
/// The Ananas operating system.
case ananas = "Ananas"
/// The CloudABI operating system.
case cloudABI = "CloudABI"
/// The Darwin operating system.
case darwin = "Darwin"
/// The DragonFly operating system.
case dragonFly = "DragonFly"
/// The FreeBSD operating system.
case freeBSD = "FreeBSD"
/// The Fuchsia operating system.
case fuchsia = "Fuchsia"
/// The iOS operating system.
case iOS = "IOS"
/// The GNU/kFreeBSD operating system.
case kFreeBSD = "KFreeBSD"
/// The Linux operating system.
case linux = "Linux"
/// Sony's PS3 operating system.
case lv2 = "Lv2"
/// The macOS operating system.
case macOS = "MacOSX"
/// The NetBSD operating system.
case netBSD = "NetBSD"
/// The OpenBSD operating system.
case openBSD = "OpenBSD"
/// The Solaris operating system.
case solaris = "Solaris"
/// The Win32 operating system.
case win32 = "Win32"
/// The Haiku operating system.
case haiku = "Haiku"
/// The Minix operating system.
case minix = "Minix"
/// The RTEMS operating system.
case rtems = "RTEMS"
/// Native Client
case naCl = "NaCl"
/// BG/P Compute-Node Kernel
case cnk = "CNK"
/// The AIX operating system.
case aix = "AIX"
/// NVIDIA CUDA
case cuda = "CUDA"
/// NVIDIA OpenCL
case nvcl = "NVCL"
/// AMD HSA Runtime
case amdHSA = "AMDHSA"
/// Sony's PS4 operating system.
case ps4 = "PS4"
/// The Intel MCU operating system.
case elfIAMCU = "ELFIAMCU"
/// Apple tvOS.
case tvOS = "TvOS"
/// Apple watchOS.
case watchOS = "WatchOS"
/// The Mesa 3D compute kernel.
case mesa3D = "Mesa3D"
/// The Contiki operating system.
case contiki = "Contiki"
/// AMD PAL Runtime.
case amdPAL = "AMDPAL"
/// HermitCore Unikernel/Multikernel.
case hermitCore = "HermitCore"
/// GNU/Hurd.
case hurd = "Hurd"
/// Experimental WebAssembly OS
case wasi = "WASI"
fileprivate init(parse OSName: Substring) {
switch OSName {
case let x where x.starts(with: "ananas"):
self = .ananas
case let x where x.starts(with: "cloudabi"):
self = .cloudABI
case let x where x.starts(with: "darwin"):
self = .darwin
case let x where x.starts(with: "dragonfly"):
self = .dragonFly
case let x where x.starts(with: "freebsd"):
self = .freeBSD
case let x where x.starts(with: "fuchsia"):
self = .fuchsia
case let x where x.starts(with: "ios"):
self = .tvOS
case let x where x.starts(with: "kfreebsd"):
self = .kFreeBSD
case let x where x.starts(with: "linux"):
self = .linux
case let x where x.starts(with: "lv2"):
self = .lv2
case let x where x.starts(with: "macos"):
self = .macOS
case let x where x.starts(with: "netbsd"):
self = .netBSD
case let x where x.starts(with: "openbsd"):
self = .openBSD
case let x where x.starts(with: "solaris"):
self = .solaris
case let x where x.starts(with: "win32"):
self = .win32
case let x where x.starts(with: "windows"):
self = .win32
case let x where x.starts(with: "haiku"):
self = .haiku
case let x where x.starts(with: "minix"):
self = .minix
case let x where x.starts(with: "rtems"):
self = .rtems
case let x where x.starts(with: "nacl"):
self = .naCl
case let x where x.starts(with: "cnk"):
self = .cnk
case let x where x.starts(with: "aix"):
self = .aix
case let x where x.starts(with: "cuda"):
self = .cuda
case let x where x.starts(with: "nvcl"):
self = .nvcl
case let x where x.starts(with: "amdhsa"):
self = .amdHSA
case let x where x.starts(with: "ps4"):
self = .ps4
case let x where x.starts(with: "elfiamcu"):
self = .elfIAMCU
case let x where x.starts(with: "tvos"):
self = .tvOS
case let x where x.starts(with: "watchos"):
self = .watchOS
case let x where x.starts(with: "mesa3d"):
self = .mesa3D
case let x where x.starts(with: "contiki"):
self = .contiki
case let x where x.starts(with: "amdpal"):
self = .amdPAL
case let x where x.starts(with: "hermit"):
self = .hermitCore
case let x where x.starts(with: "hurd"):
self = .hurd
case let x where x.starts(with: "wasi"):
self = .wasi
default:
self = .unknown
}
}
/// Returns whether the OS is unknown.
public var isUnknown: Bool {
return self == .unknown
}
/// Returns whether this a Mac OS X triple.
///
/// For legacy reasons, LLVM supports both "darwin" and "osx" as
/// macOS triples.
public var isMacOS: Bool {
return self == .darwin || self == .macOS
}
/// Returns whether this an iOS triple.
public var isiOS: Bool {
return self == .iOS || self.isTvOS
}
/// Returns whether this an Apple tvOS triple.
public var isTvOS: Bool {
return self == .tvOS
}
/// Returns whether this an Apple watchOS triple.
public var isWatchOS: Bool {
return self == .watchOS
}
/// Returns whether this a "Darwin" OS (OS X, iOS, or watchOS).
public var isDarwin: Bool {
return self.isMacOS || self.isiOS || self.isWatchOS
}
/// Returns whether the OS is NetBSD.
public var isNetBSD: Bool {
return self == .netBSD
}
/// Returns whether the OS is OpenBSD.
public var isOpenBSD: Bool {
return self == .openBSD
}
/// Returns whether the OS is FreeBSD.
public var isFreeBSD: Bool {
return self == .freeBSD
}
/// Returns whether the OS is Fuchsia.
public var isFuchsia: Bool {
return self == .fuchsia
}
/// Returns whether the OS is DragonFly.
public var isDragonFly: Bool {
return self == .dragonFly
}
/// Returns whether the OS is Solaris.
public var isSolaris: Bool {
return self == .solaris
}
/// Returns whether the OS is IAMCU.
public var isIAMCU: Bool {
return self == .elfIAMCU
}
/// Returns whether the OS is Contiki.
public var isContiki: Bool {
return self == .contiki
}
/// Returns whether the OS is Haiku.
public var isHaiku: Bool {
return self == .haiku
}
/// Returns whether the OS is Windows.
public var isWindows: Bool {
return self == .win32
}
/// Returns whether the OS is NaCl (Native Client)
public var isNaCl: Bool {
return self == .naCl
}
/// Returns whether the OS is Linux.
public var isLinux: Bool {
return self == .linux
}
/// Returns whether the OS is kFreeBSD.
public var isKFreeBSD: Bool {
return self == .kFreeBSD
}
/// Returns whether the OS is Hurd.
public var isHurd: Bool {
return self == .hurd
}
/// Returns whether the OS is WASI.
public var isWASI: Bool {
return self == .wasi
}
/// Returns whether the OS is AIX.
public var isAIX: Bool {
return self == .aix
}
}
/// Represents a runtime environment known to LLVM.
public enum Environment: String, CaseIterable {
/// An unknown environment.
case unknown = "UnknownEnvironment"
/// The generic GNU environment.
case gnu = "GNU"
/// The GNU environment with 32-bit pointers and integers.
case gnuABIN32 = "GNUABIN32"
/// The GNU environment with 64-bit pointers and integers.
case gnuABI64 = "GNUABI64"
/// The GNU environment for ARM EABI.
///
/// Differs from `gnuEABIHF` because it uses software floating point.
case gnuEABI = "GNUEABI"
/// The GNU environment for ARM EABI.
///
/// Differs from `gnuEABI` because it uses hardware floating point.
case gnuEABIHF = "GNUEABIHF"
/// The GNU X32 environment for amd64/x86_64 CPUs using 32-bit integers,
/// longs and pointers.
case gnuX32 = "GNUX32"
/// The _ environment.
case code16 = "CODE16"
/// The ARM EABI environment.
///
/// Differs from `eabiHF` because it uses software floating point.
case eabi = "EABI"
/// The ARM EABI environment.
///
/// Differs from `eabi` because it uses hardware floating point.
case eabiHF = "EABIHF"
/// The Google Android environment.
case android = "Android"
/// The musl environment.
case musl = "Musl"
/// The musl environment for ARM EABI.
///
/// Differs from `muslEABIHF` because it uses software floating point.
case muslEABI = "MuslEABI"
/// The musl environment for ARM EABI.
///
/// Differs from `Differs` because it uses hardware floating point.
case muslEABIHF = "MuslEABIHF"
/// The Microsoft Visual C++ environment.
case msvc = "MSVC"
/// The Intel Itanium environment.
case itanium = "Itanium"
/// The Cygnus environment.
case cygnus = "Cygnus"
/// The Microsoft CoreCLR environment for .NET core.
case coreCLR = "CoreCLR"
/// Simulator variants of other systems, e.g., Apple's iOS
case simulator = "Simulator"
fileprivate init(parse EnvironmentName: Substring) {
switch EnvironmentName {
case let x where x.starts(with: "eabihf"):
self = .eabiHF
case let x where x.starts(with: "eabi"):
self = .eabi
case let x where x.starts(with: "gnuabin32"):
self = .gnuABIN32
case let x where x.starts(with: "gnuabi64"):
self = .gnuABI64
case let x where x.starts(with: "gnueabihf"):
self = .gnuEABIHF
case let x where x.starts(with: "gnueabi"):
self = .gnuEABI
case let x where x.starts(with: "gnux32"):
self = .gnuX32
case let x where x.starts(with: "code16"):
self = .code16
case let x where x.starts(with: "gnu"):
self = .gnu
case let x where x.starts(with: "android"):
self = .android
case let x where x.starts(with: "musleabihf"):
self = .muslEABIHF
case let x where x.starts(with: "musleabi"):
self = .muslEABI
case let x where x.starts(with: "musl"):
self = .musl
case let x where x.starts(with: "msvc"):
self = .msvc
case let x where x.starts(with: "itanium"):
self = .itanium
case let x where x.starts(with: "cygnus"):
self = .cygnus
case let x where x.starts(with: "coreclr"):
self = .coreCLR
case let x where x.starts(with: "simulator"):
self = .simulator
default:
self = .unknown
}
}
/// Returns whether this environment is a GNU environment.
public var isGNU: Bool {
return self == .gnu || self == .gnuABIN32 ||
self == .gnuABI64 || self == .gnuEABI ||
self == .gnuEABIHF || self == .gnuX32
}
}
/// Represents an object file format known to LLVM.
public enum ObjectFormat: String, CaseIterable {
/// An unknown object file format.
case unknown = "unknown"
/// The Common Object File Format.
case coff = "COFF"
/// The Executable and Linkable Format.
case elf = "ELF"
/// The Mach Object format.
case machO = "MachO"
/// The Web Assembly format.
case wasm = "Wasm"
/// The eXtended Common Object File Format.
case xcoff = "XCOFF"
fileprivate init(parse EnvironmentName: Substring) {
switch EnvironmentName {
// "xcoff" must come before "coff" because of the order-dependendent
// pattern matching.
case let x where x.hasSuffix("xcoff"):
self = .xcoff
case let x where x.hasSuffix("coff"):
self = .coff
case let x where x.hasSuffix("elf"):
self = .elf
case let x where x.hasSuffix("macho"):
self = .machO
case let x where x.hasSuffix("wasm"):
self = .wasm
default:
self = .unknown
}
}
/// Returns the default object file format for the given architecture and
/// operating system.
///
/// - Parameters:
/// - arch: The architecture.
/// - os: The operatuing system.
/// - Returns: A default object file format compatible with the given
/// architecture and operating system.
public static func `default`(for arch: Architecture, os: OS) -> ObjectFormat {
switch arch {
case .unknown, .aarch64, .arm, .thumb, .x86, .x86_64:
if os.isDarwin {
return .machO
} else if os.isWindows {
return .coff
}
return .elf
case .aarch64_be, .arc, .amdgcn, .amdil, .amdil64, .armeb, .avr,
.bpfeb, .bpfel, .hexagon, .lanai, .hsail, .hsail64, .kalimba,
.le32, .le64, .mips, .mips64, .mips64el, .mipsel, .msp430,
.nvptx, .nvptx64, .ppc64le,
.r600, .renderscript32, .renderscript64, .riscv32, .riscv64,
.shave, .sparc, .sparcel, .sparcv9, .spir, .spir64, .systemz,
.tce, .tcele, .thumbeb, .xcore:
return .elf
case .ppc, .ppc64:
if os.isDarwin {
return .machO
} else if os.isAIX {
return .xcoff
}
return .elf
case .wasm32, .wasm64:
return .wasm
}
}
}
}
| mit | 655dc90999553eafefb204f5f3830a4c | 28.830593 | 111 | 0.592217 | 3.684057 | false | false | false | false |
douShu/weiboInSwift | weiboInSwift/weiboInSwift/Classes/Tools/SQLiteManager.swift | 1 | 1928 | //
// SQLiteManager.swift
// 14-测试FMDB
//
// Created by 逗叔 on 15/9/23.
// Copyright © 2015年 逗叔. All rights reserved.
//
import Foundation
/// 默认的数据库文件名, 如果以 db 为结尾, 容易被发现
/// SQLite 公开的版本不支持加密, 如果需要加口令, 可以去 gitHub 找一个扩展
private let dbName = "status.db"
class SQLiteManager {
static let sharedManager = SQLiteManager()
/// 能够保证线程安全, 内部有一个串行队列!
let queue: FMDatabaseQueue
/// 1> 在构造函数中, 建立数据库队列
/// private 修饰符可以禁止外部实例化对象, 保证所有的访问都是通过 sharedManager 来调用的
private init() {
let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(dbName)
print(path)
/// 创建数据库队列
/// 如果数据库不存在, 会新建数据库, 否则会直接打开
/// 后续所有根数据库的操作, 都通过 queue 来调用
queue = FMDatabaseQueue(path: path)
createTable()
}
/// 创建数据表
private func createTable() {
let path = NSBundle.mainBundle().pathForResource("tables.sql", ofType: nil)!
let sql = try! String(contentsOfFile: path)
/// executeStatements 执行很多 sql
/// executeQuery 执行查询
/// executeUpdate 执行单条 SQL, 插入/更新/删除, 除了 select 都可以用这个函数
queue.inTransaction { (db, rollback) -> Void in
if db.executeStatements(sql) {
print("创建数据表成功")
} else {
print("创建数据表失败")
}
}
}
} | mit | 5c6463cd1d87bcf7d7a2ab55843df0dc | 25.241379 | 199 | 0.589744 | 4.034483 | false | false | false | false |
hkellaway/swift-functional-intro | swift-functional-intro.playground/Contents.swift | 1 | 7605 | /* Examples of functional programming in Swift inspired by Mary Rose Cook's "A practical introduction to functional programming" http://maryrosecook.com/blog/post/a-practical-introduction-to-functional-programming
*/
import UIKit
/*** What is functional programming? ***/
// Unfunctional
var a = 0
func incrementUnfunctional() -> () {
a += 1
}
incrementUnfunctional()
print(a)
// Functional
a = 0
func incrementFunctional(num: Int) -> Int {
return num + 1
}
a = incrementFunctional(a)
print(a)
///////////////////////////////////////////////////////
/*** Don’t iterate over lists. Use map and reduce. ***/
/* Map - Example 1 */
var languages = ["Objective-C", "Java", "Smalltalk"]
let languageLengths = languages.map { language in count(language) }
print(languageLengths)
let squares = [0, 1, 2, 3, 4].map { x in x * x }
print(squares)
/* Map - Example 2 */
let newLanguages = ["Swift", "Haskell", "Erlang"]
func randomPositiveNumberUpTo(upperBound: Int) -> Int {
return Int(arc4random_uniform(UInt32(upperBound)))
}
func randomElement(array: [String]) -> String {
let randomIndex = randomPositiveNumberUpTo(array.count)
return array[randomIndex]
}
// Unfunctional
for index in 0..<languages.count {
languages[index] = randomElement(newLanguages)
}
print(languages)
// Functional
let randomLanguages = languages.map { _ in randomElement(newLanguages) }
print(randomLanguages)
/* Reduce - Example 1 */
let sum = [0, 1, 2, 3, 4].reduce(0, combine: { $0 + $1 })
print(sum)
// Without shorthand arguments
let numbers = [0, 1, 2, 3, 4]
let startingWith = 0
let sum2 = numbers.reduce(startingWith) {
(runningSum, currentNumber) in
runningSum + currentNumber
}
print(sum2)
/* Reduce - Example 2 */
let greetings = ["Hello, World", "Hello, Swift", "Later, Objective-C"]
func string(str: String, #contains: String) -> Bool {
return str.lowercaseString.rangeOfString(contains.lowercaseString) != nil
}
// Unfunctional
var helloCount = 0
for greeting in greetings {
if(string(greeting, contains:"hello")) {
helloCount += 1
}
}
print(helloCount)
// Functional
let helloCountFunctional = greetings.reduce(0, combine: { $0 + ((string($1, contains:"hello")) ? 1 : 0) })
print(helloCountFunctional)
///////////////////////////////////////////////////////
/*** Write declaratively, not imperatively ***/
// Unfunctional
var time = 5
var carPositions = [1, 1, 1]
while(time > 0) {
time -= 1
print("\n")
for index in 0..<carPositions.count {
if(randomPositiveNumberUpTo(10) > 3) {
carPositions[index] += 1
}
for _ in 0..<carPositions[index] {
print("-")
}
print("\n")
}
}
// Better, but still unfunctional
time = 5
carPositions = [1, 1, 1]
func runStepOfRace() -> () {
time -= 1
moveCars()
}
func draw() {
print("\n")
for carPosition in carPositions {
drawCar(carPosition)
}
}
func moveCars() -> () {
for index in 0..<carPositions.count {
if(randomPositiveNumberUpTo(10) > 3) {
carPositions[index] += 1
}
}
}
func drawCar(carPosition: Int) -> () {
for _ in 0..<carPosition {
print("-")
}
print("\n")
}
while(time > 0) {
runStepOfRace()
draw()
}
// Functional
typealias Time = Int
typealias Positions = [Int]
typealias State = (time: Time, positions: Positions)
func moveCarsFunctional(positions: [Int]) -> [Int] {
return positions.map { position in (randomPositiveNumberUpTo(10) > 3) ? position + 1 : position }
}
func outputCar(carPosition: Int) -> String {
let output = (0..<carPosition).map { _ in "-" }
return join("", output)
}
func runStepOfRaceFunctional(state: State) -> State {
let newTime = state.time - 1
let newPositions = moveCarsFunctional(state.positions)
return (newTime, newPositions)
}
func drawFunctional(state: State) -> () {
let outputs = state.positions.map { position in outputCar(position) }
print(join("\n", outputs))
}
func race(state: State) -> () {
drawFunctional(state)
if(state.time > 1) {
print("\n\n")
race(runStepOfRaceFunctional(state))
}
}
let state: State = (time: 5, positions: [1, 1, 1])
race(state)
///////////////////////////////////////////////////////
/*** Use pipelines ***/
// Unfunctional
let bands: [ [String : String] ] = [
["name" : "sunset rubdown", "country" : "UK"],
["name" : "women", "country" : "Germany"],
["name" : "a silver mt. zion", "country" : "Spain"]
]
var bandsMutable = bands
func formatBands(inout bands: [ [String : String] ]) -> () {
var newBands: [ [String : String] ] = []
for band in bands {
var newBand: [String : String] = band
newBand["country"] = "Canada"
newBand["name"] = newBand["name"]!.capitalizedString
newBands.append(newBand)
}
bands = newBands
}
formatBands(&bandsMutable)
print(bandsMutable)
// Functional 1
typealias BandProperty = String
typealias Band = [String : BandProperty]
typealias BandTransform = Band -> Band
typealias BandPropertyTransform = BandProperty -> BandProperty
func call(#function: BandPropertyTransform, onValueForKey key: String) -> BandTransform {
return {
band in
var newBand = band
newBand[key] = function(band[key]!)
return newBand
}
}
let canada: BandPropertyTransform = { _ in return "Canada" }
let capitalize: BandPropertyTransform = { return $0.capitalizedString }
let setCanadaAsCountry: BandTransform = call(function: canada, onValueForKey: "country")
let capitalizeName: BandTransform = call(function: capitalize, onValueForKey: "name")
func formattedBands(bands: [Band], functions: [BandTransform]) -> [Band] {
return bands.map {
band in
functions.reduce(band) {
(currentBand, function) in
function(currentBand)
}
}
}
// OR shorthand:
func formattedBandsShorthand(bands: [Band], functions: [BandTransform]) -> [Band] {
return bands.map {
functions.reduce($0) { $1($0) }
}
}
print(bands)
print(formattedBands(bands, [setCanadaAsCountry, capitalizeName]))
// Functional 2
func composeBandTransforms(transform1: BandTransform, transform2: BandTransform) -> BandTransform {
return {
band in
transform2(transform1(band))
}
}
let myBandTransform = composeBandTransforms(setCanadaAsCountry, capitalizeName)
let formattedBands = bands.map { band in myBandTransform(band) }
print(bands)
print(formattedBands)
// Functional 3
func pluck(key: String) -> BandTransform {
return {
band in
var newBand: Band = [:]
newBand[key] = band[key]
return newBand
}
}
let pluckName = pluck("name")
print(formattedBands(bands, [pluckName]))
///////////////////////////////////////////////////////
/*** Extra Credit: Generics ***/
// Generic version of randomElement(_:)
func randomElement<T>(array: [T]) -> T {
let randomIndex = randomPositiveNumberUpTo(array.count)
return array[randomIndex]
}
// Generic version of formattedBands(_:fns:)
func updatedItems<T>(items: [T], functions: [T -> T]) -> [T] {
return items.map {
functions.reduce($0) { $1($0) }
}
}
// Generic version of composeBandTransforms(_:transform2:)
func composeTransforms<T>(transform1: T -> T, transform2: T -> T) -> T -> T {
return {
transform2(transform1($0))
}
}
| mit | 6e11090fda2c36bbcadf0a7f77d07b16 | 19.944904 | 213 | 0.614626 | 3.615311 | false | false | false | false |
johnlui/Swift-MMP | Frameworks/SwiftNotice.swift | 1 | 16617 | //
// SwiftNotice.swift
// SwiftNotice
//
// Created by JohnLui on 15/4/15.
// Copyright (c) 2015年 com.lvwenhan. All rights reserved.
//
import Foundation
import UIKit
private let sn_topBar: Int = 1001
extension UIResponder {
/// wait with your own animated images
@discardableResult
func pleaseWaitWithImages(_ imageNames: Array<UIImage>, timeInterval: Int) -> UIWindow{
return SwiftNotice.wait(imageNames, timeInterval: timeInterval)
}
// api changed from v3.3
@discardableResult
func noticeTop(_ text: String, autoClear: Bool = true, autoClearTime: Int = 1) -> UIWindow{
return SwiftNotice.noticeOnStatusBar(text, autoClear: autoClear, autoClearTime: autoClearTime)
}
// new apis from v3.3
@discardableResult
func noticeSuccess(_ text: String, autoClear: Bool = false, autoClearTime: Int = 3) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.success, text: text, autoClear: autoClear, autoClearTime: autoClearTime)
}
@discardableResult
func noticeError(_ text: String, autoClear: Bool = false, autoClearTime: Int = 3) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.error, text: text, autoClear: autoClear, autoClearTime: autoClearTime)
}
@discardableResult
func noticeInfo(_ text: String, autoClear: Bool = false, autoClearTime: Int = 3) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.info, text: text, autoClear: autoClear, autoClearTime: autoClearTime)
}
// old apis
@discardableResult
func successNotice(_ text: String, autoClear: Bool = true) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.success, text: text, autoClear: autoClear, autoClearTime: 3)
}
@discardableResult
func errorNotice(_ text: String, autoClear: Bool = true) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.error, text: text, autoClear: autoClear, autoClearTime: 3)
}
@discardableResult
func infoNotice(_ text: String, autoClear: Bool = true) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.info, text: text, autoClear: autoClear, autoClearTime: 3)
}
@discardableResult
func notice(_ text: String, type: NoticeType, autoClear: Bool, autoClearTime: Int = 3) -> UIWindow{
return SwiftNotice.showNoticeWithText(type, text: text, autoClear: autoClear, autoClearTime: autoClearTime)
}
@discardableResult
func pleaseWait() -> UIWindow{
return SwiftNotice.wait()
}
@discardableResult
func noticeOnlyText(_ text: String) -> UIWindow{
return SwiftNotice.showText(text)
}
func clearAllNotice() {
SwiftNotice.clear()
}
}
enum NoticeType{
case success
case error
case info
}
class SwiftNotice: NSObject {
static var windows = Array<UIWindow!>()
static let rv = UIApplication.shared.keyWindow?.subviews.first as UIView!
static var timer: DispatchSource!
static var timerTimes = 0
/* just for iOS 8
*/
static var degree: Double {
get {
return [0, 0, 180, 270, 90][UIApplication.shared.statusBarOrientation.hashValue] as Double
}
}
// fix https://github.com/johnlui/SwiftNotice/issues/2
// thanks broccolii(https://github.com/broccolii) and his PR https://github.com/johnlui/SwiftNotice/pull/5
static func clear() {
self.cancelPreviousPerformRequests(withTarget: self)
if let _ = timer {
timer.cancel()
timer = nil
timerTimes = 0
}
windows.removeAll(keepingCapacity: false)
}
@discardableResult
static func noticeOnStatusBar(_ text: String, autoClear: Bool, autoClearTime: Int) -> UIWindow{
let frame = UIApplication.shared.statusBarFrame
let window = UIWindow()
window.backgroundColor = UIColor.clear
let view = UIView()
view.backgroundColor = UIColor(red: 0x6a/0x100, green: 0xb4/0x100, blue: 0x9f/0x100, alpha: 1)
let label = UILabel(frame: frame)
label.textAlignment = NSTextAlignment.center
label.font = UIFont.systemFont(ofSize: 12)
label.textColor = UIColor.white
label.text = text
view.addSubview(label)
window.frame = frame
view.frame = frame
if let version = Double(UIDevice.current.systemVersion),
version < 9.0 {
// change center
var array = [UIScreen.main.bounds.width, UIScreen.main.bounds.height]
array = array.sorted(by: <)
let screenWidth = array[0]
let screenHeight = array[1]
let x = [0, screenWidth/2, screenWidth/2, 10, screenWidth-10][UIApplication.shared.statusBarOrientation.hashValue] as CGFloat
let y = [0, 10, screenHeight-10, screenHeight/2, screenHeight/2][UIApplication.shared.statusBarOrientation.hashValue] as CGFloat
window.center = CGPoint(x: x, y: y)
// change direction
window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180))
}
window.windowLevel = UIWindowLevelStatusBar
window.isHidden = false
window.addSubview(view)
windows.append(window)
var origPoint = view.frame.origin
origPoint.y = -(view.frame.size.height)
let destPoint = view.frame.origin
view.tag = sn_topBar
view.frame = CGRect(origin: origPoint, size: view.frame.size)
UIView.animate(withDuration: 0.3, animations: {
view.frame = CGRect(origin: destPoint, size: view.frame.size)
}, completion: { b in
if autoClear {
let selector = #selector(SwiftNotice.hideNotice(_:))
self.perform(selector, with: window, afterDelay: TimeInterval(autoClearTime))
}
})
return window
}
@discardableResult
static func wait(_ imageNames: Array<UIImage> = Array<UIImage>(), timeInterval: Int = 0) -> UIWindow {
let frame = CGRect(x: 0, y: 0, width: 78, height: 78)
let window = UIWindow()
window.backgroundColor = UIColor.clear
let mainView = UIView()
mainView.layer.cornerRadius = 12
mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8)
if imageNames.count > 0 {
if imageNames.count > timerTimes {
let iv = UIImageView(frame: frame)
iv.image = imageNames.first!
iv.contentMode = UIViewContentMode.scaleAspectFit
mainView.addSubview(iv)
timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: DispatchQueue.main) as! DispatchSource
timer.scheduleRepeating(deadline: DispatchTime.now(), interval: DispatchTimeInterval.milliseconds(timeInterval))
timer.setEventHandler(handler: { () -> Void in
let name = imageNames[timerTimes % imageNames.count]
iv.image = name
timerTimes += 1
})
timer.resume()
}
} else {
let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
ai.frame = CGRect(x: 21, y: 21, width: 36, height: 36)
ai.startAnimating()
mainView.addSubview(ai)
}
window.frame = frame
mainView.frame = frame
window.center = rv!.center
if let version = Double(UIDevice.current.systemVersion),
version < 9.0 {
// change center
window.center = getRealCenter()
// change direction
window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180))
}
window.windowLevel = UIWindowLevelAlert
window.isHidden = false
window.addSubview(mainView)
windows.append(window)
mainView.alpha = 0.0
UIView.animate(withDuration: 0.2, animations: {
mainView.alpha = 1
})
return window
}
@discardableResult
static func showText(_ text: String, autoClear: Bool=true, autoClearTime: Int=2) -> UIWindow {
let window = UIWindow()
window.backgroundColor = UIColor.clear
let mainView = UIView()
mainView.layer.cornerRadius = 12
mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8)
let label = UILabel()
label.text = text
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 13)
label.textAlignment = NSTextAlignment.center
label.textColor = UIColor.white
label.sizeToFit()
mainView.addSubview(label)
let superFrame = CGRect(x: 0, y: 0, width: label.frame.width + 50 , height: label.frame.height + 30)
window.frame = superFrame
mainView.frame = superFrame
label.center = mainView.center
window.center = rv!.center
if let version = Double(UIDevice.current.systemVersion),
version < 9.0 {
// change center
window.center = getRealCenter()
// change direction
window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180))
}
window.windowLevel = UIWindowLevelAlert
window.isHidden = false
window.addSubview(mainView)
windows.append(window)
if autoClear {
let selector = #selector(SwiftNotice.hideNotice(_:))
self.perform(selector, with: window, afterDelay: TimeInterval(autoClearTime))
}
return window
}
@discardableResult
static func showNoticeWithText(_ type: NoticeType,text: String, autoClear: Bool, autoClearTime: Int) -> UIWindow {
let frame = CGRect(x: 0, y: 0, width: 90, height: 90)
let window = UIWindow()
window.backgroundColor = UIColor.clear
let mainView = UIView()
mainView.layer.cornerRadius = 10
mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.7)
var image = UIImage()
switch type {
case .success:
image = SwiftNoticeSDK.imageOfCheckmark
case .error:
image = SwiftNoticeSDK.imageOfCross
case .info:
image = SwiftNoticeSDK.imageOfInfo
}
let checkmarkView = UIImageView(image: image)
checkmarkView.frame = CGRect(x: 27, y: 15, width: 36, height: 36)
mainView.addSubview(checkmarkView)
let label = UILabel(frame: CGRect(x: 0, y: 60, width: 90, height: 16))
label.font = UIFont.systemFont(ofSize: 13)
label.textColor = UIColor.white
label.text = text
label.textAlignment = NSTextAlignment.center
mainView.addSubview(label)
window.frame = frame
mainView.frame = frame
window.center = rv!.center
if let version = Double(UIDevice.current.systemVersion),
version < 9.0 {
// change center
window.center = getRealCenter()
// change direction
window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180))
}
window.windowLevel = UIWindowLevelAlert
window.center = rv!.center
window.isHidden = false
window.addSubview(mainView)
windows.append(window)
mainView.alpha = 0.0
UIView.animate(withDuration: 0.2, animations: {
mainView.alpha = 1
})
if autoClear {
let selector = #selector(SwiftNotice.hideNotice(_:))
self.perform(selector, with: window, afterDelay: TimeInterval(autoClearTime))
}
return window
}
// fix https://github.com/johnlui/SwiftNotice/issues/2
@objc static func hideNotice(_ sender: AnyObject) {
if let window = sender as? UIWindow {
if let v = window.subviews.first {
UIView.animate(withDuration: 0.2, animations: {
if v.tag == sn_topBar {
v.frame = CGRect(x: 0, y: -v.frame.height, width: v.frame.width, height: v.frame.height)
}
v.alpha = 0
}, completion: { b in
if let index = windows.index(where: { (item) -> Bool in
return item == window
}) {
windows.remove(at: index)
}
})
}
}
}
// just for iOS 8
static func getRealCenter() -> CGPoint {
if UIApplication.shared.statusBarOrientation.hashValue >= 3 {
return CGPoint(x: rv!.center.y, y: rv!.center.x)
} else {
return rv!.center
}
}
}
class SwiftNoticeSDK {
struct Cache {
static var imageOfCheckmark: UIImage?
static var imageOfCross: UIImage?
static var imageOfInfo: UIImage?
}
class func draw(_ type: NoticeType) {
let checkmarkShapePath = UIBezierPath()
// draw circle
checkmarkShapePath.move(to: CGPoint(x: 36, y: 18))
checkmarkShapePath.addArc(withCenter: CGPoint(x: 18, y: 18), radius: 17.5, startAngle: 0, endAngle: CGFloat(Double.pi*2), clockwise: true)
checkmarkShapePath.close()
switch type {
case .success: // draw checkmark
checkmarkShapePath.move(to: CGPoint(x: 10, y: 18))
checkmarkShapePath.addLine(to: CGPoint(x: 16, y: 24))
checkmarkShapePath.addLine(to: CGPoint(x: 27, y: 13))
checkmarkShapePath.move(to: CGPoint(x: 10, y: 18))
checkmarkShapePath.close()
case .error: // draw X
checkmarkShapePath.move(to: CGPoint(x: 10, y: 10))
checkmarkShapePath.addLine(to: CGPoint(x: 26, y: 26))
checkmarkShapePath.move(to: CGPoint(x: 10, y: 26))
checkmarkShapePath.addLine(to: CGPoint(x: 26, y: 10))
checkmarkShapePath.move(to: CGPoint(x: 10, y: 10))
checkmarkShapePath.close()
case .info:
checkmarkShapePath.move(to: CGPoint(x: 18, y: 6))
checkmarkShapePath.addLine(to: CGPoint(x: 18, y: 22))
checkmarkShapePath.move(to: CGPoint(x: 18, y: 6))
checkmarkShapePath.close()
UIColor.white.setStroke()
checkmarkShapePath.stroke()
let checkmarkShapePath = UIBezierPath()
checkmarkShapePath.move(to: CGPoint(x: 18, y: 27))
checkmarkShapePath.addArc(withCenter: CGPoint(x: 18, y: 27), radius: 1, startAngle: 0, endAngle: CGFloat(Double.pi*2), clockwise: true)
checkmarkShapePath.close()
UIColor.white.setFill()
checkmarkShapePath.fill()
}
UIColor.white.setStroke()
checkmarkShapePath.stroke()
}
class var imageOfCheckmark: UIImage {
if (Cache.imageOfCheckmark != nil) {
return Cache.imageOfCheckmark!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 36, height: 36), false, 0)
SwiftNoticeSDK.draw(NoticeType.success)
Cache.imageOfCheckmark = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfCheckmark!
}
class var imageOfCross: UIImage {
if (Cache.imageOfCross != nil) {
return Cache.imageOfCross!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 36, height: 36), false, 0)
SwiftNoticeSDK.draw(NoticeType.error)
Cache.imageOfCross = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfCross!
}
class var imageOfInfo: UIImage {
if (Cache.imageOfInfo != nil) {
return Cache.imageOfInfo!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 36, height: 36), false, 0)
SwiftNoticeSDK.draw(NoticeType.info)
Cache.imageOfInfo = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfInfo!
}
}
extension UIWindow{
func hide(){
SwiftNotice.hideNotice(self)
}
}
| mit | 1eb1b7e141278e987d43dbf0e98f796f | 36.675737 | 153 | 0.607704 | 4.762109 | false | false | false | false |
zneak/swift-chess | chess/Player.swift | 1 | 397 | //
// Player.swift
// chess
//
// Created by Félix on 16-02-12.
// Copyright © 2016 Félix Cloutier. All rights reserved.
//
import Foundation
enum Player {
case Black
case White
var direction: Int {
return self == .Black ? -1 : 1
}
var opponent: Player {
return self == .Black ? .White : .Black
}
var description: String {
return self == .Black ? "Black" : "White"
}
} | gpl-3.0 | 5d372ac62c593b18db16526479b4df15 | 14.192308 | 57 | 0.619289 | 3.007634 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift | 37 | 2192 | //
// ControlTarget.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS) || os(macOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
#if os(iOS) || os(tvOS)
import UIKit
typealias Control = UIKit.UIControl
typealias ControlEvents = UIKit.UIControlEvents
#elseif os(macOS)
import Cocoa
typealias Control = Cocoa.NSControl
#endif
// This should be only used from `MainScheduler`
class ControlTarget: RxTarget {
typealias Callback = (Control) -> Void
let selector: Selector = #selector(ControlTarget.eventHandler(_:))
weak var control: Control?
#if os(iOS) || os(tvOS)
let controlEvents: UIControlEvents
#endif
var callback: Callback?
#if os(iOS) || os(tvOS)
init(control: Control, controlEvents: UIControlEvents, callback: @escaping Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.controlEvents = controlEvents
self.callback = callback
super.init()
control.addTarget(self, action: selector, for: controlEvents)
let method = self.method(for: selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#elseif os(macOS)
init(control: Control, callback: @escaping Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.callback = callback
super.init()
control.target = self
control.action = selector
let method = self.method(for: selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#endif
func eventHandler(_ sender: Control!) {
if let callback = self.callback, let control = self.control {
callback(control)
}
}
override func dispose() {
super.dispose()
#if os(iOS) || os(tvOS)
self.control?.removeTarget(self, action: self.selector, for: self.controlEvents)
#elseif os(macOS)
self.control?.target = nil
self.control?.action = nil
#endif
self.callback = nil
}
}
#endif
| apache-2.0 | 175128315143f32805222ec6e0657ea8 | 22.815217 | 90 | 0.637152 | 4.270955 | false | false | false | false |
darkf/darkfo | wrappers/macos/darkfo/ViewController.swift | 1 | 2117 | //
// ViewController.swift
// darkfo
//
// Created by Max Desiatov on 28/02/2019.
// Copyright © 2019 Max Desiatov. DarkFO is licensed under the terms of the
// Apache 2 license. See LICENSE.txt for the full license text.
//
import AppKit
import Foundation
import WebKit
final class ViewController: NSViewController {
private let webView = WKWebView(frame: .zero)
private var preferences: NSWindowController?
private var urlParameter = "artemple"
init() {
super.init(nibName: nil, bundle: nil)
}
override func loadView() {
view = NSView()
}
override func viewDidLoad() {
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
NSLayoutConstraint.activate([
view.widthAnchor.constraint(greaterThanOrEqualToConstant: 800),
// for some reason 700 leaves empty pixels at the bottom
view.heightAnchor.constraint(greaterThanOrEqualToConstant: 699),
webView.topAnchor.constraint(equalTo: view.topAnchor),
webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
reload()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func reload() {
let req = URLRequest(url:
URL(string: "http://localhost:8000/play.html?\(urlParameter)")!
)
webView.load(req)
}
@IBAction func preferencesPressed(_ sender: NSMenuItem) {
defer { preferences?.window?.makeKey() }
guard preferences == nil else {
return
}
let window = NSWindow(contentViewController: PreferencesController(
defaultValue: urlParameter
) { [weak self] in
self?.urlParameter = $0
self?.reload()
})
window.title = "Preferences"
window.delegate = self
preferences = NSWindowController(window: window)
preferences?.showWindow(self)
}
}
extension ViewController: NSWindowDelegate {
func windowWillClose(_ notification: Notification) {
preferences = nil
}
}
| apache-2.0 | 29ca3a45eddce3c570e79d872b649aac | 24.804878 | 76 | 0.702741 | 4.521368 | false | false | false | false |
kunitoku/RssReader | RssReaderSwift4/ListViewController.swift | 1 | 4388 |
import UIKit
import Ji
import SDWebImage
// リストビュー管理クラス
class ListViewController: UITableViewController {
var xml: ListViewXmlParser?
// Viewの表示が完了後に呼び出されるメソッド
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// XML解析
xml = ListViewXmlParser()
xml?.parse(url: Setting.RssUrl, completionHandler: { () -> () in
self.tableView.reloadData()
})
}
// セルの個数を指定する
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return xml?.items.count ?? 0
}
// セルに値を設定する
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ListViewCell", for: indexPath) as? ListViewCell else {
fatalError("Invalid cell")
}
guard let x = xml else {
return cell
}
cell.item = x.items[indexPath.row]
return cell
}
// 一覧からWebView画面へ行く時に呼び出されるメソッド
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let x = xml else {
return
}
// 選択した項目情報をWebView画面に渡す
if let indexPath = self.tableView.indexPathForSelectedRow {
let controller = segue.destination as! DetailViewController
controller.item = x.items[indexPath.row]
}
}
}
// リストビューのセルクラス
class ListViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var thumbnail: UIImageView!
var item: Item? {
didSet {
titleLabel.text = item?.title
descriptionLabel.text = item?.detail
thumbnail.sd_setImage(with: item?.imgUrl)
}
}
}
// XML解析クラス
class ListViewXmlParser: NSObject, XMLParserDelegate {
var item: Item?
var items = [Item]()
var currentString = ""
var completionHandler: (() -> ())?
/// 指定のURLからXMLを解析する
///
/// - Parameters:
/// - url: 解析するURLを指定
/// - completionHandler: 解析完了時に呼び出されるメソッドを指定
func parse(url: String, completionHandler: @escaping () -> ()) {
guard let url = URL(string: url) else {
return
}
guard let xml_parser = XMLParser(contentsOf: url) else {
return
}
items = []
self.completionHandler = completionHandler
xml_parser.delegate = self
xml_parser.parse()
}
// 解析中に要素の開始タグがあったときに呼び出されるメソッド
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
currentString = ""
if elementName == "item" {
item = Item()
}
}
// 開始タグと終了タグでくくられたデータがあったときに呼び出されるメソッド
func parser(_ parser: XMLParser, foundCharacters string: String) {
currentString += string
}
// 解析中に要素の終了タグがあったときに呼び出されるメソッド
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
guard let i = item else {
return
}
switch elementName {
case "title":
i.title = currentString
case "description":
i.detail = currentString
case "link":
i.link = currentString
case "content:encoded":
i.jiDoc = Ji(htmlString: currentString)
case "item":
items.append(i)
default:
break
}
}
// 解析終了時に呼び出されるメソッド
func parserDidEndDocument(_ parser: XMLParser) {
completionHandler?()
}
}
| mit | 2cecbd61fdec2f95378e5e9d42f3a666 | 26.64539 | 179 | 0.585428 | 4.730583 | false | false | false | false |
MaorS/macOS-PasswordManager | PasswordManager/Constants.swift | 1 | 614 | //
// Constants.swift
// PasswordManager
//
// Created by Maor Shams on 08/07/2017.
// Copyright © 2017 Maor Shams. All rights reserved.
//
import Foundation
struct Constants{
// CORE DATA
static let APP_NAME = "appName"
static let USERNAME = "userName"
static let PASSWORD = "password"
// USER DEFAULT
static let PASSWORD_ENCRYPTION = "password_encryption"
static let LOGOUT_TIMER = "logout_timer"
// SEGUE
static let MAIN_MENU_SEGUE = "mainMenuSegue"
static let PASSWORD_EDITOR_SEGUE = "passwordEditorSegue"
static let BACK_SEGUE = "backSegue"
}
| mit | 96edc5bd0151822902f6bddc3aac1bd7 | 22.576923 | 60 | 0.66721 | 3.783951 | false | false | false | false |
anasmeister/nRF-Coventry-University | nRF Toolbox/HTS/NORHTSViewController.swift | 1 | 15798 | //
// NORHTSViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 09/05/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
//// Edited by Anastasios Panagoulias on 11/01/07
import UIKit
import CoreBluetooth
class NORHTSViewController: NORBaseViewController, CBCentralManagerDelegate, CBPeripheralDelegate, NORScannerDelegate {
//MARK: - ViewController properties
var bluetoothManager : CBCentralManager?
var connectedPeripheral : CBPeripheral?
var htsServiceUUID : CBUUID
var htsMeasurementCharacteristicUUID : CBUUID
var batteryServiceUUID : CBUUID
var batteryLevelCharacteristicUUID : CBUUID
var temperatureValueFahrenheit : Bool?
var temperatureValue : Double?
//MARK: - ViewController outlets
@IBOutlet weak var type: UILabel!
@IBOutlet weak var timestamp: UILabel!
@IBOutlet weak var connectionButon: UIButton!
@IBOutlet weak var temperatureUnit: UILabel!
@IBOutlet weak var temperature: UILabel!
@IBOutlet weak var deviceName: UILabel!
@IBOutlet weak var battery: UIButton!
@IBOutlet weak var verticalLabel: UILabel!
@IBOutlet weak var degreeControl: UISegmentedControl!
//MARK: - ViewControllerActions
@IBAction func aboutButtonTapped(_ sender: AnyObject) {
self.showAbout(message: NORAppUtilities.getHelpTextForService(service: .htm))
}
@IBAction func connectionButtonTapped(_ sender: AnyObject) {
if connectedPeripheral != nil {
bluetoothManager?.cancelPeripheralConnection(connectedPeripheral!)
}
}
@IBAction func degreeHasChanged(_ sender: AnyObject) {
let control = sender as! UISegmentedControl
if (control.selectedSegmentIndex == 0) {
// Celsius
temperatureValueFahrenheit = false
UserDefaults.standard.set(false, forKey: "fahrenheit")
self.temperatureUnit.text = "°C"
if temperatureValue != nil {
temperatureValue = (temperatureValue! - 32.0) * 5.0 / 9.0
}
} else {
// Fahrenheit
temperatureValueFahrenheit = true
UserDefaults.standard.set(true, forKey: "fahrenheit")
self.temperatureUnit.text = "°F"
if temperatureValue != nil {
temperatureValue = temperatureValue! * 9.0 / 5.0 + 32.0
}
}
UserDefaults.standard.synchronize()
if temperatureValue != nil {
self.temperature.text = String(format:"%.2f", temperatureValue!)
}
}
//MARK: - Segue handling
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// The 'scan' seque will be performed only if connectedPeripheral == nil (if we are not connected already).
return identifier != "scan" || connectedPeripheral == nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "scan" {
// Set this contoller as scanner delegate
let navigationController = segue.destination as! UINavigationController
let scannerController = navigationController.childViewControllerForStatusBarHidden as! NORScannerViewController
scannerController.filterUUID = htsServiceUUID
scannerController.delegate = self
}
}
//MARK: - UIViewControllerDelegate
required init?(coder aDecoder: NSCoder) {
// Custom initialization
htsServiceUUID = CBUUID(string: NORServiceIdentifiers.htsServiceUUIDString)
htsMeasurementCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.htsMeasurementCharacteristicUUIDString)
batteryServiceUUID = CBUUID(string: NORServiceIdentifiers.batteryServiceUUIDString)
batteryLevelCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.batteryLevelCharacteristicUUIDString)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.verticalLabel.transform = CGAffineTransform(translationX: -185.0, y: 0.0).rotated(by: CGFloat(-M_PI_2))
self.updateUnits()
}
//MARK: - CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard error == nil else {
print("An error occured while discovering services: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return;
}
for aService : CBService in peripheral.services! {
// Discovers the characteristics for a given service
if aService.uuid == htsServiceUUID {
peripheral.discoverCharacteristics([htsMeasurementCharacteristicUUID], for: aService)
}else if aService.uuid == batteryServiceUUID {
peripheral.discoverCharacteristics([batteryLevelCharacteristicUUID], for: aService)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard error == nil else {
print("Error occurred while discovering characteristic: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return
}
// Characteristics for one of those services has been found
if service.uuid == htsServiceUUID {
for aCharacteristic : CBCharacteristic in service.characteristics! {
if aCharacteristic.uuid == htsMeasurementCharacteristicUUID {
// Enable notification on data characteristic
peripheral.setNotifyValue(true, for: aCharacteristic)
break
}
}
} else if service.uuid == batteryServiceUUID {
for aCharacteristic : CBCharacteristic in service.characteristics! {
if aCharacteristic.uuid == batteryLevelCharacteristicUUID {
peripheral.readValue(for: aCharacteristic)
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
print("Error occurred while updating characteristic value: \(error!.localizedDescription)")
return
}
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
// Decode the characteristic data
let data = characteristic.value
var array = UnsafeMutablePointer<UInt8>(OpaquePointer(((data as NSData?)?.bytes)!))
if characteristic.uuid == self.batteryLevelCharacteristicUUID {
let batteryLevel = NORCharacteristicReader.readUInt8Value(ptr: &array)
let text = "\(batteryLevel)%"
self.battery.setTitle(text, for: UIControlState.disabled)
if self.battery.tag == 0 {
// If battery level notifications are available, enable them
if characteristic.properties.rawValue & CBCharacteristicProperties.notify.rawValue > 0 {
self.battery.tag = 1; // mark that we have enabled notifications
// Enable notification on data characteristic
peripheral.setNotifyValue(true, for: characteristic)
}
}
} else if characteristic.uuid == self.htsMeasurementCharacteristicUUID {
let flags = NORCharacteristicReader.readUInt8Value(ptr: &array)
let tempInFahrenheit : Bool = (flags & 0x01) > 0
let timestampPresent : Bool = (flags & 0x02) > 0
let typePresent : Bool = (flags & 0x04) > 0
var tempValue : Float = NORCharacteristicReader.readFloatValue(ptr: &array)
if tempInFahrenheit == false && self.temperatureValueFahrenheit! == true {
tempValue = tempValue * 9.0 / 5.0 + 32.0
}
if tempInFahrenheit == true && self.temperatureValueFahrenheit == false {
tempValue = (tempValue - 32.0) * 5.0 / 9.0
}
self.temperatureValue = Double(tempValue)
self.temperature.text = String(format: "%.2f", tempValue)
if timestampPresent == true {
let date = NORCharacteristicReader.readDateTime(ptr: &array)
let dateFormat = DateFormatter()
dateFormat.dateFormat = "dd.MM.yyyy, hh:mm"
let dateFormattedString = dateFormat.string(from: date)
self.timestamp.text = dateFormattedString
} else {
self.timestamp.text = "Date n/a"
}
/* temperature type */
if typePresent == true {
let type = NORCharacteristicReader.readUInt8Value(ptr: &array)
var location : NSString = ""
switch (type)
{
case 0x01:
location = "Armpit";
break;
case 0x02:
location = "Body - general";
break;
case 0x03:
location = "Ear";
break;
case 0x04:
location = "Finger";
break;
case 0x05:
location = "Gastro-intenstinal Tract";
break;
case 0x06:
location = "Mouth";
break;
case 0x07:
location = "Rectum";
break;
case 0x08:
location = "Toe";
break;
case 0x09:
location = "Tympanum - ear drum";
break;
default:
location = "Unknown";
break;
}
self.type.text = String(format: "Location: %@", location)
} else {
self.type.text = "Location: n/a";
}
if NORAppUtilities.isApplicationInactive() {
var message : String = ""
if (self.temperatureValueFahrenheit == true) {
message = String(format:"New temperature reading: %.2f°F", tempValue)
} else {
message = String(format:"New temperature reading: %.2f°C", tempValue)
}
NORAppUtilities.showBackgroundNotification(message: message)
}
}
})
}
//MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOff {
print("Bluetooth powered off")
} else {
print("Bluetooth powered on")
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
self.deviceName.text = peripheral.name
self.connectionButon.setTitle("DISCONNECT", for: UIControlState())
})
NotificationCenter.default.addObserver(self, selector: #selector(self.appDidEnterBackrgoundCallback), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.appDidBecomeActiveCallback), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
// Peripheral has connected. Discover required services
connectedPeripheral = peripheral;
peripheral.discoverServices([htsServiceUUID, batteryServiceUUID])
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
NORAppUtilities.showAlert(title: "Error", andMessage: "Connecting to peripheral failed. Try again")
self.connectionButon.setTitle("CONNECT", for: UIControlState())
self.connectedPeripheral = nil
self.clearUI()
})
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
self.connectionButon.setTitle("CONNECT", for: UIControlState())
if NORAppUtilities.isApplicationInactive() {
let name = peripheral.name ?? "Peripheral"
NORAppUtilities.showBackgroundNotification(message: "\(name) is disconnected.")
}
self.connectedPeripheral = nil
self.clearUI()
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
})
}
//MARK: - NORScannerDelegate
func centralManagerDidSelectPeripheral(withManager aManager: CBCentralManager, andPeripheral aPeripheral: CBPeripheral) {
// We may not use more than one Central Manager instance. Let's just take the one returned from Scanner View Controller
bluetoothManager = aManager
bluetoothManager!.delegate = self
// The sensor has been selected, connect to it
aPeripheral.delegate = self
let options = [CBConnectPeripheralOptionNotifyOnNotificationKey : NSNumber(value: true as Bool)]
bluetoothManager!.connect(aPeripheral, options: options)
}
//MARK: - NORHTSViewController implementation
func updateUnits() {
temperatureValueFahrenheit = UserDefaults.standard.bool(forKey: "fahrenheit")
if temperatureValueFahrenheit == true {
degreeControl.selectedSegmentIndex = 1
self.temperatureUnit.text = "°F"
} else {
degreeControl.selectedSegmentIndex = 0
self.temperatureUnit.text = "°C"
}
}
func appDidEnterBackrgoundCallback() {
let name = connectedPeripheral?.name ?? "peripheral"
NORAppUtilities.showBackgroundNotification(message: "You are still connected to \(name). It will collect data also in background.")
}
func appDidBecomeActiveCallback() {
UIApplication.shared.cancelAllLocalNotifications()
self.updateUnits()
}
func clearUI() {
deviceName.text = "DEFAULT HTM"
battery.tag = 0
battery.setTitle("n/a", for: UIControlState.disabled)
self.temperature.text = "-"
self.timestamp.text = ""
self.type.text = ""
}
}
| bsd-3-clause | edb2893846b4283edc920c29f5f7502b | 44.117143 | 181 | 0.591539 | 5.885576 | false | false | false | false |
ivlasov/EvoShare | EvoShareSwift/PromoList.swift | 2 | 3849 | //
// PromoList.swift
// EvoShareSwift
//
// Created by Ilya Vlasov on 12/23/14.
// Copyright (c) 2014 mtu. All rights reserved.
//
import Foundation
import UIKit
struct PromoListDataSourceInfo {
static let reuseIdentifier: String = "promolistcell"
static let rowheight: CGFloat = 265.0
}
class ListOfPromosTableViewController : UITableViewController, ConnectionManagerDelegate {
var listOfPromosJSON: [[String:AnyObject]]?
override func viewDidLoad() {
//
}
override func didReceiveMemoryWarning() {
//
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "charityDetailSegue" {
let destinationViewController = segue.destinationViewController as! ActionDetailViewController
let relatedPromo = listOfPromosJSON![self.tableView.indexPathForSelectedRow()!.row]
let promoTitle = relatedPromo["TIT"] as! String
let promoText = relatedPromo["DTL"] as! String
let imgURLString = relatedPromo["IMG"] as! String
let needToCollect = relatedPromo["SND"] as! Double
let collected = relatedPromo["SET"] as! Double
let peoples = relatedPromo["CUS"] as! Int
let countImg = relatedPromo["IMS"] as! Int
let needToCollectString = String(format: "%.0f", needToCollect)
let peoplesString = String(format: "%d", peoples)
let collectedString = String(format: "%.0f", collected)
destinationViewController.need = needToCollectString
destinationViewController.people = peoplesString
destinationViewController.gained = collectedString
destinationViewController.img = imgURLString
destinationViewController.desc = promoText
destinationViewController.imgCount = countImg
destinationViewController.actionID = self.tableView.indexPathForSelectedRow()!.row
}
}
// MARK:TableView DataSource
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: PromoCell! = tableView.dequeueReusableCellWithIdentifier(PromoListDataSourceInfo.reuseIdentifier, forIndexPath: indexPath) as! PromoCell
let relatedPromo = listOfPromosJSON![indexPath.row]
let imgURLString = relatedPromo["IMG"] as! String
let promoTitle = relatedPromo["TIT"] as! String
let promoText = relatedPromo["DTL"] as! String
let url = NSURL(string: imgURLString)
var err: NSError?
let imageData: NSData = NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMapped, error: &err)!
let relatedPromoImage = UIImage(data:imageData)
cell.promoImage.image = relatedPromoImage
cell.promoName.text = promoTitle
cell.promoDesc.text = promoText
return cell
}
// MARK:TableView Delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("did select row: \(indexPath.row)")
}
// MARK:TableView Properties
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.listOfPromosJSON!.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return PromoListDataSourceInfo.rowheight
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
}
// MARK:ConnectionManagerDelegate
extension ListOfPromosTableViewController : ConnectionManagerDelegate {
func connectionManagerDidRecieveObject(responseObject: AnyObject) {
//
}}
| unlicense | 32ab13a82bfa160460ae82d6c151e819 | 39.946809 | 154 | 0.684334 | 5.173387 | false | false | false | false |
adrfer/swift | stdlib/public/core/RangeReplaceableCollectionType.swift | 1 | 15658 | //===--- RangeReplaceableCollectionType.swift -----------------*- swift -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// A Collection protocol with replaceRange
//
//===----------------------------------------------------------------------===//
/// A *collection* that supports replacement of an arbitrary subRange
/// of elements with the elements of another collection.
public protocol RangeReplaceableCollectionType : CollectionType {
//===--- Fundamental Requirements ---------------------------------------===//
/// Create an empty instance.
init()
/// Replace the given `subRange` of elements with `newElements`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`subRange.count`) if
/// `subRange.endIndex == self.endIndex` and `newElements.isEmpty`,
/// O(`self.count` + `newElements.count`) otherwise.
mutating func replaceRange<
C : CollectionType where C.Generator.Element == Generator.Element
>(
subRange: Range<Index>, with newElements: C
)
/*
We could have these operators with default implementations, but the compiler
crashes:
<rdar://problem/16566712> Dependent type should have been substituted by Sema
or SILGen
func +<
S : SequenceType
where S.Generator.Element == Generator.Element
>(_: Self, _: S) -> Self
func +<
S : SequenceType
where S.Generator.Element == Generator.Element
>(_: S, _: Self) -> Self
func +<
S : CollectionType
where S.Generator.Element == Generator.Element
>(_: Self, _: S) -> Self
func +<
RC : RangeReplaceableCollectionType
where RC.Generator.Element == Generator.Element
>(_: Self, _: S) -> Self
*/
/// A non-binding request to ensure `n` elements of available storage.
///
/// This works as an optimization to avoid multiple reallocations of
/// linear data structures like `Array`. Conforming types may
/// reserve more than `n`, exactly `n`, less than `n` elements of
/// storage, or even ignore the request completely.
mutating func reserveCapacity(n: Index.Distance)
//===--- Derivable Requirements -----------------------------------------===//
/// Creates a collection instance that contains `elements`.
init<
S : SequenceType where S.Generator.Element == Generator.Element
>(_ elements: S)
/// Append `x` to `self`.
///
/// Applying `successor()` to the index of the new element yields
/// `self.endIndex`.
///
/// - Complexity: Amortized O(1).
mutating func append(x: Generator.Element)
/*
The 'appendContentsOf' requirement should be an operator, but the compiler crashes:
<rdar://problem/16566712> Dependent type should have been substituted by Sema
or SILGen
func +=<
S : SequenceType
where S.Generator.Element == Generator.Element
>(inout _: Self, _: S)
*/
/// Append the elements of `newElements` to `self`.
///
/// - Complexity: O(*length of result*).
mutating func appendContentsOf<
S : SequenceType
where S.Generator.Element == Generator.Element
>(newElements: S)
/// Insert `newElement` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
mutating func insert(newElement: Generator.Element, atIndex i: Index)
/// Insert `newElements` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count + newElements.count`).
mutating func insertContentsOf<
S : CollectionType where S.Generator.Element == Generator.Element
>(newElements: S, at i: Index)
/// Remove the element at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
mutating func removeAtIndex(i: Index) -> Generator.Element
/// Customization point for `removeLast()`. Implement this function if you
/// want to replace the default implementation.
///
/// - Returns: A non-nil value if the operation was performed.
@warn_unused_result
mutating func _customRemoveLast() -> Generator.Element?
/// Customization point for `removeLast(_:)`. Implement this function if you
/// want to replace the default implementation.
///
/// - Returns: True if the operation was performed.
@warn_unused_result
mutating func _customRemoveLast(n: Int) -> Bool
/// Remove the element at `startIndex` and return it.
///
/// - Complexity: O(`self.count`)
/// - Requires: `!self.isEmpty`.
mutating func removeFirst() -> Generator.Element
/// Remove the first `n` elements.
///
/// - Complexity: O(`self.count`)
/// - Requires: `n >= 0 && self.count >= n`.
mutating func removeFirst(n: Int)
/// Remove the indicated `subRange` of elements.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
mutating func removeRange(subRange: Range<Index>)
/// Remove all elements.
///
/// Invalidates all indices with respect to `self`.
///
/// - parameter keepCapacity: If `true`, is a non-binding request to
/// avoid releasing storage, which can be a useful optimization
/// when `self` is going to be grown again.
///
/// - Complexity: O(`self.count`).
mutating func removeAll(keepCapacity keepCapacity: Bool /*= false*/)
}
//===----------------------------------------------------------------------===//
// Default implementations for RangeReplaceableCollectionType
//===----------------------------------------------------------------------===//
extension RangeReplaceableCollectionType {
public init<
S : SequenceType where S.Generator.Element == Generator.Element
>(_ elements: S) {
self.init()
appendContentsOf(elements)
}
public mutating func append(newElement: Generator.Element) {
insert(newElement, atIndex: endIndex)
}
public mutating func appendContentsOf<
S : SequenceType where S.Generator.Element == Generator.Element
>(newElements: S) {
for element in newElements {
append(element)
}
}
public mutating func insert(
newElement: Generator.Element, atIndex i: Index
) {
replaceRange(i..<i, with: CollectionOfOne(newElement))
}
public mutating func insertContentsOf<
C : CollectionType where C.Generator.Element == Generator.Element
>(newElements: C, at i: Index) {
replaceRange(i..<i, with: newElements)
}
public mutating func removeAtIndex(index: Index) -> Generator.Element {
_precondition(!isEmpty, "can't remove from an empty collection")
let result: Generator.Element = self[index]
replaceRange(index...index, with: EmptyCollection())
return result
}
public mutating func removeRange(subRange: Range<Index>) {
replaceRange(subRange, with: EmptyCollection())
}
public mutating func removeFirst(n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it has")
let end = startIndex.advancedBy(numericCast(n))
removeRange(startIndex..<end)
}
public mutating func removeFirst() -> Generator.Element {
_precondition(!isEmpty,
"can't remove first element from an empty collection")
let firstElement = first!
removeFirst(1)
return firstElement
}
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
if !keepCapacity {
self = Self()
}
else {
replaceRange(indices, with: EmptyCollection())
}
}
public mutating func reserveCapacity(n: Index.Distance) {}
}
extension RangeReplaceableCollectionType where SubSequence == Self {
/// Remove the element at `startIndex` and return it.
///
/// - Complexity: O(1)
/// - Requires: `!self.isEmpty`.
public mutating func removeFirst() -> Generator.Element {
_precondition(!isEmpty, "can't remove items from an empty collection")
let element = first!
self = self[startIndex.successor()..<endIndex]
return element
}
/// Remove the first `n` elements.
///
/// - Complexity: O(1)
/// - Requires: `self.count >= n`.
public mutating func removeFirst(n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it contains")
self = self[startIndex.advancedBy(numericCast(n))..<endIndex]
}
}
extension RangeReplaceableCollectionType {
@warn_unused_result
public mutating func _customRemoveLast() -> Generator.Element? {
return nil
}
@warn_unused_result
public mutating func _customRemoveLast(n: Int) -> Bool {
return false
}
}
extension RangeReplaceableCollectionType
where
Index : BidirectionalIndexType,
SubSequence == Self {
@warn_unused_result
public mutating func _customRemoveLast() -> Generator.Element? {
let element = last!
self = self[startIndex..<endIndex.predecessor()]
return element
}
@warn_unused_result
public mutating func _customRemoveLast(n: Int) -> Bool {
self = self[startIndex..<endIndex.advancedBy(numericCast(-n))]
return true
}
}
extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
/// Remove an element from the end.
///
/// - Complexity: O(1)
/// - Requires: `!self.isEmpty`
public mutating func removeLast() -> Generator.Element {
_precondition(!isEmpty, "can't remove last element from an empty collection")
if let result = _customRemoveLast() {
return result
}
return removeAtIndex(endIndex.predecessor())
}
/// Remove the last `n` elements.
///
/// - Complexity: O(`self.count`)
/// - Requires: `n >= 0 && self.count >= n`.
public mutating func removeLast(n: Int) {
if n == 0 { return }
_precondition(n >= 0, "number of elements to remove should be non-negative")
_precondition(count >= numericCast(n),
"can't remove more items from a collection than it contains")
if _customRemoveLast(n) {
return
}
let end = endIndex
removeRange(end.advancedBy(numericCast(-n))..<end)
}
}
/// Insert `newElement` into `x` at index `i`.
///
/// Invalidates all indices with respect to `x`.
///
/// - Complexity: O(`x.count`).
@available(*, unavailable, message="call the 'insert()' method on the collection")
public func insert<
C: RangeReplaceableCollectionType
>(inout x: C, _ newElement: C.Generator.Element, atIndex i: C.Index) {
fatalError("unavailable function can't be called")
}
/// Insert `newElements` into `x` at index `i`.
///
/// Invalidates all indices with respect to `x`.
///
/// - Complexity: O(`x.count + newElements.count`).
@available(*, unavailable, message="call the 'insertContentsOf()' method on the collection")
public func splice<
C: RangeReplaceableCollectionType,
S : CollectionType where S.Generator.Element == C.Generator.Element
>(inout x: C, _ newElements: S, atIndex i: C.Index) {
fatalError("unavailable function can't be called")
}
/// Remove from `x` and return the element at index `i`.
///
/// Invalidates all indices with respect to `x`.
///
/// - Complexity: O(`x.count`).
@available(*, unavailable, message="call the 'removeAtIndex()' method on the collection")
public func removeAtIndex<
C: RangeReplaceableCollectionType
>(inout x: C, _ index: C.Index) -> C.Generator.Element {
fatalError("unavailable function can't be called")
}
/// Remove from `x` the indicated `subRange` of elements.
///
/// Invalidates all indices with respect to `x`.
///
/// - Complexity: O(`x.count`).
@available(*, unavailable, message="call the 'removeRange()' method on the collection")
public func removeRange<
C: RangeReplaceableCollectionType
>(inout x: C, _ subRange: Range<C.Index>) {
fatalError("unavailable function can't be called")
}
/// Remove all elements from `x`.
///
/// Invalidates all indices with respect to `x`.
///
/// - parameter keepCapacity: If `true`, is a non-binding request to
/// avoid releasing storage, which can be a useful optimization
/// when `x` is going to be grown again.
///
/// - Complexity: O(`x.count`).
@available(*, unavailable, message="call the 'removeAll()' method on the collection")
public func removeAll<
C: RangeReplaceableCollectionType
>(inout x: C, keepCapacity: Bool = false) {
fatalError("unavailable function can't be called")
}
/// Append elements from `newElements` to `x`.
///
/// - Complexity: O(N).
@available(*, unavailable, message="call the 'appendContentsOf()' method on the collection")
public func extend<
C: RangeReplaceableCollectionType,
S : SequenceType where S.Generator.Element == C.Generator.Element
>(inout x: C, _ newElements: S) {
fatalError("unavailable function can't be called")
}
extension RangeReplaceableCollectionType {
@available(*, unavailable, renamed="appendContentsOf")
public mutating func extend<
S : SequenceType
where S.Generator.Element == Generator.Element
>(newElements: S) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed="insertContentsOf")
public mutating func splice<
S : CollectionType where S.Generator.Element == Generator.Element
>(newElements: S, atIndex i: Index) {
fatalError("unavailable function can't be called")
}
}
/// Remove an element from the end of `x` in O(1).
///
/// - Requires: `x` is nonempty.
@available(*, unavailable, message="call the 'removeLast()' method on the collection")
public func removeLast<
C: RangeReplaceableCollectionType where C.Index : BidirectionalIndexType
>(inout x: C) -> C.Generator.Element {
fatalError("unavailable function can't be called")
}
@warn_unused_result
public func +<
C : RangeReplaceableCollectionType,
S : SequenceType
where S.Generator.Element == C.Generator.Element
>(lhs: C, rhs: S) -> C {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.appendContentsOf(rhs)
return lhs
}
@warn_unused_result
public func +<
C : RangeReplaceableCollectionType,
S : SequenceType
where S.Generator.Element == C.Generator.Element
>(lhs: S, rhs: C) -> C {
var result = C()
result.reserveCapacity(rhs.count + numericCast(lhs.underestimateCount()))
result.appendContentsOf(lhs)
result.appendContentsOf(rhs)
return result
}
@warn_unused_result
public func +<
C : RangeReplaceableCollectionType,
S : CollectionType
where S.Generator.Element == C.Generator.Element
>(lhs: C, rhs: S) -> C {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.reserveCapacity(lhs.count + numericCast(rhs.count))
lhs.appendContentsOf(rhs)
return lhs
}
@warn_unused_result
public func +<
RRC1 : RangeReplaceableCollectionType,
RRC2 : RangeReplaceableCollectionType
where RRC1.Generator.Element == RRC2.Generator.Element
>(lhs: RRC1, rhs: RRC2) -> RRC1 {
var lhs = lhs
// FIXME: what if lhs is a reference type? This will mutate it.
lhs.reserveCapacity(lhs.count + numericCast(rhs.count))
lhs.appendContentsOf(rhs)
return lhs
}
@available(*, unavailable, renamed="RangeReplaceableCollectionType")
public typealias ExtensibleCollectionType = RangeReplaceableCollectionType
| apache-2.0 | 8b5b37befdff74610c47a490d3916c35 | 30.632323 | 92 | 0.667071 | 4.397079 | false | false | false | false |
omiz/CarBooking | CarBooking/Data/Objects/VehicleDetail.swift | 1 | 1105 | //
// VehicleDetail.swift
// CarBooking
//
// Created by Omar Allaham on 10/18/17.
// Copyright © 2017 Omar Allaham. All rights reserved.
//
import Foundation
import SwiftyJSON
import TRON
class VehicleDetail: Vehicle {
let vehicleDescription: String
let image: String
required init(json: JSON) throws {
vehicleDescription = json["description"].stringValue
image = json["image"].stringValue
try super.init(json: json)
}
required init(coder decoder: NSCoder) {
vehicleDescription = decoder.decodeObject(forKey: "vehicleDescription") as? String ?? ""
image = decoder.decodeObject(forKey: "image") as? String ?? ""
super.init(coder: decoder)
}
override func encode(with coder: NSCoder) {
super.encode(with: coder)
coder.encode(vehicleDescription, forKey: "vehicleDescription")
coder.encode(image, forKey: "image")
}
static func ==(_ lhs: VehicleDetail, _ rhs: VehicleDetail) -> Bool {
return lhs.id == rhs.id
}
}
| mit | 4e952c2ddee864001e3ba55986b40e9b | 23.533333 | 96 | 0.615942 | 4.398406 | false | false | false | false |
joerocca/GitHawk | Classes/Repository/RepositoryClient.swift | 1 | 5960 | //
// RepositoryClient.swift
// Freetime
//
// Created by Sherlock, James on 30/07/2017.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Apollo
protocol RepositoryQuery {
// generated queries should share the same init
func summaryTypes(from data: GraphQLSelectionSet) -> [RepositoryIssueSummaryType]
func nextPageToken(from data: GraphQLSelectionSet) -> String?
}
extension RepoIssuePagesQuery: RepositoryQuery {
func summaryTypes(from data: GraphQLSelectionSet) -> [RepositoryIssueSummaryType] {
guard let issues = data as? Data else { return [] }
return issues.repository?.issues.nodes?.flatMap { $0 } ?? []
}
func nextPageToken(from data: GraphQLSelectionSet) -> String? {
guard let issues = data as? Data else { return nil }
guard let pageInfo = issues.repository?.issues.pageInfo, pageInfo.hasNextPage else { return nil }
return pageInfo.endCursor
}
}
extension RepoPullRequestPagesQuery: RepositoryQuery {
func summaryTypes(from data: GraphQLSelectionSet) -> [RepositoryIssueSummaryType] {
guard let prs = data as? RepoPullRequestPagesQuery.Data else { return [] }
return prs.repository?.pullRequests.nodes?.flatMap { $0 } ?? []
}
func nextPageToken(from data: GraphQLSelectionSet) -> String? {
guard let prs = data as? RepoPullRequestPagesQuery.Data else { return nil }
guard let pageInfo = prs.repository?.pullRequests.pageInfo, pageInfo.hasNextPage else { return nil }
return pageInfo.endCursor
}
}
func createSummaryModel(_ node: RepositoryIssueSummaryType, containerWidth: CGFloat) -> RepositoryIssueSummaryModel? {
guard let date = GithubAPIDateFormatter().date(from: node.repoEventFields.createdAt)
else { return nil }
let attributes = [
NSAttributedStringKey.font: Styles.Fonts.body,
NSAttributedStringKey.foregroundColor: Styles.Colors.Gray.dark.color
]
let title = NSAttributedStringSizing(
containerWidth: containerWidth,
attributedText: NSAttributedString(string: node.title, attributes: attributes),
inset: RepositorySummaryCell.titleInset
)
return RepositoryIssueSummaryModel(
id: node.id,
title: title,
number: node.number,
created: date,
author: node.repoEventFields.author?.login ?? Constants.Strings.unknown,
status: node.status,
pullRequest: node.pullRequest,
labels: node.labelableFields.issueLabelModels
)
}
func createSummaryModel(
query: RepositoryQuery,
data: GraphQLSelectionSet,
containerWidth: CGFloat
) -> (models: [RepositoryIssueSummaryModel], nextPage: String?) {
let nextPage = query.nextPageToken(from: data)
let models: [RepositoryIssueSummaryModel] = query.summaryTypes(from: data).flatMap { (node: RepositoryIssueSummaryType) in
return createSummaryModel(node, containerWidth: containerWidth)
}
return (models, nextPage)
}
final class RepositoryClient {
let githubClient: GithubClient
private let owner: String
private let name: String
init(githubClient: GithubClient, owner: String, name: String) {
self.githubClient = githubClient
self.owner = owner
self.name = name
}
struct RepositoryPayload {
let models: [RepositoryIssueSummaryModel]
let nextPage: String?
}
private func loadPage<T: GraphQLQuery>(
query: T,
containerWidth: CGFloat,
completion: @escaping (Result<RepositoryPayload>) -> Void
) where T: RepositoryQuery {
githubClient.fetch(query: query) { (result, error) in
guard error == nil, result?.errors == nil, let data = result?.data else {
ShowErrorStatusBar(graphQLErrors: result?.errors, networkError: error)
completion(.error(nil))
return
}
DispatchQueue.global().async {
// jump to a bg queue to parse models and presize text
let summary = createSummaryModel(
query: query,
data: data,
containerWidth: containerWidth
)
DispatchQueue.main.async {
completion(.success(RepositoryPayload(
models: summary.models,
nextPage: summary.nextPage
)))
}
}
}
}
func loadIssues(
nextPage: String? = nil,
containerWidth: CGFloat,
completion: @escaping (Result<RepositoryPayload>) -> Void
) {
loadPage(
query: RepoIssuePagesQuery(owner: owner, name: name, after: nextPage, page_size: 30),
containerWidth: containerWidth,
completion: completion
)
}
func loadPullRequests(
nextPage: String? = nil,
containerWidth: CGFloat,
completion: @escaping (Result<RepositoryPayload>) -> Void
) {
loadPage(
query: RepoPullRequestPagesQuery(owner: owner, name: name, after: nextPage, page_size: 30),
containerWidth: containerWidth,
completion: completion
)
}
func fetchReadme(
completion: @escaping (Result<String>) -> Void
) {
githubClient.request(GithubClient.Request(
path: "repos/\(owner)/\(name)/readme",
completion: { (response, _) in
if let json = response.value as? [String: Any],
let content = json["content"] as? String,
let data = Data(base64Encoded: content, options: [.ignoreUnknownCharacters]),
let text = String(data: data, encoding: .utf8) {
completion(.success(text))
} else {
completion(.error(response.error))
}
}))
}
}
| mit | 78b76c9810b61a8c4728f83f5eb850bd | 33.445087 | 126 | 0.624601 | 4.916667 | false | false | false | false |
xwu/swift | test/api-digester/Inputs/cake_baseline/cake.swift | 12 | 4761 | import APINotesTest
public struct S1 {
public init(_ : Int) {}
public func foo1() {}
mutating public func foo2() {}
public func foo3() {}
public func foo4() -> Void {}
public func foo5(x : Int, y: Int) {}
}
public class C1 {
public class func foo1() {}
public func foo2(_ : Int) {}
public weak var CIIns1 : C1?
public var CIIns2 : C1?
public func foo3(a : Void?) {}
public func foo4(a : Void?) {}
}
public class C3 {}
public struct Somestruct2 {
public init(_ : C1) {}
public static func foo1(_ a : C3) {}
}
public class C4: OldType {
public func foo() {}
}
@objc
public class C5 {
@objc
public func dy_foo() {}
}
public struct C6 {}
@frozen
public enum IceKind {}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public enum FutureKind {}
public protocol P1 {}
public protocol P2 {}
public extension P1 where Self: P2 {
func P1Constraint() {}
}
@frozen
public struct fixedLayoutStruct {
public var b = 2
public func foo() {}
public var a = 1
public var height: Int {
_read { yield 0 }
}
}
@usableFromInline
@frozen
struct fixedLayoutStruct2 {
public private(set) var NoLongerWithFixedBinaryOrder = 1
public var BecomeFixedBinaryOrder: Int { return 1 }
}
@frozen
public enum FrozenKind {
case Unchanged
case Fixed
case Rigid
}
public class C7 {
public func foo(_ a: Int = 1, _ b: Int = 2) {}
}
public protocol P3: P2, P1 {}
extension fixedLayoutStruct: P1 {}
public protocol AssociatedTypePro {
associatedtype T1 = Int
associatedtype T2
associatedtype T3 = C1
}
public class RemoveSetters {
public var Value = 4
public subscript(_ idx: Int) -> Int {
get { return 1 }
set(newValue) {}
}
}
public protocol RequiementChanges {
func removedFunc()
associatedtype removedType
var removedVar: Int {get}
}
/// This protocol shouldn't be complained because its requirements are all derived.
public protocol DerivedProtocolRequiementChanges: RequiementChanges {}
public class SuperClassRemoval: C3 {}
public class ClassToStruct {
public init() {}
}
open class ClassWithMissingDesignatedInits {
internal init() {}
public convenience init(x: Int) { self.init() }
}
open class ClassWithoutMissingDesignatedInits {
public init() {}
public convenience init(x: Int) { self.init() }
}
public class SubclassWithMissingDesignatedInits: ClassWithMissingDesignatedInits {
}
public class SubclassWithoutMissingDesignatedInits: ClassWithoutMissingDesignatedInits {
}
public protocol ProtocolToEnum {}
public class SuperClassChange: C7 {}
public class GenericClass<T> {}
public class SubGenericClass: GenericClass<P1> {}
@objc
public protocol ObjCProtocol {
@objc
optional func removeOptional()
@objc
func addOptional()
}
public let GlobalLetChangedToVar = 1
public var GlobalVarChangedToLet = 1
public class ClassWithOpenMember {
open class func foo() {}
open var property: Int {get { return 1}}
open func bar() {}
}
public class EscapingFunctionType {
public func removedEscaping(_ a: @escaping ()->()) {}
public func addedEscaping(_ a: ()->()) {}
}
infix operator ..*..
public func ownershipChange(_ a: inout Int, _ b: __shared Int) {}
@usableFromInline
@_fixed_layout
class _NoResilientClass {
@usableFromInline
final func NoLongerFinalFunc() {}
private func FuncPositionChange0() {}
private func FuncPositionChange1() {}
}
public class FinalFuncContainer {
public func NewFinalFunc() {}
public final func NoLongerFinalFunc() {}
}
public protocol AssociatedTypesProtocol {
associatedtype T
}
public class TChangesFromIntToString: AssociatedTypesProtocol {
public typealias T = Int
}
public protocol HasMutatingMethod {
mutating func foo()
var bar: Int { mutating get }
}
public protocol HasMutatingMethodClone: HasMutatingMethod {
mutating func foo()
var bar: Int { mutating get }
}
public extension Int {
public func IntEnhancer() {}
}
public protocol Animal {}
public class Cat: Animal { public init() {} }
public class Dog: Animal { public init() {} }
public class Zoo {
public init() {}
@inlinable
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public var current: some Animal {
return Cat()
}
@inlinable
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public func getCurrentAnimalInlinable() -> some Animal {
return Cat()
}
}
public func returnFunctionTypeOwnershipChange() -> (C1) -> () { return { _ in } }
@objc(OldObjCClass)
public class SwiftObjcClass {
@objc(OldObjCFool:OldObjCA:OldObjCB:)
public func foo(a:Int, b:Int, c: Int) {}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
open class AddingNewDesignatedInit {
public init() {}
public convenience init(foo: Int) {
self.init()
print(foo)
}
}
| apache-2.0 | 354179df185bd34891c5bb570baac501 | 19.346154 | 88 | 0.699643 | 3.579699 | false | false | false | false |
jeevatkm/FrameworkBenchmarks | frameworks/Swift/perfect/Sources/Perfect-PostgreSQL/main.swift | 1 | 5976 | import PerfectHTTP
import PerfectHTTPServer
import PerfectLib
import PerfectPostgreSQL
import Foundation
let tfbHost = "tfb-database"
let database = "hello_world"
let username = "benchmarkdbuser"
let password = "benchmarkdbpass"
let p = PGConnection()
let status = p.connectdb("postgresql://\(username):\(password)@\(tfbHost):5432/\(database)")
class LinearCongruntialGenerator {
var state = 0 //seed of 0 by default
let a, c, m, shift: Int
init() {
self.a = 214013
self.c = 2531011
self.m = Int(pow(2.0, 31.0)) //2^31 or 2147483648
self.shift = 16
}
func random() -> Int {
state = (a * state + c) % m
return state >> shift
}
}
let numGenerator = LinearCongruntialGenerator()
func fetchFromWorld(id: String?) -> [String:Any] {
var returnObj = [String: Any]()
var rand:Int = 0
if id == nil {
rand = numGenerator.random() % 10000
} else {
rand = Int(id!)!
}
let results = p.exec(statement: "select id, randomNumber from world where id = \(rand)")
returnObj["id"] = results.getFieldString(tupleIndex: 0, fieldIndex: 0)!
returnObj["randomNumber"] = results.getFieldString(tupleIndex: 0, fieldIndex: 1)!
return returnObj
}
func updateOneFromWorld() -> [String: Any] {
var returnObj = [String: Any]()
let rand = numGenerator.random() % 10000 + 1
let rand2 = numGenerator.random() % 10000 + 1
let _ = p.exec(statement: "UPDATE world SET randomNumber = \(rand) WHERE id = \(rand2)")
// let checkIfCorrect = fetchFromWorld(id: String(describing: rand2))
//The exec statement for update doesn't return the updated values. I used to checkIfCorrect variable to confirm that the updates were taking place.
returnObj["id"] = rand2
returnObj["randomNumber"] = rand
return returnObj
}
func updatesHandler(request: HTTPRequest, response: HTTPResponse) {
let queryStr = returnCorrectTuple(queryArr: request.queryParams)
var totalQueries = sanitizeQueryValue(queryString: queryStr)
var updateArr: Array = [[String: Any]]()
while 0 < totalQueries {
updateArr.append(updateOneFromWorld())
totalQueries -= 1
}
do {
response.appendBody(string: try updateArr.jsonEncodedString())
} catch {
response.appendBody(string: String(describing: updateArr))
}
setHeaders(response: response, contentType: "application/json")
response.completed()
}
func multipleDatabaseQueriesHandler(request: HTTPRequest, response: HTTPResponse) {
let queryStr = returnCorrectTuple(queryArr: request.queryParams)
var totalQueries = sanitizeQueryValue(queryString: queryStr)
var queryArr: Array = [[String: Any]]()
while 0 < totalQueries {
queryArr.append(fetchFromWorld(id: nil))
totalQueries -= 1
}
do {
response.appendBody(string: try queryArr.jsonEncodedString())
} catch {
response.appendBody(string: String(describing: queryArr))
}
setHeaders(response: response, contentType: "application/json")
response.completed()
}
func singleDatabaseQueryHandler(request: HTTPRequest, response: HTTPResponse) {
let res = fetchFromWorld(id: nil)
let errorPayload: [String: Any] = [
"error": "Could not set body!"
]
var responseString: String = ""
var errorString: String = ""
do {
errorString = try errorPayload.jsonEncodedString()
} catch {
// Nothing to do here - we already have an empty value
}
do {
responseString = try res.jsonEncodedString()
response.appendBody(string: responseString)
} catch {
response.status = HTTPResponseStatus.internalServerError
response.appendBody(string: errorString)
}
setHeaders(response: response, contentType: "application/json")
response.completed()
}
// Helpers
func setHeaders(response: HTTPResponse, contentType: String) {
response.setHeader(.contentType, value: contentType)
response.setHeader(.custom(name: "Server"), value: "Perfect")
let currDate: String = getCurrDate()
response.setHeader(.custom(name: "Date"), value: currDate)
}
func getCurrDate() -> String {
let now = getNow()
do {
let formatted = try formatDate(now, format: "%a, %d %b %Y %H:%M:%S %Z", timezone: nil, locale: nil)
return formatted
} catch {
return "error formatting date string"
}
}
func returnCorrectTuple(queryArr: [(String, String)]) -> String {
for tup in queryArr {
if String(describing: tup.0) == "queries" {
return String(describing: tup.1)
}
}
return "nil"
}
func sanitizeQueryValue(queryString: String) -> Int {
if let queryNum = Int(queryString) {
if queryNum > 0 && queryNum < 500 {
return queryNum
} else if queryNum > 500 {
return 500
} else {
return 1
}
} else {
return 1
}
}
func spoofHTML(fortunesArr: [[String: Any]]) -> String {
var htmlToRet = "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>"
for fortune in fortunesArr {
htmlToRet += "<tr><td>\(fortune["id"]!)</td><td>\(fortune["message"]!)</td></tr>"
}
htmlToRet += "</table></body></html>";
return htmlToRet
}
var routes = Routes()
routes.add(method: .get, uri: "/updates", handler: updatesHandler)
routes.add(method: .get, uri: "/queries", handler: multipleDatabaseQueriesHandler)
routes.add(method: .get, uri: "/db", handler: singleDatabaseQueryHandler)
routes.add(method: .get, uri: "/**",
handler: StaticFileHandler(documentRoot: "./webroot", allowResponseFilters: true).handleRequest)
try HTTPServer.launch(name: "localhost",
port: 8080,
routes: routes,
responseFilters: [
(PerfectHTTPServer.HTTPFilter.contentCompression(data: [:]), HTTPFilterPriority.high)])
| bsd-3-clause | 6d90f6627ef0f471bdb0f1c22d67ef69 | 25.442478 | 151 | 0.650268 | 3.997324 | false | false | false | false |
lemberg/connfa-ios | Pods/SwiftDate/Sources/SwiftDate/Date/Date+Create.swift | 1 | 7123 | //
// Date+Operations.swift
// SwiftDate
//
// Created by Daniele Margutti on 06/06/2018.
// Copyright © 2018 SwiftDate. All rights reserved.
//
import Foundation
public extension Date {
/// Return the oldest date in given list.
///
/// - Parameter list: list of dates
/// - Returns: a tuple with the index of the oldest date and its instance.
public static func oldestIn(list: [Date]) -> Date? {
guard list.count > 0 else { return nil }
guard list.count > 1 else { return list.first! }
return list.min(by: {
return $0 < $1
})
}
/// Return the oldest date in given list.
///
/// - Parameter list: list of dates
/// - Returns: a tuple with the index of the oldest date and its instance.
public static func newestIn(list: [Date]) -> Date? {
guard list.count > 0 else { return nil }
guard list.count > 1 else { return list.first! }
return list.max(by: {
return $0 < $1
})
}
/// Enumerate dates between two intervals by adding specified time components defined by a function and return an array of dates.
/// `startDate` interval will be the first item of the resulting array.
/// The last item of the array is evaluated automatically and maybe not equal to `endDate`.
///
/// - Parameters:
/// - start: starting date
/// - endDate: ending date
/// - increment: increment function. It get the last generated date and require a valida `DateComponents` instance which define the increment
/// - Returns: array of dates
public static func enumerateDates(from startDate: Date, to endDate: Date, increment: ((Date) -> (DateComponents))) -> [Date] {
var dates: [Date] = []
var currentDate = startDate
while currentDate <= endDate {
dates.append(currentDate)
currentDate = (currentDate + increment(currentDate))
}
return dates
}
/// Enumerate dates between two intervals by adding specified time components and return an array of dates.
/// `startDate` interval will be the first item of the resulting array.
/// The last item of the array is evaluated automatically and maybe not equal to `endDate`.
///
/// - Parameters:
/// - start: starting date
/// - endDate: ending date
/// - increment: components to add
/// - Returns: array of dates
public static func enumerateDates(from startDate: Date, to endDate: Date, increment: DateComponents) -> [Date] {
return Date.enumerateDates(from: startDate, to: endDate, increment: { _ in
return increment
})
}
/// Round a given date time to the passed style (off|up|down).
///
/// - Parameter style: rounding mode.
/// - Returns: rounded date
public func dateRoundedAt(at style: RoundDateMode) -> Date {
return self.inDefaultRegion().dateRoundedAt(style).date
}
/// Returns a new DateInRegion that is initialized at the start of a specified unit of time.
///
/// - Parameter unit: time unit value.
/// - Returns: instance at the beginning of the time unit; `self` if fails.
public func dateAtStartOf(_ unit: Calendar.Component) -> Date {
return self.inDefaultRegion().dateAtStartOf(unit).date
}
/// Return a new DateInRegion that is initialized at the start of the specified components
/// executed in order.
///
/// - Parameter units: sequence of transformations as time unit components
/// - Returns: new date at the beginning of the passed components, intermediate results if fails.
public func dateAtStartOf(_ units: [Calendar.Component]) -> Date {
return units.reduce(self) { (currentDate, currentUnit) -> Date in
return currentDate.dateAtStartOf(currentUnit)
}
}
/// Returns a new Moment that is initialized at the end of a specified unit of time.
///
/// - parameter unit: A TimeUnit value.
///
/// - returns: A new Moment instance.
public func dateAtEndOf(_ unit: Calendar.Component) -> Date {
return self.inDefaultRegion().dateAtEndOf(unit).date
}
/// Return a new DateInRegion that is initialized at the end of the specified components
/// executed in order.
///
/// - Parameter units: sequence of transformations as time unit components
/// - Returns: new date at the end of the passed components, intermediate results if fails.
public func dateAtEndOf(_ units: [Calendar.Component]) -> Date {
return units.reduce(self) { (currentDate, currentUnit) -> Date in
return currentDate.dateAtEndOf(currentUnit)
}
}
/// Create a new date by altering specified components of the receiver.
///
/// - Parameter components: components to alter with their new values.
/// - Returns: new altered `DateInRegion` instance
public func dateBySet(_ components: [Calendar.Component: Int]) -> Date? {
return DateInRegion(self, region: SwiftDate.defaultRegion).dateBySet(components)?.date
}
/// Create a new date by altering specified time components.
///
/// - Parameters:
/// - hour: hour to set (`nil` to leave it unaltered)
/// - min: min to set (`nil` to leave it unaltered)
/// - secs: sec to set (`nil` to leave it unaltered)
/// - ms: milliseconds to set (`nil` to leave it unaltered)
/// - options: options for calculation
/// - Returns: new altered `DateInRegion` instance
public func dateBySet(hour: Int?, min: Int?, secs: Int?, ms: Int? = nil, options: TimeCalculationOptions = TimeCalculationOptions()) -> Date? {
let srcDate = DateInRegion(self, region: SwiftDate.defaultRegion)
return srcDate.dateBySet(hour: hour, min: min, secs: secs, ms: ms, options: options)?.date
}
/// Creates a new instance by truncating the components
///
/// - Parameter components: components to truncate.
/// - Returns: new date with truncated components.
public func dateTruncated(_ components: [Calendar.Component]) -> Date? {
return DateInRegion(self, region: SwiftDate.defaultRegion).dateTruncated(at: components)?.date
}
/// Creates a new instance by truncating the components starting from given components down the granurality.
///
/// - Parameter component: The component to be truncated from.
/// - Returns: new date with truncated components.
public func dateTruncated(from component: Calendar.Component) -> Date? {
return DateInRegion(self, region: SwiftDate.defaultRegion).dateTruncated(from: component)?.date
}
/// Offset a date by n calendar components.
/// Note: This operation can be functionally chained.
///
/// - Parameters:
/// - count: value of the offset.
/// - component: component to offset.
/// - Returns: new altered date.
public func dateByAdding(_ count: Int, _ component: Calendar.Component) -> DateInRegion {
return DateInRegion(self, region: SwiftDate.defaultRegion).dateByAdding(count, component)
}
/// Return related date starting from the receiver attributes.
///
/// - Parameter type: related date to obtain.
/// - Returns: instance of the related date.
public func dateAt(_ type: DateRelatedType) -> Date {
return self.inDefaultRegion().dateAt(type).date
}
/// Create a new date at now and extract the related date using passed rule type.
///
/// - Parameter type: related date to obtain.
/// - Returns: instance of the related date.
public static func nowAt(_ type: DateRelatedType) -> Date {
return Date().dateAt(type)
}
}
| apache-2.0 | 151181490f8ff3e70836d515bbe92c1a | 37.706522 | 144 | 0.704437 | 3.829032 | false | false | false | false |
piars777/TheMovieDatabaseSwiftWrapper | Sources/Models/ListsMDB.swift | 1 | 1592 | //
// ListMDB.swift
// MDBSwiftWrapper
//
// Created by George on 2016-03-08.
// Copyright © 2016 GeorgeKye. All rights reserved.
//
import Foundation
///TODO: ListItem status
public struct ListsMDB: ArrayObject{
public var created_by: String!
public var description: String?
public var favorite_count: Int!
public var id: String!
public var items = [MovieMDB]()
public var item_count: Int!
public var iso_639_1: String!
public var name: String!
public var poster_path: String?
public init(results: JSON){
created_by = results["created_by"].string
description = results["description"].string
favorite_count = results["favorite_count"].int
id = results["id"].string
items = MovieMDB.initialize(json: results["items"])
item_count = results["items_count"].int
iso_639_1 = results["iso_639_1"].string
name = results["name"].string
poster_path = results["poster_path"].string
}
///MARK: Lists
public static func lists(api_key: String!, listId: String!, completion: (clientReturn: ClientReturn, data: ListsMDB?) -> ()) -> (){
let url = "http://api.themoviedb.org/3/list/\(listId)"
Client.Lists(url, api_key: api_key, listId: listId!){
apiReturn in
if(apiReturn.error == nil){
completion(clientReturn: apiReturn, data: ListsMDB.init(results: apiReturn.json!))
}else{
completion(clientReturn: apiReturn, data: nil)
}
}
}
}
| mit | c17923b34617f1f5568b64544d2305f1 | 30.196078 | 136 | 0.603394 | 4.058673 | false | false | false | false |
jonesgithub/MLSwiftBasic | MLSwiftBasic/Classes/Base/MBNavigationBarView.swift | 8 | 8393 | // github: https://github.com/MakeZL/MLSwiftBasic
// author: @email <[email protected]>
//
// MBNavigationBarView.swift
// MakeBolo
//
// Created by 张磊 on 15/6/22.
// Copyright (c) 2015年 MakeZL. All rights reserved.
//
import UIKit
protocol MBNavigationBarViewDelegate:NSObjectProtocol{
func goBack()
}
class MBNavigationBarView: UIView {
var titleImage,leftImage,rightImage:String!
var rightTitleBtns:NSMutableArray = NSMutableArray()
weak var delegate:MBNavigationBarViewDelegate!
var rightItemWidth:CGFloat!{
willSet{
var count = self.rightTitleBtns.count ?? self.rightImgs.count
if count > 0 {
for (var i = 0; i < count; i++){
if var button = self.rightTitleBtns[i] as? UIButton ?? self.rightImgs[i] as? UIButton {
button.frame.size.width = newValue
var x = self.frame.size.width - newValue * CGFloat(i) - newValue
button.frame = CGRectMake(x, NAV_BAR_Y, newValue, NAV_BAR_HEIGHT) ;
}
}
self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_LEFT_W - newValue * CGFloat(count)
}else {
self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_LEFT_W - NAV_ITEM_RIGHT_W
self.rightButton.frame.size.width = newValue
self.rightButton.frame.origin.x = self.frame.size.width - newValue
}
}
}
var leftItemWidth:CGFloat!
var title:String{
set {
self.titleButton.setTitle(newValue, forState: .Normal)
}
get {
if (self.titleButton.currentTitle != nil) {
return self.titleButton.currentTitle!
}else{
return ""
}
}
}
var leftStr:String{
set {
self.leftButton.setTitle(newValue, forState: .Normal)
}
get {
if (self.leftButton.currentTitle != nil) {
return self.leftButton.currentTitle!
}else{
return ""
}
}
}
var rightImgs:NSArray{
set{
var allImgs = newValue.reverseObjectEnumerator().allObjects
for (var i = 0; i < allImgs.count; i++){
var rightButton = UIButton.buttonWithType(.Custom) as! UIButton
rightButton.tag = i
rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
var x = self.frame.size.width - CGFloat(NAV_ITEM_RIGHT_W) * CGFloat(i) - NAV_ITEM_LEFT_W
rightButton.setImage(UIImage(named: allImgs[i] as! String), forState: .Normal)
rightButton.frame = CGRectMake(x, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ;
rightButton.titleLabel?.font = NAV_ITEM_FONT
rightButton.autoresizingMask = .FlexibleRightMargin | .FlexibleLeftMargin
self.addSubview(rightButton)
rightTitleBtns.addObject(rightButton)
}
if (newValue.count > 1){
if self.rightItemWidth > 0 {
self.titleButton.frame.size.width = self.frame.size.width - self.rightItemWidth * CGFloat((newValue.count)) - NAV_ITEM_LEFT_W
}else{
self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((newValue.count)) - NAV_ITEM_LEFT_W
}
}
}
get{
return ( rightTitleBtns != false && rightTitleBtns.count > 0) ? rightTitleBtns: []
}
}
var rightTitles:NSArray{
set{
for (var i = 0; i < newValue.count; i++){
var rightButton = UIButton.buttonWithType(.Custom) as! UIButton
rightButton.tag = i
rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
var x = self.frame.size.width - CGFloat(NAV_ITEM_LEFT_W) * CGFloat(i) - NAV_ITEM_RIGHT_W
rightButton.setTitle(newValue[i] as! NSString as String, forState: .Normal)
rightButton.frame = CGRectMake(x, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ;
rightButton.titleLabel?.font = NAV_ITEM_FONT
rightButton.autoresizingMask = .FlexibleRightMargin | .FlexibleLeftMargin
self.addSubview(rightButton)
self.rightTitleBtns.addObject(rightButton)
}
if (newValue.count > 1){
if self.rightItemWidth > 0 {
self.titleButton.frame.size.width = self.frame.size.width - self.rightItemWidth * CGFloat((newValue.count)) - NAV_ITEM_LEFT_W
}else{
self.titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((newValue.count)) - NAV_ITEM_LEFT_W
}
}
}
get{
return ( rightTitleBtns != false && rightTitleBtns.count > 0) ? rightTitleBtns: []
}
}
var rightStr:String{
set {
self.rightButton.setTitle(newValue, forState: .Normal)
}
get {
if (self.rightButton.currentTitle != nil) {
return self.rightButton.currentTitle!
}else{
return ""
}
}
}
lazy var titleButton:UIButton = {
var titleButton = UIButton.buttonWithType(.Custom) as! UIButton
titleButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
titleButton.frame = CGRectMake(NAV_ITEM_LEFT_W, NAV_BAR_Y, self.frame.size.width - NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT);
if (self.rightTitles.count > 1){
titleButton.frame.size.width = self.frame.size.width - NAV_ITEM_RIGHT_W * CGFloat((2 + self.rightTitles.count))
titleButton.frame.origin.x = CGFloat(self.frame.size.width - titleButton.frame.size.width) * 0.5
}
titleButton.autoresizingMask = .FlexibleWidth | .FlexibleLeftMargin
titleButton.titleLabel?.font = NAV_TITLE_FONT
self.addSubview(titleButton)
return titleButton
}()
lazy var leftButton:UIButton = {
var leftButton = UIButton.buttonWithType(.Custom) as! UIButton
leftButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
leftButton.frame = CGRectMake(0, NAV_BAR_Y, NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT);
leftButton.titleLabel?.font = NAV_ITEM_FONT
self.addSubview(leftButton)
return leftButton
}()
lazy var rightButton:UIButton = {
var rightButton = UIButton.buttonWithType(.Custom) as! UIButton
rightButton.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
rightButton.frame = CGRectMake(self.frame.size.width - NAV_ITEM_RIGHT_W, NAV_BAR_Y, NAV_ITEM_RIGHT_W, NAV_BAR_HEIGHT) ;
rightButton.titleLabel?.font = NAV_ITEM_FONT
rightButton.autoresizingMask = .FlexibleRightMargin | .FlexibleLeftMargin
self.addSubview(rightButton)
return rightButton
}()
var back:Bool{
set{
if (newValue && (count(self.leftStr) <= 0 && self.leftStr.isEmpty)) {
var backBtn = UIButton.buttonWithType(.Custom) as! UIButton
backBtn.setTitleColor(NAV_TEXT_COLOR, forState: .Normal)
backBtn.setImage(UIImage(named: BACK_NAME), forState: .Normal)
backBtn.titleLabel!.textAlignment = .Left
backBtn.frame = CGRectMake(0, NAV_BAR_Y, NAV_ITEM_LEFT_W, NAV_BAR_HEIGHT);
backBtn.addTarget(self, action:"goBack", forControlEvents: .TouchUpInside)
self.addSubview(backBtn)
}
}
get{
return self.back
}
}
func goBack(){
if self.delegate.respondsToSelector(Selector("goBack")) {
self.delegate.goBack()
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
required override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
func setup(){
}
} | mit | 40856e2b41fefa2a882fe07eecba91a6 | 36.954751 | 145 | 0.565995 | 4.475454 | false | false | false | false |
JuliaNocera/learn | AppNativeCode/swift/playgroundsTreehouse/Arrays.playground/Contents.swift | 1 | 759 | //: Playground - noun: a place where people can play
import UIKit
var todo = ["return Calls","Write Blogpost","Cook dinner"]
// var todo: [String] = ["return Calls", "Write Blogpost", "Cook dinner"] --> explicit
todo += ["Pickup Laundry", "Buy Bulbs", "Laundry"] // adds to array
print(todo[0...2]) // print the 1st, 2nd, & 3rd items in array
print(todo.count) // length of todo
// Add to array
todo.append("Edit blog post")
// Update Array -> just reassign
todo[2] = "Clean Dishes"
let item = todo.removeLast()
// --> option+click shows you doc for this function in line - shows that this returns item
let item2 = todo.removeAtIndex(1)
todo.insert("Call Mom", atIndex: 0) // atIndex is a label --> put this task at top of array
print(todo)
| mit | af05e5e2880e36254ae2385cd6cb3fb9 | 22.71875 | 92 | 0.673254 | 3.373333 | false | false | false | false |
demmys/treeswift | src/AST/Inst.swift | 1 | 5533 | public protocol Nestable {
func appendNestedTypes(name: String, _ inst: Inst)
func appendNestedValues(name: String, _ inst: Inst)
}
public class Inst : Typeable, Nestable, SourceTrackable {
public var type = TypeManager()
public let name: String
public var accessLevel: AccessLevel?
private let info: SourceInfo
public var sourceInfo: SourceInfo {
return info
}
public var memberTypes: [String:Inst] = [:]
public var memberValues: [String:Inst] = [:]
public init(
_ name: String, _ source: SourceTrackable, _ memberTypes: [Inst] = []
) {
self.name = name
self.info = source.sourceInfo
for inst in memberTypes {
appendNestedTypes(inst.name, inst)
}
}
public func appendNestedTypes(name: String, _ inst: Inst) {
self.memberTypes[name] = inst
}
public func appendNestedValues(name: String, _ inst: Inst) {
self.memberValues[name] = inst
}
}
public class TypeInst : Inst {}
public class ConstantInst : Inst {}
public class VariableInst : Inst {}
public class FunctionInst : Inst {}
public class OperatorInst : Inst {
public var implementation: FunctionInst! {
didSet {
self.type = implementation.type
}
}
public init(_ name: String, _ source: SourceTrackable) {
super.init(name, source)
}
}
public class EnumInst : Inst {
public var node: EnumDeclaration
public init(
_ name: String, _ source: SourceTrackable, node: EnumDeclaration
) {
self.node = node
super.init(name, source)
}
}
public class EnumCaseInst : Inst {
public init(_ name: String, _ source: SourceTrackable) {
super.init(name, source)
}
}
public class StructInst : Inst {
public var node: StructDeclaration
public init(
_ name: String, _ source: SourceTrackable, node: StructDeclaration
) {
self.node = node
super.init(name, source)
}
}
public class ClassInst : Inst {
public var node: ClassDeclaration
public init(
_ name: String, _ source: SourceTrackable, node: ClassDeclaration
) {
self.node = node
super.init(name, source)
}
}
public class ProtocolInst : Inst {
private let node: ProtocolDeclaration
public init(
_ name: String, _ source: SourceTrackable, node: ProtocolDeclaration
) {
self.node = node
super.init(name, source)
}
}
public enum RefIdentifier {
case Name(String)
case Index(Int)
}
public class Ref : Typeable, SourceTrackable {
public let id: RefIdentifier
public var inst: Inst!
private var onResolved: [() throws -> ()] = []
public var type = TypeManager()
private let info: SourceInfo
public var sourceInfo: SourceInfo { return info }
func resolvedCallback() throws {
for callback in onResolved {
try callback()
}
}
public init(_ id: RefIdentifier, _ source: SourceTrackable) {
self.id = id
self.info = source.sourceInfo
onResolved.append({
self.type = self.inst.type
})
}
}
public typealias NestedTypeSpecifier = (String, [Type]?, SourceTrackable)
public class TypeRef : Ref, Nestable {
let nests: [NestedTypeSpecifier]
private var memberTypes: [String:Inst] = [:]
private var memberValues: [String:Inst] = [:]
public init(
_ name: String, _ source: SourceTrackable, _ nests: [NestedTypeSpecifier]
) {
self.nests = nests
super.init(.Name(name), source)
onResolved.append(resolveNests)
}
private func resolveNests() throws {
for (name, _, source) in nests {
guard let child = inst.memberTypes[name] else {
throw ErrorReporter.instance.fatal(
.NoNestedType(parent: inst.name, child: name), source
)
}
inst = child
}
}
func extendInst() {
for (name, inst) in memberTypes {
self.inst.appendNestedTypes(name, inst)
}
for (name, inst) in memberValues {
self.inst.appendNestedValues(name, inst)
}
}
func setAsDelayedExtension() {
onResolved.append(extendInst)
}
public func appendNestedTypes(name: String, _ inst: Inst) {
self.memberTypes[name] = inst
}
public func appendNestedValues(name: String, _ inst: Inst) {
self.memberValues[name] = inst
}
}
public class ValueRef : Ref {
public init(_ name: String, _ source: SourceTrackable) {
super.init(.Name(name), source)
}
}
public class OperatorRef : Ref {
public let impl: FunctionInst?
public init(
_ name: String, _ source: SourceTrackable, _ impl: FunctionInst? = nil
) {
self.impl = impl
super.init(.Name(name), source)
onResolved.append({
if let i = self.impl {
if case let operatorInst as OperatorInst = self.inst {
operatorInst.implementation = i
}
}
})
}
}
public class EnumCaseRef : Ref {
private let className: String?
public init(_ name: String, _ source: SourceTrackable, className: String?) {
self.className = className
super.init(.Name(name), source)
}
}
public class ImplicitParameterRef : Ref {
public init(_ index: Int, _ source: SourceTrackable) {
super.init(.Index(index), source)
}
}
| bsd-2-clause | 3c9e33f923ba29f70a9c80327c94044a | 24.26484 | 81 | 0.604735 | 4.098519 | false | false | false | false |
kmalkic/LazyKit | LazyKit/Classes/Theming/Sets/LazyDecorationSet.swift | 1 | 2150 | //
// DecorationSet.swift
// LazyKit
//
// Created by Malkic Kevin on 22/04/2015.
// Copyright (c) 2015 Malkic Kevin. All rights reserved.
//
import UIKit
internal let kBorderKey = "border"
internal let kBorderWidthKey = "border-width"
internal let kBorderColorKey = "border-color"
internal let kBorderRadiusKey = "border-radius"
internal class LazyDecorationSet {
var borders: LazyBorders?
init() {
}
func fetchBorders() -> LazyBorders {
if borders == nil {
borders = LazyBorders()
}
return borders!
}
init?(content: [String]!, variables: [String: String]?) {
for property in content {
let components = property.components(separatedBy: ":")
if components.count != 2 {
print("Invalid property should be 'key: value'\n")
print(components)
print("\n")
return nil
}
let key = components[0].replacingOccurrences(of: " ", with: "")
let rawValue = components[1].trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ";", with: "")
var value = rawValue
if let variables = variables {
value = variables[rawValue] ?? rawValue
}
switch key {
case kBorderKey:
fetchBorders().setupBorder(key, value: value)
case kBorderRadiusKey:
fetchBorders().setupBorderRadius(key, value: value)
case kBorderWidthKey:
fetchBorders().setupBorderWidth(key, value: value)
case kBorderColorKey:
fetchBorders().setupBorderColor(key, value: value)
default:
break
}
}
if isPropertiesNil() {
return nil
}
}
func isPropertiesNil() -> Bool {
return borders == nil
}
}
| mit | 116026017ce29bc3de72f67407ae9be3 | 23.431818 | 117 | 0.496279 | 5.269608 | false | false | false | false |
tomomura/PasscodeField | PasscodeField/Classes/PasscodeField.swift | 1 | 2458 | //
// PasscodeField.swift
// Pods
//
// Created by TomomuraRyota on 2016/05/30.
//
//
import UIKit
@IBDesignable public class PasscodeField: UIView {
// MARK: - Properties
@IBInspectable public var length: Int = 6 {
didSet {
self.progressView.length = self.length
}
}
@IBInspectable public var progress: Int = 0 {
didSet {
self.progressView.progress = self.progress
}
}
@IBInspectable public var borderHeight: CGFloat = 2.0 {
didSet {
self.progressView.borderHeight = self.borderHeight
}
}
@IBInspectable public var fillColor: UIColor = UIColor.blackColor() {
didSet {
self.progressView.fillColor = self.fillColor
}
}
@IBInspectable public var fillSize: CGFloat = 20 {
didSet {
self.progressView.fillSize = self.fillSize
}
}
private var progressView: ProgressStackView
// MARK: - Initializers
required public init?(coder aDecoder: NSCoder) {
self.progressView = ProgressStackView(
length: self.length,
progress: self.progress,
borderHeight: self.borderHeight,
fillSize: self.fillSize,
fillColor: self.fillColor
)
super.init(coder: aDecoder)
self.setupView()
}
override public init(frame: CGRect) {
self.progressView = ProgressStackView(
length: self.length,
progress: self.progress,
borderHeight: self.borderHeight,
fillSize: self.fillSize,
fillColor: self.fillColor
)
super.init(frame: frame)
self.setupView()
}
// MARK: - LifeCycle
override public func updateConstraints() {
NSLayoutConstraint.activateConstraints([
self.progressView.topAnchor.constraintEqualToAnchor(self.topAnchor),
self.progressView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor),
self.progressView.leadingAnchor.constraintEqualToAnchor(self.leadingAnchor),
self.progressView.trailingAnchor.constraintEqualToAnchor(self.trailingAnchor),
])
super.updateConstraints()
}
// MARK: - Private Methods
private func setupView() {
self.addSubview(progressView)
}
}
| mit | 4c07d41d2335032f596d64d28ec324d5 | 24.604167 | 90 | 0.588283 | 5.229787 | false | false | false | false |
zoul/Movies | Movies/PagedMovieList.swift | 1 | 956 | import Foundation
import MovieKit
public class PagedMovieList {
private let queue = DispatchQueue(label: "PagedMovieList")
private let webService = WebService(apiKey: "XXX")
public private(set) var lastLoadedPageNumber = 0
public init() {}
public func loadOneMorePage(completion: @escaping ([Movie]?) -> Void) {
queue.async {
let nextPageNumber = self.lastLoadedPageNumber+1
print("Loading page #\(nextPageNumber)")
let response = self.webService.loadSynchronously(resource: Movie.popular(pageNumber: nextPageNumber))
switch response {
case .success(let response):
self.lastLoadedPageNumber = nextPageNumber
completion(response.results)
case .error(let msg):
print("Page #\(nextPageNumber) failed to load: \(msg)")
completion(nil)
}
}
}
}
| mit | 337505bdb49d5ef9c9d43ee31d0538c5 | 33.142857 | 113 | 0.60251 | 4.979167 | false | false | false | false |
mpangburn/RayTracer | RayTracer/View Controllers/Abstract/ExpandableCellTableViewController.swift | 1 | 3653 | //
// ExpandableCellTableViewController.swift
// RayTracer
//
// Created by Michael Pangburn on 7/14/17.
// Copyright © 2017 Michael Pangburn. All rights reserved.
//
import UIKit
class ExpandableCellTableViewController: UITableViewController {
func closeExpandableTableViewCells(excluding indexPath: IndexPath? = nil) {
for case let cell as ExpandableTableViewCell in tableView.visibleCells where tableView.indexPath(for: cell) != indexPath && cell.isExpanded {
cell.isExpanded = false
}
}
var visibleBottomMargin: CGFloat {
let superviewHeight = tableView.superview!.frame.height
if let tabBarHeight = tabBarController?.tabBar.frame.height {
return superviewHeight - tabBarHeight
} else {
return superviewHeight
}
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
tableView.beginUpdates()
guard let expandableCell = tableView.cellForRow(at: indexPath) as? ExpandableTableViewCell else {
return indexPath
}
let cellRectInTableView = tableView.rectForRow(at: indexPath)
if !expandableCell.isExpanded {
// Ensure fully expanded cell is made visible when tapped near the bottom of the screen
closeExpandableTableViewCells(excluding: indexPath)
let cellRectInScreen = tableView.convert(cellRectInTableView, to: tableView.superview)
if (cellRectInScreen.maxY * 1.5) > visibleBottomMargin {
// Give contentSize enough space to ensure scrollRectToVisible works smoothly
tableView.contentSize.height += 10 * cellRectInTableView.height
let rectAtBottomOfCell = CGRect(x: 0, y: cellRectInTableView.maxY, width: 1, height: 1)
tableView.scrollRectToVisible(rectAtBottomOfCell, animated: true)
}
}
// An attempt at fixing jerky scrolling behavior at the bottom of the table view
// else {
// let lastSection = tableView.numberOfSections - 1
// let lastRow = tableView.numberOfRows(inSection: lastSection) - 1
// let lastIndexPath = IndexPath(row: lastRow, section: lastSection)
// if tableView.indexPathsForVisibleRows!.contains(lastIndexPath) {
// let adjustedInsets = UIEdgeInsets(top: 0, left: 0, bottom: expandableCell.expandedViewHeight, right: 0)
// tableView.contentInset = adjustedInsets
// }
// }
return indexPath
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.endUpdates()
tableView.deselectRow(at: indexPath, animated: true)
guard let expandableCell = tableView.cellForRow(at: indexPath) as? ExpandableTableViewCell else { return }
let cellRectInTableView = tableView.rectForRow(at: indexPath)
if expandableCell.isExpanded {
// Ensure fully expanded cell is made visible when tapped near the bottom of the screen
let cellRectInScreen = tableView.convert(cellRectInTableView, to: tableView.superview)
if cellRectInScreen.maxY > visibleBottomMargin {
// Give contentSize enough space to ensure scrollRectToVisible works smoothly
tableView.contentSize.height += 10 * cellRectInTableView.height
let rectAtBottomOfCell = CGRect(x: 0, y: cellRectInTableView.maxY, width: 1, height: 1)
tableView.scrollRectToVisible(rectAtBottomOfCell, animated: true)
}
}
}
}
| mit | 669395cbddcae7f7177eb365d5029a57 | 45.227848 | 149 | 0.673056 | 5.254676 | false | false | false | false |
practicalswift/swift | test/SILGen/guaranteed_self.swift | 4 | 25022 |
// RUN: %target-swift-emit-silgen -module-name guaranteed_self -Xllvm -sil-full-demangle %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s
protocol Fooable {
init()
func foo(_ x: Int)
mutating func bar()
mutating func bas()
var prop1: Int { get set }
var prop2: Int { get set }
var prop3: Int { get nonmutating set }
}
protocol Barrable: class {
init()
func foo(_ x: Int)
func bar()
func bas()
var prop1: Int { get set }
var prop2: Int { get set }
var prop3: Int { get set }
}
struct S: Fooable {
var x: C? // Make the type nontrivial, so +0/+1 is observable.
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> @owned S
init() {}
// TODO: Way too many redundant r/r pairs here. Should use +0 rvalues.
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed S) -> () {
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: copy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
func foo(_ x: Int) {
self.foo(x)
}
func foooo(_ x: (Int, Bool)) {
self.foooo(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout S) -> ()
// CHECK: bb0([[SELF:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF]]
mutating func bar() {
self.bar()
}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed S) -> ()
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: copy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
func bas() {
self.bas()
}
var prop1: Int = 0
// Getter for prop1
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop1Sivg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
// Setter for prop1
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop1Sivs : $@convention(method) (Int, @inout S) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// modify for prop1
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop1SivM : $@yield_once @convention(method) (@inout S) -> @yields @inout Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
var prop2: Int {
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV5prop2Sivg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
get { return 0 }
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV5prop2Sivs : $@convention(method) (Int, @inout S) -> ()
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop2SivM : $@yield_once @convention(method) (@inout S) -> @yields @inout Int
set { }
}
var prop3: Int {
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV5prop3Sivg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
get { return 0 }
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV5prop3Sivs : $@convention(method) (Int, @guaranteed S) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop3SivM : $@yield_once @convention(method) (@guaranteed S) -> @yields @inout Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
nonmutating set { }
}
}
// Witness thunk for nonmutating 'foo'
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> () {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for mutating 'bar'
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> () {
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for 'bas', which is mutating in the protocol, but nonmutating
// in the implementation
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP3bas{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK: end_borrow [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// Witness thunk for prop1 getter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop1SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// Witness thunk for prop1 setter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop1SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop1 modify
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop1SivMTW : $@yield_once @convention(witness_method: Fooable) (@inout S) -> @yields @inout Int {
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 getter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop2SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 setter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop2SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 modify
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop2SivMTW : $@yield_once @convention(witness_method: Fooable) (@inout S) -> @yields @inout Int {
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 getter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop3SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating setter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop3SivsTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating modify
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop3SivMTW : $@yield_once @convention(witness_method: Fooable) (@in_guaranteed S) -> @yields @inout Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: } // end sil function '$s15guaranteed_self1SVAA7FooableA2aDP5prop3SivMTW'
//
// TODO: Expected output for the other cases
//
struct AO<T>: Fooable {
var x: T?
init() {}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK: apply {{.*}} [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: }
func foo(_ x: Int) {
self.foo(x)
}
mutating func bar() {
self.bar()
}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (@in_guaranteed AO<T>) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
func bas() {
self.bas()
}
var prop1: Int = 0
var prop2: Int {
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV5prop2Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int {
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
get { return 0 }
set { }
}
var prop3: Int {
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV5prop3Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
get { return 0 }
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV5prop3Sivs : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self2AOV5prop3SivM : $@yield_once @convention(method) <T> (@in_guaranteed AO<T>) -> @yields @inout Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: }
nonmutating set { }
}
}
// Witness for nonmutating 'foo'
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self2AOVyxGAA7FooableA2aEP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (Int, @in_guaranteed AO<τ_0_0>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<τ_0_0>):
// CHECK: apply {{.*}} [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness for 'bar', which is mutating in protocol but nonmutating in impl
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self2AOVyxGAA7FooableA2aEP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (@inout AO<τ_0_0>) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<τ_0_0>):
// -- NB: This copy is not necessary, since we're willing to assume an inout
// parameter is not mutably aliased.
// CHECK: apply {{.*}}([[SELF_ADDR]])
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
class C: Fooable, Barrable {
// Allocating initializer
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C
// CHECK: [[SELF1:%.*]] = alloc_ref $C
// CHECK-NOT: [[SELF1]]
// CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
// CHECK-NOT: [[SELF2]]
// CHECK: return [[SELF2]]
// Initializing constructors still have the +1 in, +1 out convention.
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned C) -> @owned C {
// CHECK: bb0([[SELF:%.*]] : @owned $C):
// CHECK: [[MARKED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]]
// CHECK: [[MARKED_SELF_RESULT:%.*]] = copy_value [[MARKED_SELF]]
// CHECK: destroy_value [[MARKED_SELF]]
// CHECK: return [[MARKED_SELF_RESULT]]
// CHECK: } // end sil function '$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc'
// @objc thunk for initializing constructor
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (@owned C) -> @owned C
// CHECK: bb0([[SELF:%.*]] : @owned $C):
// CHECK-NOT: copy_value [[SELF]]
// CHECK: [[SELF2:%.*]] = apply {{%.*}}([[SELF]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF2]]
// CHECK: return [[SELF2]]
// CHECK: } // end sil function '$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo'
@objc required init() {}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed C) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $C):
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: } // end sil function '$s15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Int, C) -> () {
// CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: apply {{.*}}({{.*}}, [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: } // end sil function '$s15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo'
@objc func foo(_ x: Int) {
self.foo(x)
}
@objc func bar() {
self.bar()
}
@objc func bas() {
self.bas()
}
// CHECK-LABEL: sil hidden [transparent] [thunk] [ossa] @$s15guaranteed_self1CC5prop1SivgTo : $@convention(objc_method) (C) -> Int
// CHECK: bb0([[SELF:%.*]] : @unowned $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: apply {{.*}}([[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-LABEL: sil hidden [transparent] [thunk] [ossa] @$s15guaranteed_self1CC5prop1SivsTo : $@convention(objc_method) (Int, C) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: apply {{.*}} [[BORROWED_SELF_COPY]]
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: }
@objc var prop1: Int = 0
@objc var prop2: Int {
get { return 0 }
set {}
}
@objc var prop3: Int {
get { return 0 }
set {}
}
}
class D: C {
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1DC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick D.Type) -> @owned D
// CHECK: [[SELF1:%.*]] = alloc_ref $D
// CHECK-NOT: [[SELF1]]
// CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
// CHECK-NOT: [[SELF1]]
// CHECK-NOT: [[SELF2]]
// CHECK: return [[SELF2]]
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1DC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned D) -> @owned D
// CHECK: bb0([[SELF:%.*]] : @owned $D):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var D }
// CHECK-NEXT: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK-NEXT: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK-NEXT: store [[SELF]] to [init] [[PB]]
// CHECK-NOT: [[PB]]
// CHECK: [[SELF1:%.*]] = load [take] [[PB]]
// CHECK-NEXT: [[SUPER1:%.*]] = upcast [[SELF1]]
// CHECK-NOT: [[PB]]
// CHECK: [[SUPER2:%.*]] = apply {{.*}}([[SUPER1]])
// CHECK-NEXT: [[SELF2:%.*]] = unchecked_ref_cast [[SUPER2]]
// CHECK-NEXT: store [[SELF2]] to [init] [[PB]]
// CHECK-NOT: [[PB]]
// CHECK-NOT: [[SELF1]]
// CHECK-NOT: [[SUPER1]]
// CHECK-NOT: [[SELF2]]
// CHECK-NOT: [[SUPER2]]
// CHECK: [[SELF_FINAL:%.*]] = load [copy] [[PB]]
// CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]]
// CHECK-NEXT: return [[SELF_FINAL]]
required init() {
super.init()
}
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] [ossa] @$s15guaranteed_self1DC3foo{{[_0-9a-zA-Z]*}}FTD : $@convention(method) (Int, @guaranteed D) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $D):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: }
dynamic override func foo(_ x: Int) {
self.foo(x)
}
}
func S_curryThunk(_ s: S) -> ((S) -> (Int) -> ()/*, Int -> ()*/) {
return (S.foo /*, s.foo*/)
}
func AO_curryThunk<T>(_ ao: AO<T>) -> ((AO<T>) -> (Int) -> ()/*, Int -> ()*/) {
return (AO.foo /*, ao.foo*/)
}
// ----------------------------------------------------------------------------
// Make sure that we properly translate in_guaranteed parameters
// correctly if we are asked to.
// ----------------------------------------------------------------------------
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s15guaranteed_self9FakeArrayVAA8SequenceA2aDP17_constrainElement{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Sequence) (@in_guaranteed FakeElement, @in_guaranteed FakeArray) -> () {
// CHECK: bb0([[ARG0_PTR:%.*]] : $*FakeElement, [[ARG1_PTR:%.*]] : $*FakeArray):
// CHECK: [[ARG0:%.*]] = load [trivial] [[ARG0_PTR]]
// CHECK: function_ref (extension in guaranteed_self):guaranteed_self.SequenceDefaults._constrainElement
// CHECK: [[FUN:%.*]] = function_ref @{{.*}}
// CHECK: apply [[FUN]]<FakeArray>([[ARG0]], [[ARG1_PTR]])
class Z {}
public struct FakeGenerator {}
public struct FakeArray {
var z = Z()
}
public struct FakeElement {}
public protocol FakeGeneratorProtocol {
associatedtype Element
}
extension FakeGenerator : FakeGeneratorProtocol {
public typealias Element = FakeElement
}
public protocol SequenceDefaults {
associatedtype Element
associatedtype Generator : FakeGeneratorProtocol
}
extension SequenceDefaults {
public func _constrainElement(_: FakeGenerator.Element) {}
}
public protocol Sequence : SequenceDefaults {
func _constrainElement(_: Element)
}
extension FakeArray : Sequence {
public typealias Element = FakeElement
public typealias Generator = FakeGenerator
func _containsElement(_: Element) {}
}
// -----------------------------------------------------------------------------
// Make sure that we do not emit extra copy_values when accessing let fields of
// guaranteed parameters.
// -----------------------------------------------------------------------------
class Kraken {
func enrage() {}
}
func destroyShip(_ k: Kraken) {}
class LetFieldClass {
let letk = Kraken()
var vark = Kraken()
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self13LetFieldClassC10letkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
// CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass):
// CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN:%.*]] = load_borrow [[KRAKEN_ADDR]]
// CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]]
// CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]])
// CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN:%.*]] = load [copy] [[KRAKEN_ADDR]]
// CHECK: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$s15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[BORROWED_KRAKEN]])
// CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]]
// CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
// CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]]
// CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN2:%.*]] = load [copy] [[KRAKEN_ADDR]]
// CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]]
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Kraken
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$s15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
// CHECK-NEXT: destroy_value [[KRAKEN_COPY]]
// CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
func letkMethod() {
letk.enrage()
let ll = letk
destroyShip(ll)
var lv = letk
destroyShip(lv)
}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self13LetFieldClassC10varkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
// CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass):
// CHECK: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]]
// CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]])
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$s15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[BORROWED_KRAKEN]])
// CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]]
// CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
// CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]]
// CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN2:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]]
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*Kraken
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$s15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
// CHECK-NEXT: destroy_value [[KRAKEN_COPY]]
// CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
func varkMethod() {
vark.enrage()
let vl = vark
destroyShip(vl)
var vv = vark
destroyShip(vv)
}
}
// -----------------------------------------------------------------------------
// Make sure that in all of the following cases find has only one copy_value in it.
// -----------------------------------------------------------------------------
class ClassIntTreeNode {
let value : Int
let left, right : ClassIntTreeNode
init() {}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self16ClassIntTreeNodeC4find{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed ClassIntTreeNode) -> @owned ClassIntTreeNode {
// CHECK-NOT: destroy_value
// CHECK: copy_value
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: return
func find(_ v : Int) -> ClassIntTreeNode {
if v == value { return self }
if v < value { return left.find(v) }
return right.find(v)
}
}
| apache-2.0 | 810423eeadead48558d31440925379cd | 44.985294 | 259 | 0.584946 | 3.35605 | false | false | false | false |
ingresse/ios-sdk | IngresseSDK/Services/TransactionService.swift | 1 | 12231 | //
// Copyright © 2017 Ingresse. All rights reserved.
//
public class TransactionService: BaseService {
/// Create Transaction
///
/// - Parameters:
/// - userId: id of logged user
/// - userToken: token of logged user
/// - eventId: id of selected event
/// - tickets: tickets selected by user
/// - onSuccess: success callback
/// - onError: error callback
public func createTransaction(request: Request.Shop.Create,
userToken: String,
onSuccess: @escaping (_ response: Response.Shop.Transaction) -> Void,
onError: @escaping ErrorHandler) {
let builder = URLBuilder(client: client)
.setPath("shop")
.addParameter(key: "usertoken", value: userToken)
guard let requestURL = try? builder.build() else {
return onError(APIError.getDefaultError())
}
let data = try? JSONEncoder().encode(request)
client.restClient.POSTData(request: requestURL,
data: data,
JSONData: true,
onSuccess: { response in
guard let newResponse = response["data"] as? [String: Any],
let paymentResponse = JSONDecoder().decodeDict(of: Response.Shop.Transaction.self, from: newResponse) else {
onError(APIError.getDefaultError())
return
}
onSuccess(paymentResponse)
}, onError: onError)
}
/// Get transaction details
///
/// - Parameters:
/// - transactionId: transaction id
/// - userToken: user Token
/// - onSuccess: success callback with Transaction
/// - onError: fail callback with APIError
@objc public func getTransactionDetails(_ transactionId: String,
userToken: String,
onSuccess: @escaping (_ transaction: TransactionData) -> Void,
onError: @escaping ErrorHandler) {
let builder = URLBuilder(client: client)
.setPath("sale/\(transactionId)")
.addParameter(key: "usertoken", value: userToken)
guard let request = try? builder.build() else {
return onError(APIError.getDefaultError())
}
client.restClient.GET(request: request,
onSuccess: { response in
let transaction = JSONDecoder().decodeDict(of: TransactionData.self, from: response)!
onSuccess(transaction)
}, onError: onError)
}
/// Update a transaction
///
/// - Parameters:
/// - transactinId: transaction id
/// - insured: ticket insurance hired or not
/// - userToken: user token
/// - onSuccess: empty success callback
/// - onError: fail callback with APIError
public func updateTransaction(_ transactionId: String,
insured: Bool,
userToken: String,
onSuccess: @escaping () -> Void,
onError: @escaping ErrorHandler) {
let builder = URLBuilder(client: client)
.setPath("shop/\(transactionId)")
.addParameter(key: "usertoken", value: userToken)
guard let request = try? builder.build() else {
return onError(APIError.getDefaultError())
}
let params = ["insured": insured]
let data = try? JSONEncoder().encode(params)
client.restClient.PUTData(request: request,
data: data,
JSONData: true,
onSuccess: { _ in
onSuccess()
}, onError: onError)
}
/// Cancel transaction
///
/// - Parameters:
/// - transactionId: transaction id
/// - onSuccess: success callback with Transaction
/// - onError: fail callback with APIError
public func cancelTransaction(_ transactionId: String,
userToken: String,
onSuccess: @escaping () -> Void,
onError: @escaping ErrorHandler) {
let builder = URLBuilder(client: client)
.setPath("shop/\(transactionId)/cancel")
.addParameter(key: "usertoken", value: userToken)
guard let request = try? builder.build() else {
return onError(APIError.getDefaultError())
}
client.restClient.POST(request: request,
onSuccess: { _ in
onSuccess()
}, onError: onError)
}
/// Get payment methods from some transaction
///
/// - Parameters:
/// - transactionId: transaction id
/// - onSuccess: success callback with payment methods
/// - onError: fail callback with APIError
public func getPaymentMethods(_ transactionId: String,
userToken: String,
onSuccess: @escaping (_ methods: Response.Shop.Methods) -> Void,
onError: @escaping ErrorHandler) {
let builder = URLBuilder(client: client)
.setPath("shop/\(transactionId)/payment-methods")
.addParameter(key: "usertoken", value: userToken)
guard let request = try? builder.build() else {
return onError(APIError.getDefaultError())
}
client.restClient.GET(request: request,
onSuccess: { response in
guard let methods = JSONDecoder().decodeDict(of: Response.Shop.Methods.self, from: response)
else {
onError(APIError.getDefaultError())
return
}
onSuccess(methods)
}, onError: onError)
}
/// Get status from user tickets
///
/// - Parameters:
/// - ticketCode: ticket code
/// - userToken: user Token
/// - onSuccess: success callback
/// - onError: fail callback
public func getCheckinStatus(_ ticketCode: String,
userToken: String,
onSuccess: @escaping (_ checkinSession: [CheckinSession]) -> Void,
onError: @escaping ErrorHandler) {
let ticket: String = ticketCode.stringWithPercentEncoding()!
let builder = URLBuilder(client: client)
.setPath("ticket/\(ticket)/status")
.addParameter(key: "usertoken", value: userToken)
guard let request = try? builder.build() else {
return onError(APIError.getDefaultError())
}
client.restClient.GET(request: request,
onSuccess: { response in
guard
let data = response["data"] as? [[String: Any]],
let checkinSession = JSONDecoder().decodeArray(of: [CheckinSession].self, from: data) else {
onError(APIError.getDefaultError())
return
}
onSuccess(checkinSession)
}, onError: onError)
}
/// Apply coupom in transaction
///
/// - Parameters:
/// - transactionId: transaction id
/// - code: coupom code
/// - onSuccess: success callback
/// - onError: fail callback
public func applyCouponToPayment(transactionId: String, code: String, userToken: String, onSuccess: @escaping () -> Void, onError: @escaping ErrorHandler) {
let builder = URLBuilder(client: client)
.setPath("shop/\(transactionId)/coupon")
.addParameter(key: "usertoken", value: userToken)
guard let requestURL = try? builder.build() else {
return onError(APIError.getDefaultError())
}
let params = ["code": code]
client.restClient.POST(request: requestURL, parameters: params, onSuccess: { (_) in
onSuccess()
}, onError: onError)
}
public func removeCouponToPayment(transactionId: String, userToken: String, onSuccess: @escaping () -> Void, onError: @escaping ErrorHandler) {
let builder = URLBuilder(client: client)
.setPath("shop/\(transactionId)/coupon")
.addParameter(key: "usertoken", value: userToken)
guard let requestURL = try? builder.build() else {
return onError(APIError.getDefaultError())
}
client.restClient.DELETE(request: requestURL, parameters: [:], onSuccess: { (_) in
onSuccess()
}, onError: onError)
}
/// Update a transaction with coupon
///
/// - Parameters:
/// - transactinId: transaction id
/// - userToken: user token
/// - onSuccess: success callback
/// - onError: fail callback with APIError
public func updateTransactionWithCoupon(_ transactionId: String, userToken: String, onSuccess: @escaping (_ transaction: TransactionData) -> Void, onError: @escaping ErrorHandler) {
let builder = URLBuilder(client: client)
.setPath("shop/\(transactionId)")
.addParameter(key: "usertoken", value: userToken)
guard let requestURL = try? builder.build() else {
return onError(APIError.getDefaultError())
}
client.restClient.GET(request: requestURL, onSuccess: { (response) in
guard let transaction = JSONDecoder().decodeDict(of: TransactionData.self, from: response) else {
onError(APIError.getDefaultError())
return
}
onSuccess(transaction)
}, onError: onError)
}
public func getUserWalletTransactions(request: Request.Transaction.UserTransaction,
onSuccess: @escaping (_ transactions: [UserWalletTransaction], _ page: Int, _ lastPage: Int) -> Void,
onError: @escaping (_ errorData: APIError) -> Void) {
let builder = URLBuilder(client: client)
.setHost(.userTransactions)
.addParameter(key: "channel", value: request.channel)
.addParameter(key: "status", value: request.status)
.addParameter(key: "pageSize", value: request.pageSize)
.addParameter(key: "page", value: request.page)
guard let requestURL = try? builder.build() else {
return onError(APIError.getDefaultError())
}
client.restClient.GET(request: requestURL,
onSuccess: { response in
guard
let data = response["data"] as? [[String: Any]],
let checkinSession = JSONDecoder().decodeArray(of: [UserWalletTransaction].self, from: data),
let paginationData = response["paginationInfo"] as? [String: Any],
let pagination = JSONDecoder().decodeDict(of: PaginationInfo.self, from: paginationData) else {
onError(APIError.getDefaultError())
return
}
onSuccess(checkinSession, pagination.currentPage, pagination.lastPage)
}, onError: onError)
}
public func refundUserTransactions(transactionId: String,
onSuccess: @escaping () -> Void,
onError: @escaping (_ errorData: APIError) -> Void) {
let builder = URLBuilder(client: client)
.setHost(.userTransactions)
.setPath("\(transactionId)/refund")
guard let request = try? builder.build() else {
return onError(APIError.getDefaultError())
}
client.restClient.POST(request: request,
parameters: [:],
customHeader: [:],
onSuccess: { _ in
onSuccess()
}, onError: onError)
}
}
| mit | 4e7aecc617e947373fdc965b97157b70 | 38.837134 | 185 | 0.542518 | 5.380554 | false | false | false | false |
devcarlos/RappiApp | RappiApp/Classes/Views/Cells/CollectionAppCell.swift | 1 | 1317 | //
// CollectionAppCell.swift
// RappiApp
//
// Created by Carlos Alcala on 7/3/16.
// Copyright © 2016 Carlos Alcala. All rights reserved.
//
import UIKit
import AlamofireImage
class CollectionAppCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configure(app: App) {
//placeholder image
let placeholderImage = UIImage(named: "placeholder")!
self.imageView.image = placeholderImage
//download image URL async if internet is available
if InternetHandler.shared.isReachable() {
let URL = NSURL(string: app.imageURL)!
//change radius
let filter = AspectScaledToFillSizeWithRoundedCornersFilter(
size: imageView.frame.size,
radius: 10.0
)
self.imageView.af_setImageWithURL(
URL,
placeholderImage: placeholderImage,
filter: filter
)
}
//app name
self.nameLabel.text = app.name
self.layer.cornerRadius = 10
}
}
| mit | 152b5d77d4758099aca152347d1161c4 | 23.37037 | 72 | 0.56307 | 5.438017 | false | false | false | false |
ymedialabs/Swift-Notes | Swift-Notes.playground/Pages/02. Variables and constants .xcplaygroundpage/Contents.swift | 3 | 1701 | //: # Swift Foundation
//: ----
//: ## Variables and Constants
//: Declare variables with `var` keyword and constants with `let`
let numberOfRooms = 3
var numberOfDogs = 1
//numberOfRooms += 1 // ❌ ERROR!
numberOfDogs += 1
//: ## 😋
//: Declaring it as constants allows the compiler to perform some optimizations. So always start with `let`. If you need to change it's value, declare it as a `var`.
//: #### Inferred Typing & Explicit Typing
let someVariable = 10
//: The compiler knows 10 is an `Int`, so it set the type of `someVariable` to an Int for you automatically.
let boringWelcomeText = "Hello World!" //This is of String Type
//: Type Annotation - The type can also be set explicitly by
let coolText: String = "Astala Vista, Baby!"
//: ## 😋
//: It is good practice to let the compiler infer types wherever possible.
//: #### Naming variables and constants
//Swift is fully unicode compliant.
let direWolf = "🐺"
let 🐷 = "Pig"
let π = 3.14159
//: 🚫 - Constant and variable names cannot contain whitespace characters, mathematical symbols, arrows, private-use (or invalid) Unicode code points, or line- and box-drawing characters.
//: #### Printing contants and variables
print(boringWelcomeText)
print(coolText)
print("The value of Pi is \(π)")
//: #### Comments
//This is a single line comment
/* This is a multi-line comment.
Insert long code description 😐 */
//: #### Semicolons
let dragon = "🐲" //No semicolons required
//: Semicolons are required, however, if you want to write multiple separate statements on a single line
let babyDragon = "🐣"; print("This is how my baby dragon looks like - \(babyDragon)")
//: ---
//: [Next](@next)
| mit | 74f3e45bad079fa5fdf5ea222891bf30 | 25.555556 | 186 | 0.694561 | 3.785068 | false | false | false | false |
williambao/JAPhotoView | JAPhotoView/JAPhotoList.swift | 1 | 9820 | //
// JAPhotoList.swift
// tablexx
//
// Created by William on 30/12/2016.
// Copyright © 2016 William. All rights reserved.
//
import UIKit
open class JAPhotoList: UIView {
open dynamic var cornerRadius: CGFloat = 0 {
didSet {
for item in photoViews {
item.cornerRadius = cornerRadius
}
rearrangeViews()
}
}
open dynamic var borderWidth: CGFloat = 0 {
didSet {
for item in photoViews {
item.borderWidth = borderWidth
}
rearrangeViews()
}
}
open dynamic var borderColor: UIColor? {
didSet {
for item in photoViews {
item.borderColor = borderColor
}
rearrangeViews()
}
}
open dynamic var textColor: UIColor? {
didSet {
for item in photoViews {
item.textColor = textColor
}
rearrangeViews()
}
}
open dynamic var textFont: UIFont = UIFont.systemFont(ofSize: 12) {
didSet {
for item in photoViews {
item.textFont = textFont
}
rearrangeViews()
}
}
open dynamic var marginX: CGFloat = 5 {
didSet {
rearrangeViews()
}
}
open dynamic var marginY: CGFloat = 5 {
didSet {
rearrangeViews()
}
}
open dynamic var photoWidth: CGFloat = 80 {
didSet {
rearrangeViews()
}
}
open dynamic var photoHeight: CGFloat = 80 {
didSet {
rearrangeViews()
}
}
// 0: not limit
open dynamic var maxPhotoCount = 0 {
didSet {
rearrangeViews()
}
}
@objc public enum Alignment: Int {
case left
case center
case right
}
@IBInspectable open var alignment: Alignment = .left {
didSet {
rearrangeViews()
}
}
// show all photos in single line with scrolls
open dynamic var isSingleLine: Bool = false {
didSet {
rearrangeViews()
}
}
open dynamic var isShowText: Bool = false {
didSet {
rearrangeViews()
}
}
// show all photos in single line with scrolls
open dynamic var isEditable: Bool = false {
didSet {
rearrangeViews()
}
}
open dynamic var addButtonImage: UIImage = UIImage(named: "cE5DqwlD7K2tC1viSoCitgIwdeSnecOw.png")! {
didSet {
rearrangeViews()
}
}
open private(set) var photoViews: [JAPhotoItem] = []
var photoPressed: ((_ index: Int, _ item: JAPhotoItem) -> Void)?
var addButtonPressed: (() -> Void)?
var removeButtonPressed: ((_ index: Int, _ item: JAPhotoItem) -> Void)?
private var containerView = UIScrollView()
private(set) var rowViews: [UIScrollView] = []
private(set) var photoViewHeight: CGFloat = 0
private(set) var rows = 0 {
didSet {
invalidateIntrinsicContentSize()
}
}
// MARK: - Layout
open override func layoutSubviews() {
super.layoutSubviews()
rearrangeViews()
}
private func rearrangeViews() {
for view in photoViews {
view.removeFromSuperview()
}
for view in rowViews {
for subView in view.subviews {
subView.removeFromSuperview()
}
view.removeFromSuperview()
}
rowViews.removeAll(keepingCapacity: true)
var currentRow = 0
var currentRowView: UIScrollView!
var currentRowPhotoCount = 0
var currentRowWidth: CGFloat = 0
//
var addtional: [JAPhotoItem] = []
if isEditable && (maxPhotoCount == 0 || photoViews.count < maxPhotoCount) && addtional.isEmpty {
let addButton = createNewPhotoView(photo: addButtonImage, title: "")
addButton.itemPressed = { _ in
if let callback = self.addButtonPressed {
callback()
}
}
addtional.append(addButton)
}
// callback event
for (index, photoView) in photoViews.enumerated() {
photoView.itemPressed = { item in
self.itemPressed(at: index, sender: photoView)
}
}
for (_, photoView) in (photoViews + addtional).enumerated() {
photoView.frame.size = photoView.intrinsicContentSize
photoViewHeight = photoView.frame.height
//print("\(index)-\(currentRow)-\(currentRowWidth)-\(photoView.frame.width)-\(frame.width)")
if currentRowPhotoCount == 0 || (!isSingleLine && currentRowWidth + photoView.frame.width > frame.width) {
currentRow += 1
currentRowWidth = 0
currentRowPhotoCount = 0
currentRowView = UIScrollView()
//currentRowView.backgroundColor = UIColor.lightGray
currentRowView.isScrollEnabled = isSingleLine
currentRowView.frame.origin.y = CGFloat(currentRow - 1) * (photoViewHeight + marginY)
currentRowView.frame.size = CGSize(width: frame.size.width, height: photoViewHeight)
rowViews.append(currentRowView)
addSubview(currentRowView)
}
photoView.frame.origin = CGPoint(x: currentRowWidth, y: 0)
currentRowView.addSubview(photoView)
currentRowPhotoCount += 1
currentRowWidth += photoView.frame.width + marginX
switch alignment {
case .left:
currentRowView.frame.origin.x = 0
case .center:
currentRowView.frame.origin.x = (frame.width - (currentRowWidth - marginX)) / 2
case .right:
currentRowView.frame.origin.x = frame.width - (currentRowWidth - marginX)
}
currentRowView.frame.size.height = max(photoViewHeight, currentRowView.frame.height)
currentRowView.contentSize = CGSize(width: currentRowWidth, height: currentRowView.frame.size.height)
}
rows = currentRow
invalidateIntrinsicContentSize()
// layoutIfNeeded()
}
override open var intrinsicContentSize: CGSize {
var height = CGFloat(rows) * (photoViewHeight + marginY)
if rows > 0 {
height -= marginY
}
//print("rows: \(rows), height: \(height)")
return CGSize(width: frame.width, height: height)
}
private func createNewPhotoView(photo: UIImage, title: String) -> JAPhotoItem {
let item = JAPhotoItem(photo: photo, title: title, width: photoWidth, height: photoHeight)
item.textFont = textFont
item.textColor = textColor
item.borderWidth = borderWidth
item.borderColor = borderColor
item.isShowText = isShowText
item.isEditable = isEditable
return item
}
@discardableResult
open func addPhotos(photos: [UIImage]) -> [JAPhotoItem] {
var list: [JAPhotoItem] = []
for item in photos {
list.append(createNewPhotoView(photo: item, title: ""))
}
return addPhotoItems(list)
}
open func addPhotoItems(_ items: [JAPhotoItem]) -> [JAPhotoItem] {
for item in items {
photoViews.append(item)
}
rearrangeViews()
return items
}
@discardableResult
open func addPhoto(photo: UIImage) -> JAPhotoItem {
return addPhoto(photo: photo, title: "")
}
@discardableResult
open func addPhoto(photo: UIImage, title: String) -> JAPhotoItem {
return addPhotoItem(createNewPhotoView(photo: photo, title: title))
}
@discardableResult
open func addPhotoItem(_ item: JAPhotoItem) -> JAPhotoItem {
photoViews.append(item)
rearrangeViews()
return item
}
open func insertPhoto(_ photo: UIImage, at index: Int) -> JAPhotoItem {
return insertPhotoItem(createNewPhotoView(photo: photo, title: ""), at: index)
}
open func insertPhoto(_ photo: UIImage, title: String, at index: Int) -> JAPhotoItem {
return insertPhotoItem(createNewPhotoView(photo: photo, title: title), at: index)
}
@discardableResult
open func insertPhotoItem(_ item: JAPhotoItem, at index: Int) -> JAPhotoItem {
photoViews.insert(item, at: index)
rearrangeViews()
return item
}
open func remove(at index: Int) {
if photoViews.count <= index {
return
}
remove(item: photoViews[index])
}
open func remove(item: JAPhotoItem) {
item.removeFromSuperview()
if let index = photoViews.index(of: item) {
photoViews.remove(at: index)
}
rearrangeViews()
}
open func removeAll() {
for view in photoViews {
view.removeFromSuperview()
}
for rowView in rowViews {
for view in rowView.subviews {
view.removeFromSuperview()
}
rowView.removeFromSuperview()
}
photoViews = []
rowViews = []
rearrangeViews()
}
fileprivate func itemPressed(at index: Int, sender: JAPhotoItem!) {
if let callback = photoPressed {
callback(index, sender)
}
}
}
| mit | bf3bff1335531137f42071635c4c719f | 27.710526 | 118 | 0.548427 | 5.025077 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/Nodes/Effects/Filters/Moog Ladder/AKMoogLadder.swift | 1 | 5285 | //
// AKMoogLadder.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Moog Ladder is an new digital implementation of the Moog ladder filter based
/// on the work of Antti Huovilainen, described in the paper "Non-Linear Digital
/// Implementation of the Moog Ladder Filter" (Proceedings of DaFX04, Univ of
/// Napoli). This implementation is probably a more accurate digital
/// representation of the original analogue filter.
///
/// - parameter input: Input node to process
/// - parameter cutoffFrequency: Filter cutoff frequency.
/// - parameter resonance: Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing, analogue synths generally allow resonances to be above 1.
///
public class AKMoogLadder: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKMoogLadderAudioUnit?
internal var token: AUParameterObserverToken?
private var cutoffFrequencyParameter: AUParameter?
private var resonanceParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet(newValue) {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Filter cutoff frequency.
public var cutoffFrequency: Double = 1000 {
willSet(newValue) {
if cutoffFrequency != newValue {
if internalAU!.isSetUp() {
cutoffFrequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.cutoffFrequency = Float(newValue)
}
}
}
}
/// Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing, analogue synths generally allow resonances to be above 1.
public var resonance: Double = 0.5 {
willSet(newValue) {
if resonance != newValue {
if internalAU!.isSetUp() {
resonanceParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.resonance = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - parameter input: Input node to process
/// - parameter cutoffFrequency: Filter cutoff frequency.
/// - parameter resonance: Resonance, generally < 1, but not limited to it. Higher than 1 resonance values might cause aliasing, analogue synths generally allow resonances to be above 1.
///
public init(
_ input: AKNode,
cutoffFrequency: Double = 1000,
resonance: Double = 0.5) {
self.cutoffFrequency = cutoffFrequency
self.resonance = resonance
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x6d676c64 /*'mgld'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKMoogLadderAudioUnit.self,
asComponentDescription: description,
name: "Local AKMoogLadder",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKMoogLadderAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
cutoffFrequencyParameter = tree.valueForKey("cutoffFrequency") as? AUParameter
resonanceParameter = tree.valueForKey("resonance") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.cutoffFrequencyParameter!.address {
self.cutoffFrequency = Double(value)
} else if address == self.resonanceParameter!.address {
self.resonance = Double(value)
}
}
}
internalAU?.cutoffFrequency = Float(cutoffFrequency)
internalAU?.resonance = Float(resonance)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| apache-2.0 | 77613f209229f8e67b382fe013814e39 | 35.448276 | 190 | 0.633491 | 5.431655 | false | false | false | false |
jsslai/Action | Carthage/Checkouts/RxSwift/RxExample/RxExample/Operators.swift | 3 | 3387 | //
// Operators.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
import UIKit
// Two way binding operator between control property and variable, that's all it takes {
infix operator <-> : DefaultPrecedence
func nonMarkedText(_ textInput: UITextInput) -> String? {
let start = textInput.beginningOfDocument
let end = textInput.endOfDocument
guard let rangeAll = textInput.textRange(from: start, to: end),
let text = textInput.text(in: rangeAll) else {
return nil
}
guard let markedTextRange = textInput.markedTextRange else {
return text
}
guard let startRange = textInput.textRange(from: start, to: markedTextRange.start),
let endRange = textInput.textRange(from: markedTextRange.end, to: end) else {
return text
}
return (textInput.text(in: startRange) ?? "") + (textInput.text(in: endRange) ?? "")
}
func <-> <Base: UITextInput>(textInput: TextInput<Base>, variable: Variable<String>) -> Disposable {
let bindToUIDisposable = variable.asObservable()
.bindTo(textInput.text)
let bindToVariable = textInput.text
.subscribe(onNext: { [weak base = textInput.base] n in
guard let base = base else {
return
}
let nonMarkedTextValue = nonMarkedText(base)
/**
In some cases `textInput.textRangeFromPosition(start, toPosition: end)` will return nil even though the underlying
value is not nil. This appears to be an Apple bug. If it's not, and we are doing something wrong, please let us know.
The can be reproed easily if replace bottom code with
if nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue ?? ""
}
and you hit "Done" button on keyboard.
*/
if let nonMarkedTextValue = nonMarkedTextValue, nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue
}
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
if T.self == String.self {
#if DEBUG
fatalError("It is ok to delete this message, but this is here to warn that you are maybe trying to bind to some `rx_text` property directly to variable.\n" +
"That will usually work ok, but for some languages that use IME, that simplistic method could cause unexpected issues because it will return intermediate results while text is being inputed.\n" +
"REMEDY: Just use `textField <-> variable` instead of `textField.rx_text <-> variable`.\n" +
"Find out more here: https://github.com/ReactiveX/RxSwift/issues/649\n"
)
#endif
}
let bindToUIDisposable = variable.asObservable()
.bindTo(property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
// }
| mit | 73f2a1274d6e09f4eaf519c69afdff50 | 33.55102 | 207 | 0.643828 | 4.581867 | false | false | false | false |
knutigro/COSlideMenu | COSlideMenu/COSlideMenuController.swift | 1 | 16883 | //
// COSlideMenuController.swift
// COSlideMenuDemo
//
// Created by Knut Inge Grosland on 2015-09-20.
// Copyright © 2015 Cocmoc. All rights reserved.
//
import UIKit
@objc public protocol COSlideMenuDelegate {
optional func willOpenMenu()
optional func didOpenMenu()
optional func willCloseMenu()
optional func didCloseMenu()
}
public enum MenuAnimation: String {
case Alpha3D = "Alpha3D"
case Slide = "Slide"
static let all = [MenuAnimation.Alpha3D, MenuAnimation.Slide]
}
public class COSlideMenuController: UIViewController, UIGestureRecognizerDelegate {
// MARK: Public
public weak var delegate: COSlideMenuDelegate?
public var menuAnimation = MenuAnimation.Slide {
didSet {
resetMenu()
}
}
public var menuViewController: UIViewController? {
willSet {
if let menuViewController = self.menuViewController {
menuViewController.willMoveToParentViewController(nil)
menuViewController.removeFromParentViewController()
menuViewController.view.removeFromSuperview()
}
}
didSet {
if let menuViewController = self.menuViewController {
menuContainer.view.frame = self.view.bounds;
menuContainer.addChildViewController(menuViewController)
menuContainer.view.addSubview(menuViewController.view)
menuContainer.didMoveToParentViewController(menuViewController)
}
}
}
public var mainViewController: UIViewController? {
willSet {
if mainContainer == newValue {
if (CGRectGetMinX(mainContainer.view.frame) == distanceOpenMenu) {
closeMenu()
}
}
}
didSet {
if let mainViewController = self.mainViewController {
mainContainer.setViewControllers([mainViewController], animated: false)
mainViewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "menu-ico"), style: .Plain, target: self, action: Selector("didTapLeftBarButton:"))
}
if (CGRectGetMinX(mainContainer.view.frame) == distanceOpenMenu) {
closeMenu()
}
}
}
public var backgroundImage: UIImage? {
get { return bgImageContainer.image }
set { bgImageContainer.image = newValue }
}
public var backgroundImageContentMode = UIViewContentMode.ScaleAspectFill {
didSet {
bgImageContainer.contentMode = backgroundImageContentMode
}
}
// MARK: Private
private var mainContainer: UINavigationController!
private var menuContainer: UIViewController!
private var tapGestureRecognizer: UITapGestureRecognizer?
private var bgImageContainer: UIImageView!
private var panGestureRecognizer: UIPanGestureRecognizer?
private var draggingPoint: CGPoint?
private var distanceOpenMenu: CGFloat = 210.0
private let kDefaultAngle3DMenu = 35.0
// MARK: Setup
private func setup() {
view.backgroundColor = UIColor.blackColor()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didRotate:"), name: UIDeviceOrientationDidChangeNotification, object: nil)
bgImageContainer = UIImageView(frame: view.bounds)
bgImageContainer.contentMode = backgroundImageContentMode
bgImageContainer.layer.zPosition = -2000
view.addSubview(bgImageContainer)
menuContainer = UIViewController()
menuContainer.view.layer.anchorPoint = CGPointMake(1.0, 0.5)
menuContainer.view.frame = view.bounds
menuContainer.view.backgroundColor = UIColor.clearColor()
addChildViewController(menuContainer)
view.addSubview(menuContainer.view)
menuContainer.didMoveToParentViewController(self)
mainContainer = UINavigationController(rootViewController: UIViewController())
mainContainer.view.frame = self.view.bounds
mainContainer.view.backgroundColor = UIColor.clearColor()
addChildViewController(mainContainer)
view.addSubview(mainContainer.view)
mainContainer.didMoveToParentViewController(self)
enablePan = true
}
// MARK: View Lifecycle
override public func viewDidLoad() {
super.viewDidLoad()
setup()
}
// MARK: Rotation
func didRotate(notification: NSNotification) {
let fMain = mainContainer.view.frame
if CGRectGetMinX(fMain) == 0 {
let layer = menuContainer.view.layer
layer.transform = CATransform3DIdentity
}
}
}
// MARK: Actions
extension COSlideMenuController {
@IBAction func didTapLeftBarButton(sender: AnyObject?) {
toggleMenu()
}
}
// MARK: Menu Actions
extension COSlideMenuController {
public func toggleMenu() {
let fMain = mainContainer.view.frame
if CGRectGetMinX(fMain) == distanceOpenMenu {
closeMenu()
} else {
openMenu()
}
}
public func openMenu() {
delegate?.willOpenMenu?()
addTapGestures()
var toFrame = mainContainer.view.frame
toFrame.origin.x = distanceOpenMenu
animateView(mainContainer.view, toFrame: toFrame, duration: 0.2, delay: 0) { (finished: Bool) -> Void in
delegate?.didOpenMenu?()
}
setMenuVisible(false, animated: false)
setMenuVisible(true, animated: true)
}
public func closeMenu() {
let delayInSeconds = 0.1
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) { () -> Void in
delegate?.willCloseMenu?()
}
var toFrame = mainContainer.view.frame
toFrame.origin.x = 0
animateView(mainContainer.view, toFrame: toFrame, duration: 0.2, delay: 0.2) { [weak self] (finished: Bool) -> Void in
self?.removeTapGestures()
self?.delegate?.didCloseMenu?()
}
setMenuVisible(false, animated: true)
}
}
// MARK: Tap Gestures Recognizer
extension COSlideMenuController {
private func addTapGestures() {
if tapGestureRecognizer == nil {
self.mainViewController?.view.userInteractionEnabled = false
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapMainAction:"))
mainContainer.view.addGestureRecognizer(tapGestureRecognizer!)
}
}
private func removeTapGestures() {
if let tapGestureRecognizer = self.tapGestureRecognizer {
mainContainer.view.removeGestureRecognizer(tapGestureRecognizer)
}
mainViewController?.view.userInteractionEnabled = true
tapGestureRecognizer = nil
}
func tapMainAction(sender: AnyObject?) {
closeMenu()
}
}
// MARK: Pan Gesture Recognizer
extension COSlideMenuController {
private var shouldOpen: Bool {
get {
return (mainContainer.view.frame.origin.x >= distanceOpenMenu / 2)
}
}
public var enablePan: Bool {
set {
if (enablePan == true) {
addPanGestures()
} else{
removePanGestures()
}
}
get {
return panGestureRecognizer == nil
}
}
private func addPanGestures() {
if panGestureRecognizer == nil {
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panDetected:"))
panGestureRecognizer?.delegate = self;
self.mainContainer.view.addGestureRecognizer(panGestureRecognizer!)
}
}
private func removePanGestures() {
if let panGestureRecognizer = self.panGestureRecognizer {
mainContainer.view.removeGestureRecognizer(panGestureRecognizer)
}
self.panGestureRecognizer = nil
}
func panDetected(panRecognizer: UIPanGestureRecognizer) {
let translation = panRecognizer.translationInView(panRecognizer.view)
let velocity = panRecognizer.velocityInView(panRecognizer.view)
if panGestureRecognizer?.state == .Began {
self.draggingPoint = translation
} else if panGestureRecognizer?.state == .Changed {
var offset = fabs(self.draggingPoint!.x - translation.x)
if offset == 0 { return }
self.draggingPoint = translation
if velocity.x <= 0 {
offset = -offset
}
var fMain = mainContainer.view.frame
fMain.origin.x += offset
let isOutsideMenuBounds = (fMain.origin.x <= 0) || (fMain.origin.x >= distanceOpenMenu)
if (isOutsideMenuBounds) { return }
mainContainer.view.frame = fMain
setPanMenuAction(panGestureRecognizer!.state, offset: offset)
} else if (panGestureRecognizer?.state == .Ended) || (panGestureRecognizer?.state == .Cancelled) {
var fMain = mainContainer.view.frame
let newSeg: CGFloat!
if (shouldOpen) {
addTapGestures()
newSeg = (distanceOpenMenu - fMain.origin.x) / distanceOpenMenu
fMain.origin.x = distanceOpenMenu
} else {
removeTapGestures()
newSeg = fMain.origin.x / distanceOpenMenu
fMain.origin.x = 0
}
animateView(mainContainer.view, toFrame: fMain, duration: Double(newSeg), delay: 0.0, completion: nil)
setPanMenuAction(panGestureRecognizer!.state, offset: 0)
}
}
}
// MARK: Main Animations
extension COSlideMenuController {
private func animateView(view: UIView, toFrame: CGRect, duration: NSTimeInterval, delay: NSTimeInterval, completion: ((Bool) -> Void)?) {
UIView.animateWithDuration(duration, delay: delay, options: .CurveLinear, animations: { () -> Void in
view.frame = toFrame
}) { (finished: Bool) -> Void in
completion?(finished)
}
}
}
// MARK: Menu Animations
extension COSlideMenuController {
func resetMenu() {
set3DMenuVisible(true, animated: false)
setSlideMenuVisible(true, animated: false)
}
func setMenuVisible(visible: Bool, animated: Bool) {
switch menuAnimation {
case .Alpha3D:
set3DMenuVisible(visible, animated: animated)
case .Slide:
setSlideMenuVisible(visible, animated: animated)
}
}
func setPanMenuAction(panState: UIGestureRecognizerState, offset: CGFloat) {
switch menuAnimation {
case .Alpha3D:
setPan3DMenuAction(panState, offset: offset)
case .Slide:
setPanSlideMenuAction(panState, offset: offset)
}
}
}
// MARK: 3D-Menu Animations
extension COSlideMenuController {
private func setPan3DMenuAction(panState: UIGestureRecognizerState, offset: CGFloat) {
if panState == .Changed {
var fMain = mainContainer.view.frame
fMain.origin.x += offset
let newAngle = ((Double(distanceOpenMenu - fMain.origin.x) * kDefaultAngle3DMenu) / Double(distanceOpenMenu)) * -1
let newAlpha = ((0.7 * (fMain.origin.x)) / distanceOpenMenu) + 0.3;
rotate3DView(menuContainer.view, toAngle: newAngle)
menuContainer.view.alpha = newAlpha
} else if (panState == .Ended) || (panState == .Cancelled) {
let fMain = mainContainer.view.frame
let new3dSeg: CGFloat!
let newAngle: Double!
let newAlpha: CGFloat!
if (self.shouldOpen) {
new3dSeg = ((distanceOpenMenu - fMain.origin.x) * 0.3) / distanceOpenMenu
newAngle = 0.0
newAlpha = 1.0
} else {
new3dSeg = ((fMain.origin.x) * 0.3 ) / distanceOpenMenu
newAngle = -kDefaultAngle3DMenu
newAlpha = 0.3
}
animateView3D(menuContainer.view, toAngle: newAngle, toAlpha: newAlpha, duration: Double(new3dSeg), delay: 0.1, completion:nil)
}
}
private func set3DMenuVisible(visible: Bool, animated: Bool) {
if visible == true {
if animated == true {
animateView3D(menuContainer.view, toAngle: 0, toAlpha: 1.0, duration: 0.3, delay: 0.1, completion:nil)
} else {
menuContainer.view.layer.transform = CATransform3DIdentity
menuContainer.view.alpha = 1.0
}
} else {
if animated == true {
animateView3D(menuContainer.view, toAngle: -kDefaultAngle3DMenu, toAlpha: 0.3, duration: 0.3, delay: 0.1, completion:nil)
} else {
rotate3DView(menuContainer.view, toAngle: -kDefaultAngle3DMenu)
menuContainer.view.alpha = 0.3
}
}
}
private func animateView3D(view: UIView, toAngle: Double, toAlpha: CGFloat, duration: NSTimeInterval, delay: NSTimeInterval, completion: ((Bool) -> Void)?) {
UIView.animateWithDuration(duration, delay: delay, options: .CurveLinear, animations: { [weak self] () -> Void in
if toAngle == 0 {
view.layer.transform = CATransform3DIdentity
} else {
self?.rotate3DView(view, toAngle: toAngle)
}
view.alpha = toAlpha
}) { (finished: Bool) -> Void in
completion?(finished)
}
}
private func rotate3DView(view: UIView, toAngle: Double) {
let layer = view.layer
layer.zPosition = -1000
var t = CATransform3DIdentity
t.m34 = 1.0 / -500
t = CATransform3DRotate(t, CGFloat(toAngle * M_PI / 180.0), 0, 1, 0)
layer.transform = t
}
}
// MARK: Slide Animations
extension COSlideMenuController {
private func setPanSlideMenuAction(panState: UIGestureRecognizerState, offset: CGFloat) {
let slidePosition = mainContainer.view.frame.origin.x + offset
let offset: CGFloat = -((distanceOpenMenu - slidePosition) * 0.2)
print("offset \(offset)")
if panState == .Changed {
menuContainer.view.frame = CGRectMake(offset, view.frame.origin.y, view.frame.size.width, view.frame.size.height)
} else if (panState == .Ended) || (panState == .Cancelled) {
let fMain = mainContainer.view.frame
let duration: CGFloat!
if (shouldOpen) {
duration = ((distanceOpenMenu - fMain.origin.x) * 0.3 ) / distanceOpenMenu
} else {
duration = ((fMain.origin.x) * 0.3 ) / distanceOpenMenu
}
animateViewSlide(menuContainer.view, toOffset: offset, toAlpha: 0, duration: Double(duration), delay: 0.1, completion:nil)
}
}
private func setSlideMenuVisible(visible: Bool, animated: Bool) {
if visible == true {
if animated == true {
animateViewSlide(menuContainer.view, toOffset: 0, toAlpha: 0.3, duration: 0.3, delay: 0.0, completion:nil)
} else {
menuContainer.view.frame = CGRectMake(0, view.frame.origin.y, view.frame.size.width, view.frame.size.height)
}
} else {
let offset = -(distanceOpenMenu * 0.2)
if animated == true {
animateViewSlide(menuContainer.view, toOffset: offset, toAlpha: 0.3, duration: 0.3, delay: 0.1, completion:nil)
} else {
menuContainer.view.frame = CGRectMake(offset, view.frame.origin.y, view.frame.size.width, view.frame.size.height)
}
}
}
private func animateViewSlide(view: UIView, toOffset: CGFloat, toAlpha: CGFloat, duration: NSTimeInterval, delay: NSTimeInterval, completion: ((Bool) -> Void)?) {
UIView.animateWithDuration(duration, delay: delay, options: .CurveLinear, animations: { () -> Void in
view.frame = CGRectMake(toOffset, view.frame.origin.y, view.frame.size.width, view.frame.size.height)
}) { (finished: Bool) -> Void in
completion?(finished)
}
}
}
| mit | 33568a2f2f5955ce5af6d94b6dca7591 | 33.313008 | 191 | 0.602121 | 4.851149 | false | false | false | false |
tardieu/swift | test/DebugInfo/return.swift | 3 | 942 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -g -emit-ir -o - | %FileCheck %s
class X {
init (i : Int64) { x = i }
var x : Int64
}
// CHECK: define {{.*}}ifelseexpr
public func ifelseexpr() -> Int64 {
var x = X(i:0)
// CHECK: [[META:%.*]] = call %swift.type* @_T06return1XCMa()
// CHECK: [[X:%.*]] = call %C6return1X* @_T06return1XCACs5Int64V1i_tcfC(
// CHECK-SAME: i64 0, %swift.type* [[META]])
// CHECK: @swift_rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]])
if true {
x.x += 1
} else {
x.x -= 1
}
// CHECK: @swift_rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]])
// CHECK-SAME: , !dbg ![[RELEASE:.*]]
// The ret instruction should be in the same scope as the return expression.
// CHECK: ret{{.*}}, !dbg ![[RELEASE]]
return x.x // CHECK: ![[RELEASE]] = !DILocation(line: [[@LINE]], column: 3
}
| apache-2.0 | bf04d47572982758d674993e718359c2 | 33.888889 | 97 | 0.546709 | 2.981013 | false | false | false | false |
ibari/StationToStation | StationToStation/DataStoreClient.swift | 1 | 21513 | //
// DataStoreClient.swift
// StationToStation
//
// Created by Benjamin Tsai on 6/6/15.
// Copyright (c) 2015 Ian Bari. All rights reserved.
//
import UIKit
class DataStoreClient {
func onApplicationLaunch() {
let applicationId = Utils.sharedInstance.getSecret("parse_application_id")
let clientKey = Utils.sharedInstance.getSecret("parse_client_key")
Parse.setApplicationId(applicationId, clientKey: clientKey)
}
class var sharedInstance: DataStoreClient {
struct Static {
static let instance = DataStoreClient()
}
return Static.instance
}
// MARK: - Station
private static let station_ClassName = "Station"
private static let station_ObjectId = "objectId"
private static let station_OwnerKey = "owner_key"
private static let station_PlaylistKey = "playlist_key"
private static let station_Name = "name"
private static let station_Description = "description"
private static let station_ImageFile = "imageFile"
private static let station_PlaylistMeta = "playlist_meta"
func getAllStations(completion: (stations: [Station]?, error: NSError?) -> Void) {
getCollaboratingStations(completion)
}
class func loadAll(completion: (stations: [Station]?, error: NSError?) -> Void) {
DataStoreClient.sharedInstance.getAllStations(completion)
}
func getStations(completion: (stations: [Station]?, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.station_ClassName)
query.whereKey(DataStoreClient.station_OwnerKey, equalTo: User.currentUser!.key)
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(stations: nil, error: error)
return
}
if let objects = objects as? [PFObject] {
var stations = [Station]()
for obj in objects {
stations.append(self.pfoToStation(obj))
}
self.loadStationProperties(stations, completion: completion)
} else {
completion(stations: [], error: nil)
return
}
}
}
func getStations(ids: [String], completion: (stations: [Station]?, error: NSError?) -> Void) {
NSLog("getStations \(ids)")
var query: PFQuery = PFQuery(className: DataStoreClient.station_ClassName)
query.whereKey("objectId", containedIn: ids)
query.findObjectsInBackgroundWithBlock { (objs: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(stations: nil, error: error)
return
}
var stations = [Station]()
for obj in objs! {
stations.append(self.pfoToStation(obj as! PFObject))
}
self.loadStationProperties(stations, completion: completion)
}
}
func getInvitedStations(completion: (stations: [Station]?, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.invite_ClassName)
query.whereKey(DataStoreClient.invite_toUserKey, equalTo: User.currentUser!.key)
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(stations: nil, error: error)
return
}
if let objects = objects as? [PFObject] {
var stationIds = [String]()
for obj in objects {
stationIds.append(obj[DataStoreClient.invite_stationObjectId] as! String)
}
self.getStations(stationIds, completion: completion)
return
} else {
completion(stations: [], error: nil)
return
}
}
}
func getCollaboratingStations(completion: (stations: [Station]?, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.collaborator_ClassName)
query.whereKey(DataStoreClient.collaborator_userKey, equalTo: User.currentUser!.key)
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(stations: nil, error: error)
return
}
if let objects = objects as? [PFObject] {
var stationIds = [String]()
for obj in objects {
stationIds.append(obj[DataStoreClient.collaborator_stationObjectId] as! String)
}
self.getStations(stationIds, completion: completion)
return
} else {
completion(stations: [], error: nil)
return
}
}
}
func getStation(objectId: String, completion: (station: Station?, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.station_ClassName)
query.getObjectInBackgroundWithId(objectId) { (obj: PFObject?, error: NSError?) -> Void in
if error == nil && obj != nil {
let stationObj = self.pfoToStation(obj!)
self.loadStationProperties([stationObj]) { (stations, error) in
var station = stations?.first
completion(station: station, error: error)
}
} else {
completion(station: nil, error: error)
}
}
}
func handleOnComplete(stations: [Station], collabCount: Int, playlistCount: Int, commentsCount: Int, completion: (stations: [Station]?, error: NSError?) -> Void) {
if stations.count == collabCount && stations.count == playlistCount && stations.count == commentsCount {
completion(stations: stations, error: nil)
}
}
func loadStationProperties(stations: [Station], completion: (stations: [Station]?, error: NSError?) -> Void) {
var loadedStationCollaboratorCount = 0
var loadedStationPlaylistCount = 0
var loadedStationCommentsCount = 0
for station in stations {
getCollaborators(station, completion: { (users, error) -> Void in
if let error = error {
NSLog("Error while loading collaborators in loadStationProperties: \(error)")
return
}
station.collaborators = users
loadedStationCollaboratorCount += 1
self.handleOnComplete(stations, collabCount: loadedStationCollaboratorCount, playlistCount: loadedStationPlaylistCount, commentsCount: loadedStationCommentsCount, completion: completion)
})
getStationComments(station.objectId!, completion: { (comments, error) -> Void in
if let error = error {
NSLog("Error while loading comments for station in loadStationProperties: \(error)")
return
}
station.comments = comments
loadedStationCommentsCount += 1
self.handleOnComplete(stations, collabCount: loadedStationCollaboratorCount, playlistCount: loadedStationPlaylistCount, commentsCount: loadedStationCommentsCount, completion: completion)
})
RdioClient.sharedInstance.getPlaylist(station.playlistKey, withMeta: station.playlistMeta, completion: { (playlist: Playlist?, error: NSError?) in
if let error = error {
NSLog("Error while loading playlist in loadStationProperties: \(error)")
return
}
station.playlist = playlist
loadedStationPlaylistCount += 1
self.handleOnComplete(stations, collabCount: loadedStationCollaboratorCount, playlistCount: loadedStationPlaylistCount, commentsCount: loadedStationCommentsCount, completion: completion)
})
}
}
func saveStation(station: Station, completion: (success: Bool, error: NSError?) -> Void) {
if let objectId = station.objectId {
// Update
let pfo = stationToPfo(station)
pfo.objectId = objectId
pfo.saveInBackgroundWithBlock(completion)
} else {
// Create
let pfo = stationToPfo(station)
pfo.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) in
station.objectId = pfo.objectId
completion(success: success, error: error)
})
}
}
func pfoToStation(obj: PFObject) -> Station {
var image: UIImage?
/*if let imageData = obj[DataStoreClient.station_ImageFile] as? NSData {
image = UIImage(data: imageData)
}*/
let station = Station(
ownerKey: obj[DataStoreClient.station_OwnerKey] as! String,
playlistKey: obj[DataStoreClient.station_PlaylistKey] as! String,
name: obj[DataStoreClient.station_Name] as! String,
description: obj[DataStoreClient.station_Description] as! String,
image: image,
playlistMetaDict: obj[DataStoreClient.station_PlaylistMeta] as? [String: AnyObject]
)
station.objectId = obj.objectId!
if let imageFile = obj[DataStoreClient.station_ImageFile] as? PFFile {
station.imageUrl = imageFile.url!
}
return station
}
func stationToPfo(station: Station) -> PFObject {
var obj = PFObject(className: DataStoreClient.station_ClassName)
if let image = station.image {
let imageData = UIImageJPEGRepresentation(image, 0.7)
let imageFile = PFFile(name: "header-image.jpg", data: imageData)
obj[DataStoreClient.station_ImageFile] = imageFile
}
obj[DataStoreClient.station_OwnerKey] = station.ownerKey
obj[DataStoreClient.station_Name] = station.name
obj[DataStoreClient.station_Description] = station.description
obj[DataStoreClient.station_PlaylistKey] = station.playlistKey
obj[DataStoreClient.station_PlaylistMeta] = station.playlistMeta.getData()
return obj
}
// MARK: - Invite
private static let invite_ClassName = "Invite"
private static let invite_fromUserKey = "fromUserKey"
private static let invite_toUserKey = "toUserkey"
private static let invite_stationObjectId = "stationObjectId"
private static let invite_accepted = "accepted"
func getInvites(completion: (invites: [Invite]?, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.invite_ClassName)
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(invites: nil, error: error)
return
}
if let objects = objects as? [PFObject] {
var invites = [Invite]()
for obj in objects {
invites.append(self.pfoToInvite(obj))
}
completion(invites: invites, error: nil)
} else {
completion(invites: [], error: nil)
return
}
}
}
func saveInvite(invite: Invite, completion: (success: Bool, error: NSError?) -> Void) {
inviteToPfo(invite).saveInBackgroundWithBlock(completion)
}
func pfoToInvite(obj: PFObject) -> Invite {
return Invite(
fromUserKey: obj[DataStoreClient.invite_fromUserKey] as! String,
toUserKey: obj[DataStoreClient.invite_toUserKey] as! String,
stationObjectId: obj[DataStoreClient.invite_stationObjectId] as! String,
accepted: obj[DataStoreClient.invite_accepted] as! Bool
)
}
func inviteToPfo(invite: Invite) -> PFObject {
var obj = PFObject(className: DataStoreClient.invite_ClassName)
obj[DataStoreClient.invite_fromUserKey] = invite.fromUserKey
obj[DataStoreClient.invite_toUserKey] = invite.toUserKey
obj[DataStoreClient.invite_stationObjectId] = invite.stationObjectId
obj[DataStoreClient.invite_accepted] = invite.accepted
return obj
}
// MARK: - Collaborator
private static let collaborator_ClassName = "Collaborator"
private static let collaborator_objectId = "objectId"
private static let collaborator_userKey = "userKey"
private static let collaborator_stationObjectId = "stationObjectId"
func getCollaborators(station: Station, completion: (users: [User]?, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.collaborator_ClassName)
query.whereKey(DataStoreClient.collaborator_stationObjectId, equalTo: station.objectId!)
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(users: nil, error: error)
return
}
if let objects = objects as? [PFObject] {
var userKeys = [String]()
for obj in objects {
userKeys.append(obj[DataStoreClient.collaborator_userKey] as! String)
}
RdioClient.sharedInstance.getUsers(userKeys, completion: completion)
return
} else {
completion(users: [], error: nil)
return
}
}
}
func saveCollaborator(collaborator: User, station: Station, completion: (success: Bool, error: NSError?) -> Void) {
collaboratorToPfo(collaborator, station: station).saveInBackgroundWithBlock(completion)
}
func deleteCollaborator(collaborator: User, station: Station, completion: (success: Bool, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.collaborator_ClassName)
query.whereKey(DataStoreClient.collaborator_userKey, equalTo: collaborator.key)
query.whereKey(DataStoreClient.collaborator_stationObjectId, equalTo: station.objectId!)
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(success: false, error: error)
return
}
if let objects = objects as? [PFObject] {
for obj in objects {
obj.deleteInBackgroundWithBlock(completion)
}
} else {
completion(success: false, error: nil)
return
}
}
}
func collaboratorToPfo(collaborator: User, station: Station) -> PFObject {
var obj = PFObject(className: DataStoreClient.collaborator_ClassName)
obj[DataStoreClient.collaborator_userKey] = collaborator.key
obj[DataStoreClient.collaborator_stationObjectId] = station.objectId
return obj
}
func isCollaborator(user: User, station: Station, completion: (collaborator: Bool?, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.collaborator_ClassName)
query.whereKey(DataStoreClient.collaborator_userKey, equalTo: user.key)
query.whereKey(DataStoreClient.collaborator_stationObjectId, equalTo: station.objectId!)
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(collaborator: nil, error: error)
return
}
if let objects = objects as? [PFObject] {
var collaborators = [String]()
for obj in objects {
collaborators.append(obj[DataStoreClient.collaborator_userKey] as! String)
}
let collaborator = (collaborators.first != nil) ? true : false
completion(collaborator: collaborator, error: nil)
return
} else {
completion(collaborator: false, error: nil)
return
}
}
}
// MARK: - Comment
private static let comment_ClassName = "Comment"
private static let comment_stationObjectId = "stationObjectId"
private static let comment_trackKey = "trackKey"
private static let comment_userKey = "userKey"
private static let comment_text = "text"
func getTrackComments(trackKey: String, completion: (comments: [Comment]?, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.comment_ClassName)
query.whereKey(DataStoreClient.comment_trackKey, equalTo: trackKey)
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(comments: nil, error: error)
return
}
if let objects = objects as? [PFObject] {
var comments = [Comment]()
for obj in objects {
comments.append(self.pfoToComment(obj))
}
self.loadCommentProperties(comments, completion: completion)
} else {
completion(comments: [], error: nil)
return
}
}
}
func getStationComments(objectId: String, completion: (comments: [Comment]?, error: NSError?) -> Void) {
var query: PFQuery = PFQuery(className: DataStoreClient.comment_ClassName)
query.whereKey(DataStoreClient.comment_stationObjectId, equalTo: objectId)
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in
if let error = error {
completion(comments: nil, error: error)
return
}
if let objects = objects as? [PFObject] {
var comments = [Comment]()
for obj in objects {
comments.append(self.pfoToComment(obj))
}
self.loadCommentProperties(comments, completion: completion)
} else {
completion(comments: [], error: nil)
return
}
}
}
func loadCommentProperties(comments: [Comment], completion: (comments: [Comment]?, error: NSError?) -> Void) {
var loadedCommentUserCount = 0
if comments.count == 0 {
completion(comments: comments, error: nil)
return
}
var userToComments = [String: [Comment]]()
for comment in comments {
if userToComments[comment.userKey!] == nil {
userToComments[comment.userKey!] = [Comment]()
}
userToComments[comment.userKey!]!.append(comment)
}
var loadedUserCount = 0
for userKey in userToComments.keys {
RdioClient.sharedInstance.getUser(userKey, completion: { (user, error) -> Void in
if let error = error {
NSLog("Error while loading user \(userKey) in loadCommentProperties: \(error)")
return
}
NSLog("Loaded user \(userKey) for comments \(userToComments[userKey])")
loadedUserCount += 1
for comment in userToComments[userKey]! {
comment.user = user!
}
if userToComments.count == loadedUserCount {
completion(comments: comments, error: nil)
}
})
}
}
func saveComment(comment: Comment, completion: (success: Bool, error: NSError?) -> Void) {
commentToPfo(comment).saveInBackgroundWithBlock(completion)
}
func pfoToComment(obj: PFObject) -> Comment {
return Comment(
stationObjectId: obj[DataStoreClient.comment_stationObjectId] as! String,
trackKey: obj[DataStoreClient.comment_trackKey] as! String,
userKey: obj[DataStoreClient.comment_userKey] as! String,
text: obj[DataStoreClient.comment_text] as! String
)
}
func commentToPfo(comment: Comment) -> PFObject {
var obj = PFObject(className: DataStoreClient.comment_ClassName)
obj[DataStoreClient.comment_stationObjectId] = comment.stationObjectId
obj[DataStoreClient.comment_trackKey] = comment.trackKey
obj[DataStoreClient.comment_userKey] = comment.userKey
obj[DataStoreClient.comment_text] = comment.text
return obj
}
}
| gpl-2.0 | 4f706f32b644e130bc40f263550cb814 | 39.977143 | 202 | 0.585367 | 5.117269 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/baseball-game.swift | 1 | 728 | /**
* https://leetcode.com/problems/baseball-game/
*
*
*/
// Date: Sat Apr 9 23:27:59 PDT 2022
class Solution {
func calPoints(_ ops: [String]) -> Int {
var result = [Int]()
for op in ops {
if op == "+" {
let n = result.count
let sum = result[n - 1] + result[n - 2]
result.append(sum)
} else if op == "D" {
let d = result[result.count - 1] * 2
result.append(d)
} else if op == "C" {
result.removeLast()
} else {
result.append(Int(op)!)
}
// print(result)
}
return result.reduce(0) { $0 + $1 }
}
} | mit | e796149d157edd16aff34a037a166623 | 26 | 55 | 0.410714 | 3.752577 | false | false | false | false |
rafaelGuerreiro/swift-websocket | Sources/App/WebSocketSession.swift | 1 | 959 | import Vapor
class WebSocketSession: Equatable, Hashable, CustomStringConvertible {
let id: String
let username: String
let socket: WebSocket
init(id: String, username: String, socket: WebSocket) {
self.id = id
self.username = username
self.socket = socket
}
var description: String {
return "\(id) -> \(username)"
}
var hashValue: Int {
return id.hashValue
}
static func == (lhs: WebSocketSession, rhs: WebSocketSession) -> Bool {
return lhs.id == rhs.id
}
func send(_ message: String) {
send(MessageOutputData(message: message, sent: Date.currentTimestamp(), received: Date.currentTimestamp()))
}
func send(_ output: MessageOutputData) {
if let json = try? output.makeJSON(),
let bytes = try? json.makeBytes() {
print("Sending to \(id)")
try? socket.send(bytes.makeString())
}
}
}
| mit | fc4266ca10be63d8032b4ef2f49d872d | 24.236842 | 115 | 0.596455 | 4.359091 | false | false | false | false |
colbylwilliams/bugtrap | iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/JIRA/Domain/JiraPriority.swift | 1 | 1384 | //
// JiraPriority.swift
// bugTrap
//
// Created by Colby L Williams on 12/5/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
class JiraPriority : JiraSimpleItem {
var statusColor = ""
override init() {
super.init()
}
init(id: Int?, name: String, key: String, selfUrl: String, iconUrl: String, details: String, expand: String, statusColor: String) {
super.init(id: id, name: name, key: key, selfUrl: selfUrl, iconUrl: iconUrl, details: details, expand: expand)
self.statusColor = statusColor
}
override class func deserialize (json: JSON) -> JiraPriority? {
let id = json["id"].intValue
let name = json["name"].stringValue
let key = json["key"].stringValue
let selfUrl = json["self"].stringValue
let iconUrl = json["iconUrl"].stringValue
let details = json["description"].stringValue
let expand = json["expand"].stringValue
let statusColor = json["statusColor"].stringValue
return JiraPriority(id: id, name: name, key: key, selfUrl: selfUrl, iconUrl: iconUrl, details: details, expand: expand, statusColor: statusColor)
}
class func deserializeAll(json: JSON) -> [JiraPriority] {
var items = [JiraPriority]()
if let jsonArray = json.array {
for item: JSON in jsonArray {
if let si = deserialize(item) {
items.append(si)
}
}
}
return items
}
} | mit | e1b2a4ddcf8437d9196db1a9c8d4217d | 22.474576 | 147 | 0.669798 | 3.486146 | false | false | false | false |
lorentey/swift | test/IRGen/multi_module_resilience.swift | 12 | 3918 | // 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 -emit-module -I %t \
// RUN: -emit-module-path=%t/OtherModule.swiftmodule \
// RUN: -module-name=OtherModule %S/Inputs/OtherModule.swift
// RUN: %target-swift-frontend -module-name main -I %t -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize
// rdar://39763787
import OtherModule
// CHECK-LABEL: define {{(dllexport |protected )?}}swiftcc void @"$s4main7copyFoo3foo11OtherModule0C0VAF_tF"
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s11OtherModule3FooVMa"([[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:%T11OtherModule3FooV]]*
// 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
}
// CHECK-LABEL: define {{(dllexport |protected )?}}swiftcc void @"$s4main7copyBar3bar11OtherModule0C0VAF_tF"
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s11OtherModule3BarVMa"([[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 [[BAR:%T11OtherModule3BarV]]*
// 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 [[BAR]]* [[COPY]] to %swift.opaque*
// CHECK: [[SRC:%.*]] = bitcast [[BAR]]* %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 [[BAR]]* %0 to %swift.opaque*
// CHECK: [[SRC:%.*]] = bitcast [[BAR]]* [[COPY]] to %swift.opaque*
// CHECK: call %swift.opaque* [[COPYFN]](%swift.opaque* noalias [[DEST]], %swift.opaque* noalias [[SRC]], %swift.type* [[METADATA]])
public func copyBar(bar: Bar) -> Bar {
let copy = bar
return copy
}
| apache-2.0 | 5b16cd52f15f36d7114775b7ef2d4ffc | 56.617647 | 132 | 0.612813 | 3.203598 | false | false | false | false |
glessard/swift-atomics | Sources/SwiftAtomics/atomics-pointer.swift | 1 | 59524 | //
// atomics-pointer.swift
// Atomics
//
// Created by Guillaume Lessard on 2015-05-21.
// Copyright © 2015-2017 Guillaume Lessard. All rights reserved.
// This file is distributed under the BSD 3-clause license. See LICENSE for details.
//
@_exported import enum CAtomics.MemoryOrder
@_exported import enum CAtomics.LoadMemoryOrder
@_exported import enum CAtomics.StoreMemoryOrder
@_exported import enum CAtomics.CASType
import CAtomics
public struct AtomicPointer<Pointee>
{
#if swift(>=4.2)
@usableFromInline var ptr = AtomicRawPointer()
#else
@_versioned var ptr = AtomicRawPointer()
#endif
public init(_ pointer: UnsafePointer<Pointee>)
{
CAtomicsInitialize(&ptr, pointer)
}
public mutating func initialize(_ pointer: UnsafePointer<Pointee>)
{
CAtomicsInitialize(&ptr, pointer)
}
#if swift(>=4.2)
public var pointer: UnsafePointer<Pointee> {
@inlinable
mutating get {
return CAtomicsLoad(&ptr, .acquire).assumingMemoryBound(to: Pointee.self)
}
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafePointer<Pointee>
{
return CAtomicsLoad(&ptr, order).assumingMemoryBound(to: Pointee.self)
}
@inlinable
public mutating func store(_ pointer: UnsafePointer<Pointee>, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&ptr, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: UnsafePointer<Pointee>, order: MemoryOrder = .acqrel) -> UnsafePointer<Pointee>
{
return CAtomicsExchange(&ptr, pointer, order).assumingMemoryBound(to: Pointee.self)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout UnsafePointer<Pointee>,
future: UnsafePointer<Pointee>,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = UnsafeRawPointer(current)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&ptr, &c, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&ptr, &c, future, orderSwap, orderLoad)
current = c.assumingMemoryBound(to: Pointee.self)
return s
}
@inlinable @discardableResult
public mutating func CAS(current: UnsafePointer<Pointee>, future: UnsafePointer<Pointee>,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: UnsafePointer<Pointee> {
@inline(__always)
mutating get {
return CAtomicsLoad(&ptr, .acquire).assumingMemoryBound(to: Pointee.self)
}
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafePointer<Pointee>
{
return CAtomicsLoad(&ptr, order).assumingMemoryBound(to: Pointee.self)
}
@inline(__always)
public mutating func store(_ pointer: UnsafePointer<Pointee>, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&ptr, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: UnsafePointer<Pointee>, order: MemoryOrder = .acqrel) -> UnsafePointer<Pointee>
{
return CAtomicsExchange(&ptr, pointer, order).assumingMemoryBound(to: Pointee.self)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout UnsafePointer<Pointee>,
future: UnsafePointer<Pointee>,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = UnsafeRawPointer(current)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&ptr, &c, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&ptr, &c, future, orderSwap, orderLoad)
current = c.assumingMemoryBound(to: Pointee.self)
return s
}
@inline(__always) @discardableResult
public mutating func CAS(current: UnsafePointer<Pointee>, future: UnsafePointer<Pointee>,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
public struct AtomicMutablePointer<Pointee>
{
#if swift(>=4.2)
@usableFromInline var ptr = AtomicMutableRawPointer()
#else
@_versioned var ptr = AtomicMutableRawPointer()
#endif
public init(_ pointer: UnsafeMutablePointer<Pointee>)
{
CAtomicsInitialize(&ptr, pointer)
}
public mutating func initialize(_ pointer: UnsafeMutablePointer<Pointee>)
{
CAtomicsInitialize(&ptr, pointer)
}
#if swift(>=4.2)
public var pointer: UnsafeMutablePointer<Pointee> {
@inlinable
mutating get {
return CAtomicsLoad(&ptr, .acquire).assumingMemoryBound(to: Pointee.self)
}
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeMutablePointer<Pointee>
{
return CAtomicsLoad(&ptr, order).assumingMemoryBound(to: Pointee.self)
}
@inlinable
public mutating func store(_ pointer: UnsafeMutablePointer<Pointee>, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&ptr, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: UnsafeMutablePointer<Pointee>, order: MemoryOrder = .acqrel) -> UnsafeMutablePointer<Pointee>
{
return CAtomicsExchange(&ptr, pointer, order).assumingMemoryBound(to: Pointee.self)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout UnsafeMutablePointer<Pointee>,
future: UnsafeMutablePointer<Pointee>,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = UnsafeMutableRawPointer(current)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&ptr, &c, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&ptr, &c, future, orderSwap, orderLoad)
current = c.assumingMemoryBound(to: Pointee.self)
return s
}
@inlinable @discardableResult
public mutating func CAS(current: UnsafeMutablePointer<Pointee>, future: UnsafeMutablePointer<Pointee>,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: UnsafeMutablePointer<Pointee> {
@inline(__always)
mutating get {
return CAtomicsLoad(&ptr, .acquire).assumingMemoryBound(to: Pointee.self)
}
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeMutablePointer<Pointee>
{
return CAtomicsLoad(&ptr, order).assumingMemoryBound(to: Pointee.self)
}
@inline(__always)
public mutating func store(_ pointer: UnsafeMutablePointer<Pointee>, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&ptr, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: UnsafeMutablePointer<Pointee>, order: MemoryOrder = .acqrel) -> UnsafeMutablePointer<Pointee>
{
return CAtomicsExchange(&ptr, pointer, order).assumingMemoryBound(to: Pointee.self)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout UnsafeMutablePointer<Pointee>,
future: UnsafeMutablePointer<Pointee>,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = UnsafeMutableRawPointer(current)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&ptr, &c, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&ptr, &c, future, orderSwap, orderLoad)
current = c.assumingMemoryBound(to: Pointee.self)
return s
}
@inline(__always) @discardableResult
public mutating func CAS(current: UnsafeMutablePointer<Pointee>, future: UnsafeMutablePointer<Pointee>,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
public struct AtomicOptionalPointer<Pointee>
{
#if swift(>=4.2)
@usableFromInline var ptr = AtomicOptionalRawPointer()
#else
@_versioned var ptr = AtomicOptionalRawPointer()
#endif
public init()
{
CAtomicsInitialize(&ptr, nil)
}
public init(_ pointer: UnsafePointer<Pointee>?)
{
CAtomicsInitialize(&ptr, pointer)
}
public mutating func initialize(_ pointer: UnsafePointer<Pointee>?)
{
CAtomicsInitialize(&ptr, pointer)
}
#if swift(>=4.2)
public var pointer: UnsafePointer<Pointee>? {
@inlinable
mutating get {
return CAtomicsLoad(&ptr, .acquire)?.assumingMemoryBound(to: Pointee.self)
}
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafePointer<Pointee>?
{
return CAtomicsLoad(&ptr, order)?.assumingMemoryBound(to: Pointee.self)
}
@inlinable
public mutating func store(_ pointer: UnsafePointer<Pointee>?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&ptr, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: UnsafePointer<Pointee>?, order: MemoryOrder = .acqrel) -> UnsafePointer<Pointee>?
{
return CAtomicsExchange(&ptr, pointer, order)?.assumingMemoryBound(to: Pointee.self)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout UnsafePointer<Pointee>?,
future: UnsafePointer<Pointee>?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = UnsafeRawPointer(current)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&ptr, &c, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&ptr, &c, future, orderSwap, orderLoad)
current = c?.assumingMemoryBound(to: Pointee.self)
return s
}
@inlinable @discardableResult
public mutating func CAS(current: UnsafePointer<Pointee>?, future: UnsafePointer<Pointee>?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: UnsafePointer<Pointee>? {
@inline(__always)
mutating get {
return CAtomicsLoad(&ptr, .acquire)?.assumingMemoryBound(to: Pointee.self)
}
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafePointer<Pointee>?
{
return CAtomicsLoad(&ptr, order)?.assumingMemoryBound(to: Pointee.self)
}
@inline(__always)
public mutating func store(_ pointer: UnsafePointer<Pointee>?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&ptr, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: UnsafePointer<Pointee>?, order: MemoryOrder = .acqrel) -> UnsafePointer<Pointee>?
{
return CAtomicsExchange(&ptr, pointer, order)?.assumingMemoryBound(to: Pointee.self)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout UnsafePointer<Pointee>?,
future: UnsafePointer<Pointee>?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = UnsafeRawPointer(current)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&ptr, &c, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&ptr, &c, future, orderSwap, orderLoad)
current = c?.assumingMemoryBound(to: Pointee.self)
return s
}
@inline(__always) @discardableResult
public mutating func CAS(current: UnsafePointer<Pointee>?, future: UnsafePointer<Pointee>?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
public struct AtomicOptionalMutablePointer<Pointee>
{
#if swift(>=4.2)
@usableFromInline var ptr = AtomicOptionalMutableRawPointer()
#else
@_versioned var ptr = AtomicOptionalMutableRawPointer()
#endif
public init()
{
CAtomicsInitialize(&ptr, nil)
}
public init(_ pointer: UnsafeMutablePointer<Pointee>?)
{
CAtomicsInitialize(&ptr, pointer)
}
public mutating func initialize(_ pointer: UnsafeMutablePointer<Pointee>?)
{
CAtomicsInitialize(&ptr, pointer)
}
#if swift(>=4.2)
public var pointer: UnsafeMutablePointer<Pointee>? {
@inlinable
mutating get {
return CAtomicsLoad(&ptr, .acquire)?.assumingMemoryBound(to: Pointee.self)
}
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeMutablePointer<Pointee>?
{
return CAtomicsLoad(&ptr, order)?.assumingMemoryBound(to: Pointee.self)
}
@inlinable
public mutating func store(_ pointer: UnsafeMutablePointer<Pointee>?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&ptr, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: UnsafeMutablePointer<Pointee>?, order: MemoryOrder = .acqrel) -> UnsafeMutablePointer<Pointee>?
{
return CAtomicsExchange(&ptr, pointer, order)?.assumingMemoryBound(to: Pointee.self)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout UnsafeMutablePointer<Pointee>?,
future: UnsafeMutablePointer<Pointee>?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = UnsafeMutableRawPointer(current)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&ptr, &c, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&ptr, &c, future, orderSwap, orderLoad)
current = c?.assumingMemoryBound(to: Pointee.self)
return s
}
@inlinable @discardableResult
public mutating func CAS(current: UnsafeMutablePointer<Pointee>?, future: UnsafeMutablePointer<Pointee>?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: UnsafeMutablePointer<Pointee>? {
@inline(__always)
mutating get {
return CAtomicsLoad(&ptr, .acquire)?.assumingMemoryBound(to: Pointee.self)
}
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeMutablePointer<Pointee>?
{
return CAtomicsLoad(&ptr, order)?.assumingMemoryBound(to: Pointee.self)
}
@inline(__always)
public mutating func store(_ pointer: UnsafeMutablePointer<Pointee>?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&ptr, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: UnsafeMutablePointer<Pointee>?, order: MemoryOrder = .acqrel) -> UnsafeMutablePointer<Pointee>?
{
return CAtomicsExchange(&ptr, pointer, order)?.assumingMemoryBound(to: Pointee.self)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout UnsafeMutablePointer<Pointee>?,
future: UnsafeMutablePointer<Pointee>?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = UnsafeMutableRawPointer(current)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&ptr, &c, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&ptr, &c, future, orderSwap, orderLoad)
current = c?.assumingMemoryBound(to: Pointee.self)
return s
}
@inline(__always) @discardableResult
public mutating func CAS(current: UnsafeMutablePointer<Pointee>?, future: UnsafeMutablePointer<Pointee>?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicRawPointer
extension AtomicRawPointer
{
#if swift(>=4.2)
public var pointer: UnsafeRawPointer {
@inlinable
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inlinable
public mutating func initialize(_ pointer: UnsafeRawPointer)
{
CAtomicsInitialize(&self, pointer)
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeRawPointer
{
return CAtomicsLoad(&self, order)
}
@inlinable
public mutating func store(_ pointer: UnsafeRawPointer, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: UnsafeRawPointer, order: MemoryOrder = .acqrel) -> UnsafeRawPointer
{
return CAtomicsExchange(&self, pointer, order)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout UnsafeRawPointer,
future: UnsafeRawPointer,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inlinable @discardableResult
public mutating func CAS(current: UnsafeRawPointer, future: UnsafeRawPointer,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: UnsafeRawPointer {
@inline(__always)
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inline(__always)
public mutating func initialize(_ pointer: UnsafeRawPointer)
{
CAtomicsInitialize(&self, pointer)
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeRawPointer
{
return CAtomicsLoad(&self, order)
}
@inline(__always)
public mutating func store(_ pointer: UnsafeRawPointer, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: UnsafeRawPointer, order: MemoryOrder = .acqrel) -> UnsafeRawPointer
{
return CAtomicsExchange(&self, pointer, order)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout UnsafeRawPointer,
future: UnsafeRawPointer,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inline(__always) @discardableResult
public mutating func CAS(current: UnsafeRawPointer, future: UnsafeRawPointer,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicOptionalRawPointer
extension AtomicOptionalRawPointer
{
#if swift(>=4.2)
public var pointer: UnsafeRawPointer? {
@inlinable
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inlinable
public mutating func initialize(_ pointer: UnsafeRawPointer?)
{
CAtomicsInitialize(&self, pointer)
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeRawPointer?
{
return CAtomicsLoad(&self, order)
}
@inlinable
public mutating func store(_ pointer: UnsafeRawPointer?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: UnsafeRawPointer?, order: MemoryOrder = .acqrel) -> UnsafeRawPointer?
{
return CAtomicsExchange(&self, pointer, order)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout UnsafeRawPointer?,
future: UnsafeRawPointer?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inlinable @discardableResult
public mutating func CAS(current: UnsafeRawPointer?, future: UnsafeRawPointer?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: UnsafeRawPointer? {
@inline(__always)
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inline(__always)
public mutating func initialize(_ pointer: UnsafeRawPointer?)
{
CAtomicsInitialize(&self, pointer)
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeRawPointer?
{
return CAtomicsLoad(&self, order)
}
@inline(__always)
public mutating func store(_ pointer: UnsafeRawPointer?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: UnsafeRawPointer?, order: MemoryOrder = .acqrel) -> UnsafeRawPointer?
{
return CAtomicsExchange(&self, pointer, order)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout UnsafeRawPointer?,
future: UnsafeRawPointer?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inline(__always) @discardableResult
public mutating func CAS(current: UnsafeRawPointer?, future: UnsafeRawPointer?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicMutableRawPointer
extension AtomicMutableRawPointer
{
#if swift(>=4.2)
public var pointer: UnsafeMutableRawPointer {
@inlinable
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inlinable
public mutating func initialize(_ pointer: UnsafeMutableRawPointer)
{
CAtomicsInitialize(&self, pointer)
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeMutableRawPointer
{
return CAtomicsLoad(&self, order)
}
@inlinable
public mutating func store(_ pointer: UnsafeMutableRawPointer, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: UnsafeMutableRawPointer, order: MemoryOrder = .acqrel) -> UnsafeMutableRawPointer
{
return CAtomicsExchange(&self, pointer, order)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout UnsafeMutableRawPointer,
future: UnsafeMutableRawPointer,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inlinable @discardableResult
public mutating func CAS(current: UnsafeMutableRawPointer, future: UnsafeMutableRawPointer,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: UnsafeMutableRawPointer {
@inline(__always)
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inline(__always)
public mutating func initialize(_ pointer: UnsafeMutableRawPointer)
{
CAtomicsInitialize(&self, pointer)
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeMutableRawPointer
{
return CAtomicsLoad(&self, order)
}
@inline(__always)
public mutating func store(_ pointer: UnsafeMutableRawPointer, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: UnsafeMutableRawPointer, order: MemoryOrder = .acqrel) -> UnsafeMutableRawPointer
{
return CAtomicsExchange(&self, pointer, order)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout UnsafeMutableRawPointer,
future: UnsafeMutableRawPointer,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inline(__always) @discardableResult
public mutating func CAS(current: UnsafeMutableRawPointer, future: UnsafeMutableRawPointer,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicOptionalMutableRawPointer
extension AtomicOptionalMutableRawPointer
{
#if swift(>=4.2)
public var pointer: UnsafeMutableRawPointer? {
@inlinable
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inlinable
public mutating func initialize(_ pointer: UnsafeMutableRawPointer?)
{
CAtomicsInitialize(&self, pointer)
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeMutableRawPointer?
{
return CAtomicsLoad(&self, order)
}
@inlinable
public mutating func store(_ pointer: UnsafeMutableRawPointer?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: UnsafeMutableRawPointer?, order: MemoryOrder = .acqrel) -> UnsafeMutableRawPointer?
{
return CAtomicsExchange(&self, pointer, order)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout UnsafeMutableRawPointer?,
future: UnsafeMutableRawPointer?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inlinable @discardableResult
public mutating func CAS(current: UnsafeMutableRawPointer?, future: UnsafeMutableRawPointer?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: UnsafeMutableRawPointer? {
@inline(__always)
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inline(__always)
public mutating func initialize(_ pointer: UnsafeMutableRawPointer?)
{
CAtomicsInitialize(&self, pointer)
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> UnsafeMutableRawPointer?
{
return CAtomicsLoad(&self, order)
}
@inline(__always)
public mutating func store(_ pointer: UnsafeMutableRawPointer?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: UnsafeMutableRawPointer?, order: MemoryOrder = .acqrel) -> UnsafeMutableRawPointer?
{
return CAtomicsExchange(&self, pointer, order)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout UnsafeMutableRawPointer?,
future: UnsafeMutableRawPointer?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inline(__always) @discardableResult
public mutating func CAS(current: UnsafeMutableRawPointer?, future: UnsafeMutableRawPointer?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicOpaquePointer
extension AtomicOpaquePointer
{
#if swift(>=4.2)
public var pointer: OpaquePointer {
@inlinable
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inlinable
public mutating func initialize(_ pointer: OpaquePointer)
{
CAtomicsInitialize(&self, pointer)
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> OpaquePointer
{
return CAtomicsLoad(&self, order)
}
@inlinable
public mutating func store(_ pointer: OpaquePointer, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: OpaquePointer, order: MemoryOrder = .acqrel) -> OpaquePointer
{
return CAtomicsExchange(&self, pointer, order)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout OpaquePointer,
future: OpaquePointer,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inlinable @discardableResult
public mutating func CAS(current: OpaquePointer, future: OpaquePointer,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: OpaquePointer {
@inline(__always)
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inline(__always)
public mutating func initialize(_ pointer: OpaquePointer)
{
CAtomicsInitialize(&self, pointer)
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> OpaquePointer
{
return CAtomicsLoad(&self, order)
}
@inline(__always)
public mutating func store(_ pointer: OpaquePointer, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: OpaquePointer, order: MemoryOrder = .acqrel) -> OpaquePointer
{
return CAtomicsExchange(&self, pointer, order)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout OpaquePointer,
future: OpaquePointer,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inline(__always) @discardableResult
public mutating func CAS(current: OpaquePointer, future: OpaquePointer,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicOptionalOpaquePointer
extension AtomicOptionalOpaquePointer
{
#if swift(>=4.2)
public var pointer: OpaquePointer? {
@inlinable
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inlinable
public mutating func initialize(_ pointer: OpaquePointer?)
{
CAtomicsInitialize(&self, pointer)
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> OpaquePointer?
{
return CAtomicsLoad(&self, order)
}
@inlinable
public mutating func store(_ pointer: OpaquePointer?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inlinable
public mutating func swap(_ pointer: OpaquePointer?, order: MemoryOrder = .acqrel) -> OpaquePointer?
{
return CAtomicsExchange(&self, pointer, order)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout OpaquePointer?,
future: OpaquePointer?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inlinable @discardableResult
public mutating func CAS(current: OpaquePointer?, future: OpaquePointer?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var pointer: OpaquePointer? {
@inline(__always)
mutating get {
return CAtomicsLoad(&self, .acquire)
}
}
@inline(__always)
public mutating func initialize(_ pointer: OpaquePointer?)
{
CAtomicsInitialize(&self, pointer)
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> OpaquePointer?
{
return CAtomicsLoad(&self, order)
}
@inline(__always)
public mutating func store(_ pointer: OpaquePointer?, order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, pointer, order)
}
@inline(__always)
public mutating func swap(_ pointer: OpaquePointer?, order: MemoryOrder = .acqrel) -> OpaquePointer?
{
return CAtomicsExchange(&self, pointer, order)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout OpaquePointer?,
future: OpaquePointer?,
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
return type == .weak
? CAtomicsCompareAndExchangeWeak(&self, ¤t, future, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, ¤t, future, orderSwap, orderLoad)
}
@inline(__always) @discardableResult
public mutating func CAS(current: OpaquePointer?, future: OpaquePointer?,
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicTaggedRawPointer
extension AtomicTaggedRawPointer
{
public init(_ p: (pointer: UnsafeRawPointer, tag: Int))
{
self.init(TaggedRawPointer(p.pointer, tag: p.tag))
}
#if swift(>=4.2)
public var value: (pointer: UnsafeRawPointer, tag: Int) {
@inlinable
mutating get {
let t = CAtomicsLoad(&self, .acquire)
return (t.ptr, t.tag)
}
}
@inlinable
public mutating func initialize(_ p: (pointer: UnsafeRawPointer, tag: Int))
{
CAtomicsInitialize(&self, TaggedRawPointer(p.pointer, tag: p.tag))
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> (pointer: UnsafeRawPointer, tag: Int)
{
let t = CAtomicsLoad(&self, order)
return (t.ptr, t.tag)
}
@inlinable
public mutating func store(_ p: (pointer: UnsafeRawPointer, tag: Int), order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, TaggedRawPointer(p.pointer, tag: p.tag), order)
}
@inlinable
public mutating func swap(_ p: (pointer: UnsafeRawPointer, tag: Int), order: MemoryOrder = .acqrel) -> (pointer: UnsafeRawPointer, tag: Int)
{
let t = CAtomicsExchange(&self, TaggedRawPointer(p.pointer, tag: p.tag), order)
return (t.ptr, t.tag)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout (pointer: UnsafeRawPointer, tag: Int),
future: (pointer: UnsafeRawPointer, tag: Int),
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = TaggedRawPointer(current.0, tag: current.1)
let f = TaggedRawPointer(future.0, tag: future.1)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&self, &c, f, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, &c, f, orderSwap, orderLoad)
current = (c.ptr, c.tag)
return s
}
@inlinable @discardableResult
public mutating func CAS(current: (pointer: UnsafeRawPointer, tag: Int),
future: (pointer: UnsafeRawPointer, tag: Int),
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var value: (pointer: UnsafeRawPointer, tag: Int) {
@inline(__always)
mutating get {
let t = CAtomicsLoad(&self, .acquire)
return (t.ptr, t.tag)
}
}
@inline(__always)
public mutating func initialize(_ p: (pointer: UnsafeRawPointer, tag: Int))
{
CAtomicsInitialize(&self, TaggedRawPointer(p.pointer, tag: p.tag))
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> (pointer: UnsafeRawPointer, tag: Int)
{
let t = CAtomicsLoad(&self, order)
return (t.ptr, t.tag)
}
@inline(__always)
public mutating func store(_ p: (pointer: UnsafeRawPointer, tag: Int), order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, TaggedRawPointer(p.pointer, tag: p.tag), order)
}
@inline(__always)
public mutating func swap(_ p: (pointer: UnsafeRawPointer, tag: Int), order: MemoryOrder = .acqrel) -> (pointer: UnsafeRawPointer, tag: Int)
{
let t = CAtomicsExchange(&self, TaggedRawPointer(p.pointer, tag: p.tag), order)
return (t.ptr, t.tag)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout (pointer: UnsafeRawPointer, tag: Int),
future: (pointer: UnsafeRawPointer, tag: Int),
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = TaggedRawPointer(current.0, tag: current.1)
let f = TaggedRawPointer(future.0, tag: future.1)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&self, &c, f, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, &c, f, orderSwap, orderLoad)
current = (c.ptr, c.tag)
return s
}
@inline(__always) @discardableResult
public mutating func CAS(current: (pointer: UnsafeRawPointer, tag: Int),
future: (pointer: UnsafeRawPointer, tag: Int),
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicTaggedOptionalRawPointer
extension AtomicTaggedOptionalRawPointer
{
public init(_ p: (pointer: UnsafeRawPointer?, tag: Int))
{
self.init(TaggedOptionalRawPointer(p.pointer, tag: p.tag))
}
#if swift(>=4.2)
public var value: (pointer: UnsafeRawPointer?, tag: Int) {
@inlinable
mutating get {
let t = CAtomicsLoad(&self, .acquire)
return (t.ptr, t.tag)
}
}
@inlinable
public mutating func initialize(_ p: (pointer: UnsafeRawPointer?, tag: Int))
{
CAtomicsInitialize(&self, TaggedOptionalRawPointer(p.pointer, tag: p.tag))
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> (pointer: UnsafeRawPointer?, tag: Int)
{
let t = CAtomicsLoad(&self, order)
return (t.ptr, t.tag)
}
@inlinable
public mutating func store(_ p: (pointer: UnsafeRawPointer?, tag: Int), order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, TaggedOptionalRawPointer(p.pointer, tag: p.tag), order)
}
@inlinable
public mutating func swap(_ p: (pointer: UnsafeRawPointer?, tag: Int), order: MemoryOrder = .acqrel) -> (pointer: UnsafeRawPointer?, tag: Int)
{
let t = CAtomicsExchange(&self, TaggedOptionalRawPointer(p.pointer, tag: p.tag), order)
return (t.ptr, t.tag)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout (pointer: UnsafeRawPointer?, tag: Int),
future: (pointer: UnsafeRawPointer?, tag: Int),
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = TaggedOptionalRawPointer(current.0, tag: current.1)
let f = TaggedOptionalRawPointer(future.0, tag: future.1)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&self, &c, f, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, &c, f, orderSwap, orderLoad)
current = (c.ptr, c.tag)
return s
}
@inlinable @discardableResult
public mutating func CAS(current: (pointer: UnsafeRawPointer?, tag: Int),
future: (pointer: UnsafeRawPointer?, tag: Int),
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var value: (pointer: UnsafeRawPointer?, tag: Int) {
@inline(__always)
mutating get {
let t = CAtomicsLoad(&self, .acquire)
return (t.ptr, t.tag)
}
}
@inline(__always)
public mutating func initialize(_ p: (pointer: UnsafeRawPointer?, tag: Int))
{
CAtomicsInitialize(&self, TaggedOptionalRawPointer(p.pointer, tag: p.tag))
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> (pointer: UnsafeRawPointer?, tag: Int)
{
let t = CAtomicsLoad(&self, order)
return (t.ptr, t.tag)
}
@inline(__always)
public mutating func store(_ p: (pointer: UnsafeRawPointer?, tag: Int), order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, TaggedOptionalRawPointer(p.pointer, tag: p.tag), order)
}
@inline(__always)
public mutating func swap(_ p: (pointer: UnsafeRawPointer?, tag: Int), order: MemoryOrder = .acqrel) -> (pointer: UnsafeRawPointer?, tag: Int)
{
let t = CAtomicsExchange(&self, TaggedOptionalRawPointer(p.pointer, tag: p.tag), order)
return (t.ptr, t.tag)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout (pointer: UnsafeRawPointer?, tag: Int),
future: (pointer: UnsafeRawPointer?, tag: Int),
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = TaggedOptionalRawPointer(current.0, tag: current.1)
let f = TaggedOptionalRawPointer(future.0, tag: future.1)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&self, &c, f, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, &c, f, orderSwap, orderLoad)
current = (c.ptr, c.tag)
return s
}
@inline(__always) @discardableResult
public mutating func CAS(current: (pointer: UnsafeRawPointer?, tag: Int),
future: (pointer: UnsafeRawPointer?, tag: Int),
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicTaggedMutableRawPointer
extension AtomicTaggedMutableRawPointer
{
public init(_ p: (pointer: UnsafeMutableRawPointer, tag: Int))
{
self.init(TaggedMutableRawPointer(p.pointer, tag: p.tag))
}
#if swift(>=4.2)
public var value: (pointer: UnsafeMutableRawPointer, tag: Int) {
@inlinable
mutating get {
let t = CAtomicsLoad(&self, .acquire)
return (t.ptr, t.tag)
}
}
@inlinable
public mutating func initialize(_ p: (pointer: UnsafeMutableRawPointer, tag: Int))
{
CAtomicsInitialize(&self, TaggedMutableRawPointer(p.pointer, tag: p.tag))
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> (pointer: UnsafeMutableRawPointer, tag: Int)
{
let t = CAtomicsLoad(&self, order)
return (t.ptr, t.tag)
}
@inlinable
public mutating func store(_ p: (pointer: UnsafeMutableRawPointer, tag: Int), order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, TaggedMutableRawPointer(p.pointer, tag: p.tag), order)
}
@inlinable
public mutating func swap(_ p: (pointer: UnsafeMutableRawPointer, tag: Int), order: MemoryOrder = .acqrel) -> (pointer: UnsafeMutableRawPointer, tag: Int)
{
let t = CAtomicsExchange(&self, TaggedMutableRawPointer(p.pointer, tag: p.tag), order)
return (t.ptr, t.tag)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout (pointer: UnsafeMutableRawPointer, tag: Int),
future: (pointer: UnsafeMutableRawPointer, tag: Int),
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = TaggedMutableRawPointer(current.0, tag: current.1)
let f = TaggedMutableRawPointer(future.0, tag: future.1)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&self, &c, f, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, &c, f, orderSwap, orderLoad)
current = (c.ptr, c.tag)
return s
}
@inlinable @discardableResult
public mutating func CAS(current: (pointer: UnsafeMutableRawPointer, tag: Int),
future: (pointer: UnsafeMutableRawPointer, tag: Int),
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var value: (pointer: UnsafeMutableRawPointer, tag: Int) {
@inline(__always)
mutating get {
let t = CAtomicsLoad(&self, .acquire)
return (t.ptr, t.tag)
}
}
@inline(__always)
public mutating func initialize(_ p: (pointer: UnsafeMutableRawPointer, tag: Int))
{
CAtomicsInitialize(&self, TaggedMutableRawPointer(p.pointer, tag: p.tag))
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> (pointer: UnsafeMutableRawPointer, tag: Int)
{
let t = CAtomicsLoad(&self, order)
return (t.ptr, t.tag)
}
@inline(__always)
public mutating func store(_ p: (pointer: UnsafeMutableRawPointer, tag: Int), order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, TaggedMutableRawPointer(p.pointer, tag: p.tag), order)
}
@inline(__always)
public mutating func swap(_ p: (pointer: UnsafeMutableRawPointer, tag: Int), order: MemoryOrder = .acqrel) -> (pointer: UnsafeMutableRawPointer, tag: Int)
{
let t = CAtomicsExchange(&self, TaggedMutableRawPointer(p.pointer, tag: p.tag), order)
return (t.ptr, t.tag)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout (pointer: UnsafeMutableRawPointer, tag: Int),
future: (pointer: UnsafeMutableRawPointer, tag: Int),
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = TaggedMutableRawPointer(current.0, tag: current.1)
let f = TaggedMutableRawPointer(future.0, tag: future.1)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&self, &c, f, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, &c, f, orderSwap, orderLoad)
current = (c.ptr, c.tag)
return s
}
@inline(__always) @discardableResult
public mutating func CAS(current: (pointer: UnsafeMutableRawPointer, tag: Int),
future: (pointer: UnsafeMutableRawPointer, tag: Int),
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@_exported import struct CAtomics.AtomicTaggedOptionalMutableRawPointer
extension AtomicTaggedOptionalMutableRawPointer
{
public init(_ p: (pointer: UnsafeMutableRawPointer?, tag: Int))
{
self.init(TaggedOptionalMutableRawPointer(p.pointer, tag: p.tag))
}
#if swift(>=4.2)
public var value: (pointer: UnsafeMutableRawPointer?, tag: Int) {
@inlinable
mutating get {
let t = CAtomicsLoad(&self, .acquire)
return (t.ptr, t.tag)
}
}
@inlinable
public mutating func initialize(_ p: (pointer: UnsafeMutableRawPointer?, tag: Int))
{
CAtomicsInitialize(&self, TaggedOptionalMutableRawPointer(p.pointer, tag: p.tag))
}
@inlinable
public mutating func load(order: LoadMemoryOrder = .acquire) -> (pointer: UnsafeMutableRawPointer?, tag: Int)
{
let t = CAtomicsLoad(&self, order)
return (t.ptr, t.tag)
}
@inlinable
public mutating func store(_ p: (pointer: UnsafeMutableRawPointer?, tag: Int), order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, TaggedOptionalMutableRawPointer(p.pointer, tag: p.tag), order)
}
@inlinable
public mutating func swap(_ p: (pointer: UnsafeMutableRawPointer?, tag: Int), order: MemoryOrder = .acqrel) -> (pointer: UnsafeMutableRawPointer?, tag: Int)
{
let t = CAtomicsExchange(&self, TaggedOptionalMutableRawPointer(p.pointer, tag: p.tag), order)
return (t.ptr, t.tag)
}
@inlinable @discardableResult
public mutating func loadCAS(current: inout (pointer: UnsafeMutableRawPointer?, tag: Int),
future: (pointer: UnsafeMutableRawPointer?, tag: Int),
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = TaggedOptionalMutableRawPointer(current.0, tag: current.1)
let f = TaggedOptionalMutableRawPointer(future.0, tag: future.1)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&self, &c, f, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, &c, f, orderSwap, orderLoad)
current = (c.ptr, c.tag)
return s
}
@inlinable @discardableResult
public mutating func CAS(current: (pointer: UnsafeMutableRawPointer?, tag: Int),
future: (pointer: UnsafeMutableRawPointer?, tag: Int),
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#else
public var value: (pointer: UnsafeMutableRawPointer?, tag: Int) {
@inline(__always)
mutating get {
let t = CAtomicsLoad(&self, .acquire)
return (t.ptr, t.tag)
}
}
@inline(__always)
public mutating func initialize(_ p: (pointer: UnsafeMutableRawPointer?, tag: Int))
{
CAtomicsInitialize(&self, TaggedOptionalMutableRawPointer(p.pointer, tag: p.tag))
}
@inline(__always)
public mutating func load(order: LoadMemoryOrder = .acquire) -> (pointer: UnsafeMutableRawPointer?, tag: Int)
{
let t = CAtomicsLoad(&self, order)
return (t.ptr, t.tag)
}
@inline(__always)
public mutating func store(_ p: (pointer: UnsafeMutableRawPointer?, tag: Int), order: StoreMemoryOrder = .release)
{
CAtomicsStore(&self, TaggedOptionalMutableRawPointer(p.pointer, tag: p.tag), order)
}
@inline(__always)
public mutating func swap(_ p: (pointer: UnsafeMutableRawPointer?, tag: Int), order: MemoryOrder = .acqrel) -> (pointer: UnsafeMutableRawPointer?, tag: Int)
{
let t = CAtomicsExchange(&self, TaggedOptionalMutableRawPointer(p.pointer, tag: p.tag), order)
return (t.ptr, t.tag)
}
@inline(__always) @discardableResult
public mutating func loadCAS(current: inout (pointer: UnsafeMutableRawPointer?, tag: Int),
future: (pointer: UnsafeMutableRawPointer?, tag: Int),
type: CASType = .strong,
orderSwap: MemoryOrder = .acqrel,
orderLoad: LoadMemoryOrder = .acquire) -> Bool
{
var c = TaggedOptionalMutableRawPointer(current.0, tag: current.1)
let f = TaggedOptionalMutableRawPointer(future.0, tag: future.1)
let s = (type == .weak)
? CAtomicsCompareAndExchangeWeak(&self, &c, f, orderSwap, orderLoad)
: CAtomicsCompareAndExchangeStrong(&self, &c, f, orderSwap, orderLoad)
current = (c.ptr, c.tag)
return s
}
@inline(__always) @discardableResult
public mutating func CAS(current: (pointer: UnsafeMutableRawPointer?, tag: Int),
future: (pointer: UnsafeMutableRawPointer?, tag: Int),
type: CASType = .strong,
order: MemoryOrder = .acqrel) -> Bool
{
var current = current
return loadCAS(current: ¤t, future: future, type: type,
orderSwap: order, orderLoad: order.asLoadOrdering())
}
#endif
}
@available(*, unavailable, renamed: "AtomicPointer")
public typealias AtomicNonNullPointer<T> = AtomicPointer<T>
@available(*, unavailable, renamed: "AtomicMutablePointer")
public typealias AtomicNonNullMutablePointer<T> = AtomicMutablePointer<T>
@available(*, unavailable, renamed: "AtomicRawPointer")
public typealias AtomicNonNullRawPointer = AtomicRawPointer
@available(*, unavailable, renamed: "AtomicMutableRawPointer")
public typealias AtomicNonNullMutableRawPointer = AtomicMutableRawPointer
@available(*, unavailable, renamed: "AtomicOpaquePointer")
public typealias AtomicNonNullOpaquePointer = AtomicOpaquePointer
| bsd-3-clause | 3700f5b0ac52e9c78eed83bba65a9bba | 33.267703 | 158 | 0.642508 | 4.462663 | false | false | false | false |
apple/swift-nio | IntegrationTests/tests_04_performance/test_01_resources/test_udp_1_reqs_1000_conn.swift | 1 | 839 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOPosix
func run(identifier: String) {
measure(identifier: identifier) {
var numberDone = 1
for _ in 0..<1000 {
let newDones = try! UDPShared.doUDPRequests(group: group, number: 1)
precondition(newDones == 1)
numberDone += newDones
}
return numberDone
}
}
| apache-2.0 | 2e68357153951c63fff525ffcabb9d18 | 30.074074 | 80 | 0.529201 | 4.794286 | false | false | false | false |
joninsky/JVUtilities | JVUtilities/Notification.swift | 1 | 2925 | //
// Notification.swift
// JVUtilities
//
// Created by Jon Vogel on 4/5/16.
// Copyright © 2016 Jon Vogel. All rights reserved.
//
import UIKit
public class Notification: NSObject, NSCoding {
public var photo: UIImage?
public var text: String?
public var expandedText: String?
public private(set)var date: NSDate!
public var subPhoto: Int?
public var seen: Bool!
public var debug: Bool!
public var screenedNotification: Bool!
public var info: [String: String]?
public override init() {
super.init()
self.date = NSDate()
self.seen = false
self.debug = false
self.screenedNotification = false
}
//MARK: Functions
public func addMainPhoto(thePhoto: UIImage) {
let scale = 52 / thePhoto.size.height
let newWidth = thePhoto.size.width * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, 52))
thePhoto.drawInRect(CGRectMake(0, 0, newWidth, 52))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.photo = newImage
}
//MARK: NSCoding Compliance
public required init?(coder aDecoder: NSCoder) {
super.init()
if let retrievedPhoto = aDecoder.decodeObjectForKey("Photo") as? UIImage {
self.photo = retrievedPhoto
}
if let retrievedText = aDecoder.decodeObjectForKey("Text") as? String {
self.text = retrievedText
}
if let retrievedExpandedText = aDecoder.decodeObjectForKey("ExpandedText") as? String {
self.expandedText = retrievedExpandedText
}
if let retrievedDate = aDecoder.decodeObjectForKey("Date") as? NSDate {
self.date = retrievedDate
}
self.subPhoto = aDecoder.decodeIntegerForKey("SubPhoto")
self.seen = aDecoder.decodeBoolForKey("seen")
self.debug = aDecoder.decodeBoolForKey("debug")
self.screenedNotification = aDecoder.decodeBoolForKey("Screened")
if let retrievedInfo = aDecoder.decodeObjectForKey("Info") as? [String:String] {
self.info = retrievedInfo
}
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.photo, forKey: "Photo")
aCoder.encodeObject(self.text, forKey: "Text")
aCoder.encodeObject(self.expandedText, forKey: "ExpandedText")
aCoder.encodeObject(self.date, forKey: "Date")
if self.subPhoto != nil {
aCoder.encodeInteger(self.subPhoto!, forKey: "SubPhoto")
}
aCoder.encodeBool(self.seen, forKey: "seen")
aCoder.encodeBool(self.debug, forKey: "debug")
aCoder.encodeBool(self.screenedNotification, forKey: "Screened")
aCoder.encodeObject(self.info, forKey: "Info")
}
}
| mit | 65c371ff2b9444fef15cc70e83f0160d | 31.488889 | 95 | 0.626881 | 4.670927 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Helpers/UITraitEnvironment+LayoutMargins.swift | 1 | 2259 | //
// 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 Foundation
import UIKit
struct HorizontalMargins {
var left: CGFloat
var right: CGFloat
init(left: CGFloat, right: CGFloat) {
self.left = left
self.right = right
}
init(userInterfaceSizeClass: UIUserInterfaceSizeClass) {
switch userInterfaceSizeClass {
case .regular:
left = 96
right = 96
default:
left = 56
right = 16
}
}
}
extension UITraitEnvironment {
var conversationHorizontalMargins: HorizontalMargins {
return conversationHorizontalMargins()
}
func conversationHorizontalMargins(windowWidth: CGFloat? = UIApplication.shared.firstKeyWindow?.frame.width) -> HorizontalMargins {
let userInterfaceSizeClass: UIUserInterfaceSizeClass
// On iPad 9.7 inch 2/3 mode, right view's width is 396pt, use the compact mode's narrower margin
if let windowWidth = windowWidth,
windowWidth <= CGFloat.SplitView.IPadMarginLimit {
userInterfaceSizeClass = .compact
} else {
userInterfaceSizeClass = .regular
}
return HorizontalMargins(userInterfaceSizeClass: userInterfaceSizeClass)
}
var directionAwareConversationLayoutMargins: HorizontalMargins {
let margins = conversationHorizontalMargins
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
return HorizontalMargins(left: margins.right, right: margins.left)
} else {
return margins
}
}
}
| gpl-3.0 | 85c40518e382423bd4aacc7a003eee77 | 30.375 | 135 | 0.682603 | 4.997788 | false | false | false | false |
insanoid/SwiftyJSONAccelerator | SwiftyJSONAcceleratorTests/StringTests.swift | 1 | 1975 | //
// StringTests.swift
// SwiftyJSONAccelerator
//
// Created by Karthik on 06/07/2016.
// Copyright © 2016 Karthikeya Udupa K M. All rights reserved.
//
import Foundation
import XCTest
/// Additional tests foe String extensions.
class StringTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testFirst() {
let str1 = "demo"
XCTAssert(str1.first == "d")
let str2 = ""
XCTAssertNil(str2.first)
}
func testCases() {
var str1 = "demo"
str1.uppercaseFirst()
XCTAssert(str1 == "Demo")
str1.uppercaseFirst()
XCTAssert(str1 == "Demo")
str1.lowercaseFirst()
XCTAssert(str1 == "demo")
str1.lowercaseFirst()
XCTAssert(str1 == "demo")
}
func testReplacement() {
var str1 = "demo_of-the%app_works-well"
str1.replaceOccurrencesOfStringsWithString(["_", "-", "%"], " ")
XCTAssert(str1 == "demo of the app works well")
}
func testPrefix() {
var str1 = "Demo"
str1.appendPrefix("AC")
XCTAssert(str1 == "ACDemo")
str1.appendPrefix("")
XCTAssert(str1 == "ACDemo")
str1.appendPrefix(nil)
XCTAssert(str1 == "ACDemo")
}
func testTrimChars() {
var str1 = " De mo "
str1.trim()
XCTAssert(str1 == "De mo")
}
func testCharAtIndex() {
let str1 = "0123456789\n1234567890"
XCTAssert(str1.characterRowAndLineAt(position: 1).character == "0")
XCTAssert(str1.characterRowAndLineAt(position: 12).character == "1")
XCTAssert(str1.characterRowAndLineAt(position: 12).line == 2)
XCTAssert(str1.characterRowAndLineAt(position: 12).column == 1)
XCTAssert("".characterRowAndLineAt(position: 12).character.isEmpty)
XCTAssert(str1.characterRowAndLineAt(position: 11).character == "\n")
}
}
| mit | ef436494e5d829ddb204b006d48c9a39 | 26.041096 | 77 | 0.591185 | 3.893491 | false | true | false | false |
osianSmith/Swift-to-HTML | CommandLineWebsiteMaker/UserInterface.swift | 1 | 1172 | //
// UserInterface.swift
// CommandLineWebsiteMaker
//
// Created by Osian on 28/12/2016.
// Copyright © 2016 Osian Smith. All rights reserved.
//
import Foundation
class UserInterface {
var this = WebSiteCreator() //kill me again if your getting confused with this and other C based langauges 😜
init(){
}
//this code will step through the proccess with you
func run() {
print("what would you want to display as the webpage - this will be in the tab bar")
var input : String = readLine()!
this.setTitle(title: input)
print("So what will you want the title to be? - This will be in big for everyone to see")
input = readLine()!
this.setPageTitle(pageTitle: input)
print("And the website stuff! Use newline !NewDiv! to create a new box and newline !Exit! to end")
let website = readMain()
print(website)//temp code
}
/**
Reads the data in from command and then returns a script
**/
func readMain() -> String{
var input : String
var data = ""
var finished = false
repeat {
input = readLine()!
if(input == "finish") {
finished = true
}
data = data + input
} while (finished)
return data
}
}
| gpl-3.0 | b5c0aff6cf135618d40ded7c301762e7 | 22.836735 | 109 | 0.669521 | 3.455621 | false | false | false | false |
MAARK/Charts | ChartsDemo-iOS/Swift/Demos/HalfPieChartViewController.swift | 2 | 4748 | //
// HalfPieChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class HalfPieChartViewController: DemoBaseViewController {
@IBOutlet var chartView: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Half Pie Chart"
self.options = [.toggleValues,
.toggleXValues,
.togglePercent,
.toggleHole,
.animateX,
.animateY,
.animateXY,
.spin,
.drawCenter,
.saveToGallery,
.toggleData]
self.setup(pieChartView: chartView)
chartView.delegate = self
chartView.holeColor = .white
chartView.transparentCircleColor = NSUIColor.white.withAlphaComponent(0.43)
chartView.holeRadiusPercent = 0.58
chartView.rotationEnabled = false
chartView.highlightPerTapEnabled = true
chartView.maxAngle = 180 // Half chart
chartView.rotationAngle = 180 // Rotate to make the half on the upper side
chartView.centerTextOffset = CGPoint(x: 0, y: -20)
let l = chartView.legend
l.horizontalAlignment = .center
l.verticalAlignment = .top
l.orientation = .horizontal
l.drawInside = false
l.xEntrySpace = 7
l.yEntrySpace = 0
l.yOffset = 0
// chartView.legend = l
// entry label styling
chartView.entryLabelColor = .white
chartView.entryLabelFont = UIFont(name:"HelveticaNeue-Light", size:12)!
self.updateChartData()
chartView.animate(xAxisDuration: 1.4, easingOption: .easeOutBack)
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setDataCount(4, range: 100)
}
func setDataCount(_ count: Int, range: UInt32) {
let entries = (0..<count).map { (i) -> PieChartDataEntry in
// IMPORTANT: In a PieChart, no values (Entry) should have the same xIndex (even if from different DataSets), since no values can be drawn above each other.
return PieChartDataEntry(value: Double(arc4random_uniform(range) + range / 5),
label: parties[i % parties.count])
}
let set = PieChartDataSet(entries: entries, label: "Election Results")
set.sliceSpace = 3
set.selectionShift = 5
set.colors = ChartColorTemplates.material()
let data = PieChartData(dataSet: set)
let pFormatter = NumberFormatter()
pFormatter.numberStyle = .percent
pFormatter.maximumFractionDigits = 1
pFormatter.multiplier = 1
pFormatter.percentSymbol = " %"
data.setValueFormatter(DefaultValueFormatter(formatter: pFormatter))
data.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 11)!)
data.setValueTextColor(.white)
chartView.data = data
chartView.setNeedsDisplay()
}
override func optionTapped(_ option: Option) {
switch option {
case .toggleXValues:
chartView.drawEntryLabelsEnabled = !chartView.drawEntryLabelsEnabled
chartView.setNeedsDisplay()
case .togglePercent:
chartView.usePercentValuesEnabled = !chartView.usePercentValuesEnabled
chartView.setNeedsDisplay()
case .toggleHole:
chartView.drawHoleEnabled = !chartView.drawHoleEnabled
chartView.setNeedsDisplay()
case .drawCenter:
chartView.drawCenterTextEnabled = !chartView.drawCenterTextEnabled
chartView.setNeedsDisplay()
case .animateX:
chartView.animate(xAxisDuration: 1.4)
case .animateY:
chartView.animate(yAxisDuration: 1.4)
case .animateXY:
chartView.animate(xAxisDuration: 1.4, yAxisDuration: 1.4)
case .spin:
chartView.spin(duration: 2,
fromAngle: chartView.rotationAngle,
toAngle: chartView.rotationAngle + 360,
easingOption: .easeInCubic)
default:
handleOption(option, forChartView: chartView)
}
}
}
| apache-2.0 | 206b90900e5ce537eea15fdf868aa4d2 | 32.429577 | 168 | 0.570466 | 5.532634 | false | false | false | false |
KrishMunot/swift | benchmark/single-source/Histogram.swift | 6 | 5170 | //===--- Histogram.swift --------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This test measures performance of histogram generating.
// <rdar://problem/17384894>
import TestsUtils
typealias rrggbb_t = UInt32
func output_sorted_sparse_rgb_histogram<S: Sequence where S.Iterator.Element == rrggbb_t>(_ samples: S, _ N: Int) {
var histogram = Dictionary<rrggbb_t, Int>()
for _ in 1...50*N {
for sample in samples { // This part is really awful, I agree
let i = histogram.index(forKey: sample)
histogram[sample] = (i != nil ? histogram[i!].1 : 0) + 1
}
}
}
// Packed-RGB test data: four gray samples, two red, two blue, and a 4 pixel gradient from black to white
let samples: [rrggbb_t] = [
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,
0x00808080, 0x00808080, 0x00808080, 0x00808080,
0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,
0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF
]
@inline(never)
public func run_Histogram(_ N: Int) {
output_sorted_sparse_rgb_histogram(samples, N);
}
| apache-2.0 | 277702f56dbcbf7c110674f1605b6d82 | 44.350877 | 115 | 0.755319 | 2.594079 | false | false | false | false |
StachkaConf/ios-app | StachkaIOS/StachkaIOS/Classes/User Stories/Talks/Feed/ViewModel/CellViewModelFactory/PresentationCellViewModelFactoryImplementation.swift | 1 | 2485 | //
// PresentationCellViewModelFactoryImplementation.swift
// StachkaIOS
//
// Created by m.rakhmanov on 08.04.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import Foundation
class PresentationCellViewModelFactoryImplementation: PresentationCellViewModelFactory {
enum Constants {
static let barrierDate = Date(timeIntervalSince1970: 1492142400)
}
let dateFormatter: DateFormatter
init(dateFormatter: DateFormatter) {
self.dateFormatter = dateFormatter
}
func sections(from presentations: [Presentation]) -> [PresentationSectionModel] {
guard presentations.count > 0 else { return [] }
let sortedPresentations = presentations
.sorted {
($0.actualStartDate as Date) < ($1.actualStartDate as Date)
}
.filter {
$0.actualStartDate as Date >= Constants.barrierDate
}
var sectionModels: [PresentationSectionModel] = []
var currentDate = sortedPresentations[0].actualStartDate
var currentModel = PresentationSectionModel(timeString: dateFormatter.string(from: currentDate as Date),
items: [])
for presentation in sortedPresentations {
let viewModel = presentationViewModel(from: presentation)
if currentDate == presentation.actualStartDate {
currentModel.items.append(viewModel)
} else {
sectionModels.append(currentModel)
currentDate = presentation.actualStartDate
currentModel = PresentationSectionModel(timeString: dateFormatter.string(from: currentDate as Date),
items: [viewModel])
}
}
sectionModels.append(currentModel)
return sectionModels
}
private func presentationViewModel(from presentation: Presentation) -> PresentationCellViewModel {
return PresentationCellViewModel(associatedCell: PresentationCell.self,
title: presentation.presentationName,
authorImageUrl: presentation.author?.imageUrlString ?? "",
category: presentation.category,
place: presentation.place,
presentationKey: presentation.compoundKey)
}
}
| mit | c04f96d7f7b39dd9fea031fb473fe5ef | 38.428571 | 116 | 0.602254 | 6.179104 | false | false | false | false |
fitomad/iOS-Bubble-Transition | BubbleTransition.swift | 1 | 5265 | //
// BubbleTransition.swift
// desappstre framework
//
// Created by Adolfo Vera Blasco on 14/03/16.
// Copyright (c) 2016 Adolfo Vera Blasco. All rights reserved.
//
import UIKit
import Foundation
@objc public class BubbleTransition: NSObject
{
/// Point in which we situate the bubble.
/// By default Upper Left corner
public var startingPoint: CGPoint
/// The transition direction.
public var transitionMode: TransitionMode
/// The color of the bubble.
/// Non defined? We use the presented controller background color
public var bubbleColor: UIColor?
/// The bubble
private var bubble: UIView!
/// Transition duration
private var presentingDuration: Double
/// Dismiss duration
private var dismissDuration: Double
/**
Initializer
*/
public override init()
{
self.presentingDuration = 0.5
self.dismissDuration = 0.35
self.startingPoint = CGPointMake(0.0, 0.0)
self.transitionMode = TransitionMode.Present
}
//
// MARK: - Private Methods
//
/**
Calculate the circle needed to cover the screen completly
- Parameters:
- originalSize: Size that must be covered
- start: Where the bubble starts to growth
*/
private func frameForBubbleWithSize(originalSize: CGSize, start: CGPoint) -> CGRect
{
let lengthX = fmax(start.x, originalSize.width - start.x);
let lengthY = fmax(start.y, originalSize.height - start.y)
let offset = sqrt(lengthX * lengthX + lengthY * lengthY) * 2;
return CGRectMake(0, 0, offset, offset)
}
}
//
// MARK: - UIViewControllerAnimatedTransitioning Protocol
//
extension BubbleTransition: UIViewControllerAnimatedTransitioning
{
/**
Transition duration
*/
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval
{
return self.transitionMode == .Present ? self.presentingDuration : self.dismissDuration
}
/**
Where the magic happends :)
*/
public func animateTransition(transitionContext: UIViewControllerContextTransitioning)
{
guard let
containerView = transitionContext.containerView(),
toView = transitionContext.viewForKey(UITransitionContextToViewKey),
fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
else
{
return
}
if transitionMode == TransitionMode.Present
{
let originalCenter = toView.center
let originalSize = toView.frame.size
let frame: CGRect = self.frameForBubbleWithSize(originalSize, start: self.startingPoint)
self.bubble = UIView(frame: frame)
self.bubble.layer.cornerRadius = CGRectGetHeight(self.bubble.frame) / 2
self.bubble.center = self.startingPoint
self.bubble.transform = CGAffineTransformMakeScale(0.001, 0.001)
if let bubbleColor = self.bubbleColor
{
self.bubble.backgroundColor = bubbleColor
}
else
{
self.bubble.backgroundColor = toView.backgroundColor
}
toView.center = startingPoint
toView.transform = CGAffineTransformMakeScale(0.001, 0.001)
toView.alpha = 0
containerView.addSubview(toView)
containerView.addSubview(self.bubble)
UIView.animateWithDuration(self.presentingDuration,
animations:
{
self.bubble.transform = CGAffineTransformIdentity
toView.transform = CGAffineTransformIdentity
toView.alpha = 1
toView.center = originalCenter
},
completion: { (finished: Bool) -> (Void) in
if finished
{
self.bubble.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
)
}
else
{
let originalSize = fromView.frame.size
self.bubble.frame = self.frameForBubbleWithSize(originalSize, start: startingPoint)
self.bubble.layer.cornerRadius = CGRectGetHeight(self.bubble.frame) / 2
self.bubble.center = self.startingPoint
containerView.addSubview(toView)
containerView.addSubview(self.bubble)
UIView.animateWithDuration(self.dismissDuration,
animations:
{
self.bubble.transform = CGAffineTransformMakeScale(0.001, 0.001)
},
completion: { (finished: Bool) -> (Void) in
if finished
{
toView.removeFromSuperview()
self.bubble.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
)
}
}
}
| mit | 873e4567379738a1386360bcea1e7ff2 | 30.153846 | 111 | 0.578158 | 5.655209 | false | false | false | false |
karstengresch/rw_studies | Apprentice/Checklists10/Checklists10/Checklists10/AllLists10ViewController.swift | 1 | 5851 | //
// AllLists10ViewController.swift
// Checklists10
//
// Created by Karsten Gresch on 10.03.17.
// Copyright © 2017 Closure One. All rights reserved.
//
import UIKit
class AllLists10ViewController: UITableViewController, ListDetailViewControllerDelegate, UINavigationControllerDelegate {
var dataModel10: DataModel10!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
navigationController?.delegate = self
let index = dataModel10.indexOfSelectedChecklist10
if index >= 0 && index < dataModel10.checklist10s.count {
let checklist10 = dataModel10.checklist10s[index]
performSegue(withIdentifier: "ShowChecklist10", sender: checklist10)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
dataModel10.saveChecklist10s()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataModel10.checklist10s.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = makeCell(for: tableView)
let checklist10 = dataModel10.checklist10s[indexPath.row]
if let textLabel = cell.textLabel {
textLabel.text = checklist10.name
}
cell.accessoryType = .detailDisclosureButton
// cell.showsReorderControl = true
cell.detailTextLabel!.text = getDetailTextLabelByUncheckedItems(checklist10)
cell.imageView!.image = UIImage(named: checklist10.iconName)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
dataModel10.checklist10s.remove(at: indexPath.row)
let indexPaths = [indexPath]
tableView.deleteRows(at: indexPaths, with: .automatic)
}
func makeCell(for tableView: UITableView) -> UITableViewCell {
let cellIdentifier = "Cell10"
if let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) {
return cell
} else
{
return UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dataModel10.indexOfSelectedChecklist10 = indexPath.row
let checklist10 = dataModel10.checklist10s[indexPath.row]
performSegue(withIdentifier: "ShowChecklist10", sender: checklist10)
}
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let navigationController = storyboard!.instantiateViewController(withIdentifier: "ListDetailViewController") as! UINavigationController
let controller = navigationController.topViewController as! ListDetailViewController
controller.delegate = self
let checklist10 = dataModel10.checklist10s[indexPath.row]
controller.checklist10ToEdit = checklist10
present(navigationController, animated: true, completion: nil)
}
// MARK: Segue related
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowChecklist10" {
let checklist10ViewController = segue.destination as! Checklist10ViewController
checklist10ViewController.checklist10 = (sender as! Checklist10)
} else if segue.identifier == "AddChecklist10" {
let navigationController = segue.destination as! UINavigationController
let controller = navigationController.topViewController as! ListDetailViewController
controller.delegate = self
controller.checklist10ToEdit = nil
}
}
// MARK: ListDetailViewControllerDelegate methods
func listDetailViewControllerDidCancel(_ controller: ListDetailViewController) {
dismiss(animated: true, completion: nil)
}
func listDetailViewController(_ controller: ListDetailViewController, didFinishAdding checklist10: Checklist10) {
// let newRowIndex = dataModel10.checklist10s.count
dataModel10.checklist10s.append(checklist10)
dataModel10.sortChecklist10s()
tableView.reloadData()
// let indexPath = IndexPath(row: newRowIndex, section: 0)
// let indexPaths = [indexPath]
// tableView.insertRows(at: indexPaths, with: .automatic)
dismiss(animated: true, completion: nil)
}
func listDetailViewController(_ controller: ListDetailViewController, didFinishEditing checklist10: Checklist10) {
dataModel10.sortChecklist10s()
tableView.reloadData()
// if let index = dataModel10.checklist10s.index(of: checklist10) {
// let indexPath = IndexPath(row: index, section: 0)
// if let cell = tableView.cellForRow(at: indexPath) {
// cell.textLabel!.text = checklist10.name
// }
// }
dismiss(animated: true, completion: nil)
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController === self {
dataModel10.indexOfSelectedChecklist10 = -1
}
}
func getDetailTextLabelByUncheckedItems(_ checklist10: Checklist10) -> String {
var detailTextLabelText = ""
let count = checklist10.countUncheckedChecklist10Items()
if checklist10.checklist10Items.count == 0 {
detailTextLabelText = "(List empty)"
}
else if count == 0 {
detailTextLabelText = "All done!"
} else {
detailTextLabelText = "\(checklist10.countUncheckedChecklist10Items()) remaining"
}
return detailTextLabelText
}
}
| unlicense | 7d39d177990ff52024a50b5d5e1be8fe | 33.821429 | 139 | 0.731111 | 5.073721 | false | false | false | false |
moritzsternemann/SwipyCell | Example/SwipyCellExample/SwipyCellViewController.swift | 1 | 10120 | //
// ViewController.swift
// SwipyCellExample
//
// Created by Moritz Sternemann on 15.03.16.
// Copyright © 2016 Moritz Sternemann. All rights reserved.
//
import UIKit
import SwipyCell
class SwipyCellViewController: UITableViewController, SwipyCellDelegate {
let initialNumberItems = 7
var numberItems: Int = 0
var cellToDelete: SwipyCell? = nil
override func viewDidLoad() {
super.viewDidLoad()
numberItems = self.initialNumberItems
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(SwipyCellViewController.reload))
let backgroundView = UIView(frame: tableView.frame)
backgroundView.backgroundColor = UIColor.white
tableView.backgroundView = backgroundView
tableView.tableFooterView = UIView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table View Data Source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberItems
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SwipyCell
cell.selectionStyle = .gray
cell.contentView.backgroundColor = UIColor.white
configureCell(cell, forRowAtIndexPath: indexPath)
return cell
}
func configureCell(_ cell: SwipyCell, forRowAtIndexPath indexPath: IndexPath) {
let checkView = viewWithImageName("check")
let greenColor = UIColor(red: 85.0 / 255.0, green: 213.0 / 255.0, blue: 80.0 / 255.0, alpha: 1.0)
let crossView = viewWithImageName("cross")
let redColor = UIColor(red: 232.0 / 255.0, green: 61.0 / 255.0, blue: 14.0 / 255.0, alpha: 1.0)
let clockView = viewWithImageName("clock")
let yellowColor = UIColor(red: 254.0 / 255.0, green: 217.0 / 255.0, blue: 56.0 / 255.0, alpha: 1.0)
let listView = viewWithImageName("list")
let brownColor = UIColor(red: 206.0 / 255.0, green: 149.0 / 255.0, blue: 98.0 / 255.0, alpha: 1.0)
cell.defaultColor = tableView.backgroundView?.backgroundColor
cell.delegate = self
if indexPath.row % initialNumberItems == 0 {
cell.textLabel?.text = "Switch Mode Cell"
cell.detailTextLabel?.text = "Swipe to switch"
cell.addSwipeTrigger(forState: .state(0, .left), withMode: .toggle, swipeView: checkView, swipeColor: greenColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Checkmark\" cell")
})
cell.addSwipeTrigger(forState: .state(1, .left), withMode: .toggle, swipeView: crossView, swipeColor: redColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Cross\" cell")
})
cell.addSwipeTrigger(forState: .state(0, .right), withMode: .toggle, swipeView: clockView, swipeColor: yellowColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Clock\" cell")
})
cell.addSwipeTrigger(forState: .state(1, .right), withMode: .toggle, swipeView: listView, swipeColor: brownColor, completion: { cell, trigger, state, mode in
print("Did swipe \"List\" cell")
})
} else if indexPath.row % initialNumberItems == 1 {
cell.textLabel?.text = "Exit Mode Cell"
cell.detailTextLabel?.text = "Swipe to delete"
cell.addSwipeTrigger(forState: .state(0, .left), withMode: .exit, swipeView: crossView, swipeColor: redColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Cross\" cell")
self.deleteCell(cell)
})
} else if indexPath.row % initialNumberItems == 2 {
cell.textLabel?.text = "Mixed Mode Cell"
cell.detailTextLabel?.text = "Swipe to switch or delete"
cell.addSwipeTrigger(forState: .state(0, .left), withMode: .toggle, swipeView: checkView, swipeColor: greenColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Checkmark\" cell")
})
cell.addSwipeTrigger(forState: .state(1, .left), withMode: .exit, swipeView: crossView, swipeColor: redColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Cross\" cell")
self.deleteCell(cell)
})
} else if indexPath.row % initialNumberItems == 3 {
cell.textLabel?.text = "Un-animated Icons"
cell.detailTextLabel?.text = "Swipe"
cell.shouldAnimateSwipeViews = false
cell.addSwipeTrigger(forState: .state(0, .left), withMode: .toggle, swipeView: checkView, swipeColor: greenColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Checkmark\" cell")
})
cell.addSwipeTrigger(forState: .state(1, .left), withMode: .exit, swipeView: crossView, swipeColor: redColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Cross\" cell")
self.deleteCell(cell)
})
} else if indexPath.row % initialNumberItems == 4 {
cell.textLabel?.text = "Right swipe only"
cell.detailTextLabel?.text = "Swipe"
cell.addSwipeTrigger(forState: .state(0, .right), withMode: .toggle, swipeView: clockView, swipeColor: yellowColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Clock\" cell")
})
cell.addSwipeTrigger(forState: .state(1, .right), withMode: .toggle, swipeView: listView, swipeColor: brownColor, completion: { cell, trigger, state, mode in
print("Did swipe \"List\" cell")
})
} else if indexPath.row % initialNumberItems == 5 {
cell.textLabel?.text = "Small triggers"
cell.detailTextLabel?.text = "Using 10% and 50%"
cell.setTriggerPoints(points: [0.1, 0.5])
cell.addSwipeTrigger(forState: .state(0, .left), withMode: .toggle, swipeView: checkView, swipeColor: greenColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Checkmark\" cell")
})
cell.addSwipeTrigger(forState: .state(1, .left), withMode: .exit, swipeView: crossView, swipeColor: redColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Cross\" cell")
self.deleteCell(cell)
})
} else if indexPath.row % initialNumberItems == 6 {
cell.textLabel?.text = "Exit Mode Cell + Confirmation"
cell.detailTextLabel?.text = "Swipe to delete"
cell.addSwipeTrigger(forState: .state(0, .left), withMode: .exit, swipeView: crossView, swipeColor: redColor, completion: { cell, trigger, state, mode in
print("Did swipe \"Cross\" cell")
self.cellToDelete = cell
let alertController = UIAlertController(title: "Delete?", message: "Are you sure you want to delete the cell?", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in
cell.swipeToOrigin {
print("Swiped back")
}
})
alertController.addAction(cancelAction)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: { (action) in
self.numberItems -= 1
self.tableView.deleteRows(at: [self.tableView.indexPath(for: cell)!], with: .fade)
})
alertController.addAction(deleteAction)
self.present(alertController, animated: true, completion: {})
})
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70.0
}
// MARK: - SwipyCell Delegate
// When the user starts swiping the cell this method is called
func swipyCellDidStartSwiping(_ cell: SwipyCell) {
}
// When the user ends swiping the cell this method is called
func swipyCellDidFinishSwiping(_ cell: SwipyCell, atState state: SwipyCellState, triggerActivated activated: Bool) {
print("swipe finished - activated: \(activated), state: \(state)")
}
// When the user is dragging, this method is called with the percentage from the border
func swipyCell(_ cell: SwipyCell, didSwipeWithPercentage percentage: CGFloat, currentState state: SwipyCellState, triggerActivated activated: Bool) {
print("swipe - percentage: \(percentage), activated: \(activated), state: \(state)")
}
// MARK: - Utils
@objc func reload() {
numberItems = self.initialNumberItems
tableView.reloadSections(IndexSet(integer: 0), with: .fade)
}
func deleteCell(_ cell: SwipyCell) {
numberItems -= 1
let indexPath = tableView.indexPath(for: cell)
tableView.deleteRows(at: [indexPath!], with: .fade)
}
func viewWithImageName(_ imageName: String) -> UIView {
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image)
imageView.contentMode = .center
return imageView
}
}
| mit | 2c5d05d30fcafe3511b63156b35cf134 | 44.78733 | 171 | 0.596699 | 4.704324 | false | false | false | false |
justindarc/firefox-ios | XCUITests/IntegrationTests.swift | 1 | 6458 | /* 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 XCTest
private let testingURL = "example.com"
private let userName = "iosmztest"
private let userPassword = "test15mz"
private let historyItemSavedOnDesktop = "http://www.example.com/"
private let loginEntry = "https://accounts.google.com"
private let tabOpenInDesktop = "http://example.com/"
class IntegrationTests: BaseTestCase {
let testWithDB = ["testFxASyncHistory", "testFxASyncBookmark"]
// This DB contains 1 entry example.com
let historyDB = "exampleURLHistoryBookmark.db"
override func setUp() {
// Test name looks like: "[Class testFunc]", parse out the function name
let parts = name.replacingOccurrences(of: "]", with: "").split(separator: " ")
let key = String(parts[1])
if testWithDB.contains(key) {
// for the current test name, add the db fixture used
launchArguments = [LaunchArguments.SkipIntro, LaunchArguments.StageServer, LaunchArguments.SkipWhatsNew, LaunchArguments.LoadDatabasePrefix + historyDB]
}
super.setUp()
}
func allowNotifications () {
addUIInterruptionMonitor(withDescription: "notifications") { (alert) -> Bool in
alert.buttons["Allow"].tap()
return true
}
app.swipeDown()
}
private func signInFxAccounts() {
navigator.goto(FxASigninScreen)
waitForExistence(app.navigationBars["Client.FxAContentView"], timeout: 10)
userState.fxaUsername = ProcessInfo.processInfo.environment["FXA_EMAIL"]!
userState.fxaPassword = ProcessInfo.processInfo.environment["FXA_PASSWORD"]!
navigator.performAction(Action.FxATypeEmail)
navigator.performAction(Action.FxATapOnContinueButton)
navigator.performAction(Action.FxATypePassword)
navigator.performAction(Action.FxATapOnSignInButton)
sleep(3)
allowNotifications()
}
private func waitForInitialSyncComplete() {
navigator.nowAt(BrowserTab)
navigator.goto(SettingsScreen)
waitForExistence(app.tables.staticTexts["Sync Now"], timeout: 15)
}
func testFxASyncHistory () {
// History is generated using the DB so go directly to Sign in
// Sign into Firefox Accounts
navigator.goto(BrowserTabMenu)
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
}
func testFxASyncBookmark () {
// Bookmark is added by the DB
// Sign into Firefox Accounts
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
}
func testFxASyncBookmarkDesktop () {
// Sign into Firefox Accounts
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
navigator.goto(LibraryPanel_Bookmarks)
waitForExistence(app.tables["Bookmarks List"].cells.staticTexts["Example Domain"])
}
func testFxASyncTabs () {
navigator.openURL(testingURL)
waitUntilPageLoad()
navigator.goto(BrowserTabMenu)
signInFxAccounts()
// Wait for initial sync to complete
navigator.nowAt(BrowserTab)
// This is only to check that the device's name changed
navigator.goto(SettingsScreen)
app.tables.cells.element(boundBy: 0).tap()
waitForExistence(app.cells["DeviceNameSetting"].textFields["DeviceNameSettingTextField"])
XCTAssertEqual(app.cells["DeviceNameSetting"].textFields["DeviceNameSettingTextField"].value! as! String, "Fennec (synctesting) on iOS")
// Sync again just to make sure to sync after new name is shown
app.buttons["Settings"].tap()
app.tables.cells.element(boundBy: 1).tap()
waitForExistence(app.tables.staticTexts["Sync Now"], timeout: 15)
}
func testFxASyncLogins () {
navigator.openURL("gmail.com")
waitUntilPageLoad()
// Log in in order to save it
waitForExistence(app.webViews.textFields["Email or phone"])
app.webViews.textFields["Email or phone"].tap()
app.webViews.textFields["Email or phone"].typeText(userName)
app.webViews.buttons["Next"].tap()
waitForExistence(app.webViews.secureTextFields["Password"])
app.webViews.secureTextFields["Password"].tap()
app.webViews.secureTextFields["Password"].typeText(userPassword)
app.webViews.buttons["Sign in"].tap()
// Save the login
waitForExistence(app.buttons["SaveLoginPrompt.saveLoginButton"])
app.buttons["SaveLoginPrompt.saveLoginButton"].tap()
// Sign in with FxAccount
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
}
func testFxASyncHistoryDesktop () {
// Sign into Firefox Accounts
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
// Check synced History
navigator.goto(LibraryPanel_History)
waitForExistence(app.tables.cells.staticTexts[historyItemSavedOnDesktop], timeout: 5)
}
func testFxASyncPasswordDesktop () {
// Sign into Firefox Accounts
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
// Check synced Logins
navigator.nowAt(SettingsScreen)
navigator.goto(LoginsSettings)
waitForExistence(app.tables["Login List"], timeout: 5)
XCTAssertTrue(app.tables.cells.staticTexts[loginEntry].exists, "The login saved on desktop is not synced")
}
func testFxASyncTabsDesktop () {
// Sign into Firefox Accounts
signInFxAccounts()
// Wait for initial sync to complete
waitForInitialSyncComplete()
// Check synced Tabs
navigator.goto(LibraryPanel_History)
waitForExistence(app.cells["HistoryPanel.syncedDevicesCell"], timeout: 5)
app.cells["HistoryPanel.syncedDevicesCell"].tap()
// Need to swipe to get the data on the screen on focus
app.swipeDown()
waitForExistence(app.tables.otherElements["profile1"], timeout: 5)
XCTAssertTrue(app.tables.staticTexts[tabOpenInDesktop].exists, "The tab is not synced")
}
}
| mpl-2.0 | 89e2fca0c6fd5549532f0ee399291ccf | 35.902857 | 157 | 0.676525 | 4.851991 | false | true | false | false |
argent-os/argent-ios | app-ios/WebPrivacyViewController.swift | 1 | 3371 | //
// WebPrivacyViewController.swift
// argent-ios
//
// Created by Sinan Ulkuatam on 3/27/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
import UIKit
import WebKit
import CWStatusBarNotification
class WebPrivacyViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
@IBOutlet var containerView : UIView! = nil
var webView: WKWebView?
override func loadView() {
super.loadView()
self.navigationController?.navigationBar.tintColor = UIColor.darkGrayColor()
self.webView = WKWebView()
self.webView?.UIDelegate = self
self.webView?.contentMode = UIViewContentMode.ScaleToFill
self.view = self.webView!
}
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string:"https://www.argentapp.com/privacy")
let req = NSURLRequest(URL:url!)
self.webView!.loadRequest(req)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
lazy var previewActions: [UIPreviewActionItem] = {
func previewActionForTitle(title: String, style: UIPreviewActionStyle = .Default) -> UIPreviewAction {
return UIPreviewAction(title: title, style: style) { previewAction, viewController in
// guard let detailViewController = viewController as? DetailViewController,
// item = detailViewController.detailItemTitle else { return }
// print("\(previewAction.title) triggered from `DetailViewController` for item: \(item)")
if title == "Copy Link" {
showGlobalNotification("Link copied!", duration: 3.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.StatusBarNotification, color: UIColor.skyBlue())
UIPasteboard.generalPasteboard().string = "https://www.argentapp.com/privacy"
}
if title == "Share" {
let activityViewController = UIActivityViewController(
activityItems: [APP_NAME + " Privacy Policy https://www.argentapp.com/privacy" as NSString],
applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList]
self.presentViewController(activityViewController, animated: true, completion: nil)
}
}
}
let action1 = previewActionForTitle("Copy Link")
// return [action1]
let action2 = previewActionForTitle("Share")
return [action1, action2]
// let action2 = previewActionForTitle("Share", style: .Destructive)
// let subAction1 = previewActionForTitle("Sub Action 1")
// let subAction2 = previewActionForTitle("Sub Action 2")
// let groupedActions = UIPreviewActionGroup(title: "More", style: .Default, actions: [subAction1, subAction2] )
// return [action1, action2, groupedActions]
}()
override func previewActionItems() -> [UIPreviewActionItem] {
return previewActions
}
} | mit | 066e548dc64dee123513acffbff77787 | 40.109756 | 248 | 0.62819 | 5.298742 | false | false | false | false |
lfaoro/Cast | Carthage/Checkouts/RxSwift/RxSwift/Observers/AnonymousObserver.swift | 1 | 2116 | //
// AnonymousObserver.swift
// Rx
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public class AnonymousObserver<ElementType> : ObserverBase<ElementType> {
public typealias Element = ElementType
public typealias EventHandler = Event<Element> -> Void
private let eventHandler : EventHandler
public init(_ eventHandler: EventHandler) {
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
self.eventHandler = eventHandler
}
func makeSafe(disposable: Disposable) -> AnonymousSafeObserver<Element> {
return AnonymousSafeObserver(self.eventHandler, disposable: disposable)
}
public override func onCore(event: Event<Element>) {
return self.eventHandler(event)
}
#if TRACE_RESOURCES
deinit {
OSAtomicDecrement32(&resourceCount)
}
#endif
}
public class AnonymousSafeObserver<ElementType> : Observer<ElementType> {
public typealias Element = ElementType
public typealias EventHandler = Event<Element> -> Void
private let eventHandler : EventHandler
private let disposable: Disposable
var stopped: Int32 = 0
public init(_ eventHandler: EventHandler, disposable: Disposable) {
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
self.eventHandler = eventHandler
self.disposable = disposable
}
public override func on(event: Event<Element>) {
switch event {
case .Next:
if stopped == 0 {
self.eventHandler(event)
}
case .Error:
if OSAtomicCompareAndSwapInt(0, 1, &stopped) {
self.eventHandler(event)
self.disposable.dispose()
}
case .Completed:
if OSAtomicCompareAndSwapInt(0, 1, &stopped) {
self.eventHandler(event)
self.disposable.dispose()
}
}
}
#if TRACE_RESOURCES
deinit {
OSAtomicDecrement32(&resourceCount)
}
#endif
} | mit | c119b5156c7a99a30f335b5f4d1a8b87 | 24.817073 | 79 | 0.638941 | 4.955504 | false | false | false | false |
sberrevoets/dotfiles | lldbhelpers/uikit.swift | 1 | 510 | import UIKit
extension UIViewController {
static func hierarchy() {
let root = UIApplication.shared.keyWindow!.rootViewController!
print(root.hierarchy())
}
func hierarchy(indent: Int = 0) -> String {
let indentString = String(repeating: " ", count: indent)
var hierarchy = "\(indentString)\(String(describing: self))\n"
for child in self.children {
hierarchy += child.hierarchy(indent: indent + 4)
}
return hierarchy
}
}
| mit | 14e577de9f198fc4e2ef020ec2ff21a5 | 25.842105 | 70 | 0.615686 | 4.594595 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios | Source/Phone/Device/DeviceService.swift | 1 | 4854 | // Copyright 2016 Cisco Systems Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class DeviceService: CompletionHandlerType<Device> {
static let sharedInstance = DeviceService()
private var device: Device?
private let client: DeviceClient = DeviceClient()
var deviceUrl: String? {
get {
return UserDefaults.sharedInstance.deviceUrl
}
set {
UserDefaults.sharedInstance.deviceUrl = newValue
}
}
var webSocketUrl: String? {
return device?.webSocketUrl
}
func getServiceUrl(_ service: String) -> String? {
if let services = device?.services {
return services[service + "ServiceUrl"]
}
return nil
}
func registerDevice(_ completionHandler: @escaping (Bool) -> Void) {
let deviceInfo = createDeviceInfo()
if deviceUrl == nil {
client.create(deviceInfo) {
(response: ServiceResponse<Device>) in
self.onRegisterDeviceCompleted(response, completionHandler: completionHandler)
}
} else {
client.update(deviceUrl!, deviceInfo: deviceInfo) {
(response: ServiceResponse<Device>) in
self.onRegisterDeviceCompleted(response, completionHandler: completionHandler)
}
}
}
func deregisterDevice(_ completionHandler: @escaping (Bool) -> Void) {
if deviceUrl == nil {
completionHandler(true)
return
}
client.delete(deviceUrl!) {
(response: ServiceResponse<Any>) in
self.onDeregisterDeviceCompleted(response, completionHandler: completionHandler)
}
deviceUrl = nil
}
private func onRegisterDeviceCompleted(_ response: ServiceResponse<Device>, completionHandler: (Bool) -> Void) {
switch response.result {
case .success(let value):
self.device = value
self.deviceUrl = self.device?.deviceUrl
completionHandler(true)
case .failure(let error):
Logger.error("Failed to register device", error: error)
completionHandler(false)
}
}
private func onDeregisterDeviceCompleted(_ response: ServiceResponse<Any>, completionHandler: (Bool) -> Void) {
switch response.result {
case .success:
completionHandler(true)
case .failure(let error):
Logger.error("Failed to deregister device", error: error)
completionHandler(false)
}
}
private func createDeviceInfo() -> RequestParameter {
let currentDevice = UIDevice.current
let deviceName = currentDevice.name.isEmpty ? "notset" : currentDevice.name
let deviceType: String
if isPad() {
deviceType = "IPAD"
} else if isPhone() {
deviceType = "IPHONE"
} else {
deviceType = "UNKNOWN"
}
let deviceParameters:[String: Any] = [
"deviceName": deviceName,
"name": currentDevice.name,
"model": currentDevice.model,
"localizedModel": currentDevice.localizedModel,
"systemName": currentDevice.systemName,
"systemVersion": currentDevice.systemVersion,
"deviceType": deviceType,
"capabilities": ["sdpSupported":true, "groupCallSupported":true]]
return RequestParameter(deviceParameters)
}
private func isPad() -> Bool {
return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
}
private func isPhone() -> Bool {
return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone
}
}
| mit | 03d8e43a5a1eabd084ab686d61906e36 | 34.173913 | 116 | 0.633498 | 5.180363 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/StakingCell.swift | 1 | 4452 | //
// StakingCell.swift
// breadwallet
//
// Created by Adrian Corscadden on 2020-10-17.
// Copyright © 2020 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import UIKit
class StakingCell: UIView, Subscriber {
private let iconContainer = UIView(color: .transparentIconBackground)
private let icon = UIImageView()
private let currency: Currency
private let title = UILabel(font: .customBody(size: 14), color: .rewardsViewNormalTitle)
private var indicatorView = UIImageView()
private let topPadding = UIView(color: .whiteTint)
private let bottomPadding = UIView(color: .whiteTint)
private let statusFlag = UILabel(font: .customBody(size: 11))
private var wallet: Wallet?
init(currency: Currency, wallet: Wallet?) {
self.currency = currency
self.wallet = wallet
super.init(frame: .zero)
setup()
}
private func setup() {
addSubviews()
setupConstraints()
setInitialData()
}
private func addSubviews() {
addSubview(topPadding)
addSubview(bottomPadding)
addSubview(iconContainer)
iconContainer.addSubview(icon)
addSubview(title)
addSubview(indicatorView)
addSubview(statusFlag)
}
private func setupConstraints() {
let containerPadding = C.padding[2]
topPadding.constrainTopCorners(height: containerPadding)
bottomPadding.constrainBottomCorners(height: containerPadding)
iconContainer.constrain([
iconContainer.leadingAnchor.constraint(equalTo: leadingAnchor, constant: containerPadding),
iconContainer.centerYAnchor.constraint(equalTo: centerYAnchor),
iconContainer.heightAnchor.constraint(equalToConstant: 40),
iconContainer.widthAnchor.constraint(equalTo: iconContainer.heightAnchor)])
icon.constrain(toSuperviewEdges: .zero)
title.constrain([
title.leadingAnchor.constraint(equalTo: iconContainer.trailingAnchor, constant: C.padding[1]),
title.centerYAnchor.constraint(equalTo: iconContainer.centerYAnchor)
])
statusFlag.constrain([
statusFlag.centerYAnchor.constraint(equalTo: iconContainer.centerYAnchor),
statusFlag.trailingAnchor.constraint(equalTo: indicatorView.leadingAnchor, constant: -C.padding[2]),
statusFlag.heightAnchor.constraint(equalToConstant: 20) ])
indicatorView.constrain([
indicatorView.centerYAnchor.constraint(equalTo: centerYAnchor),
indicatorView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -21)])
}
private func setInitialData() {
icon.image = currency.imageNoBackground
icon.tintColor = .white
iconContainer.layer.cornerRadius = C.Sizes.homeCellCornerRadius
iconContainer.backgroundColor = currency.colors.0
title.text = S.Staking.stakingTitle
statusFlag.layer.cornerRadius = C.Sizes.homeCellCornerRadius
statusFlag.clipsToBounds = true
indicatorView.image = UIImage(named: "RightArrow")
updateStakingStatus()
wallet?.subscribe(self) { [weak self] event in
DispatchQueue.main.async {
switch event {
case .transferChanged, .transferSubmitted:
self?.updateStakingStatus()
default:
break
}
}
}
}
private func updateStakingStatus() {
if currency.wallet?.hasPendingTxn == true {
statusFlag.text = " \(S.Staking.stakingPendingFlag) "
statusFlag.backgroundColor = Theme.accent.withAlphaComponent(0.16)
statusFlag.textColor = .darkGray
} else if currency.wallet?.stakedValidatorAddress != nil {
statusFlag.text = " \(S.Staking.stakingActiveFlag) "
statusFlag.backgroundColor = Theme.success.withAlphaComponent(0.16)
statusFlag.textColor = Theme.success
} else {
statusFlag.text = " \(S.Staking.stakingInactiveFlag) "
statusFlag.backgroundColor = Theme.accent.withAlphaComponent(0.16)
statusFlag.textColor = .darkGray
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 3fd4ad334c6bbf59ba075f10d10f81f8 | 38.04386 | 112 | 0.65446 | 4.95657 | false | false | false | false |
ryet231ere/DouYuSwift | douyu/douyu/Classes/Home/View/AmuseMenuView.swift | 1 | 2471 | //
// AmuseMenuView.swift
// douyu
//
// Created by 练锦波 on 2017/3/9.
// Copyright © 2017年 练锦波. All rights reserved.
//
import UIKit
private let kMenuCleeID = "kMenuCleeID"
class AmuseMenuView: UIView {
var groups : [AnchorGroup]?{
didSet {
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "AmuseMenuCell", bundle: nil), forCellWithReuseIdentifier: kMenuCleeID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
extension AmuseMenuView {
class func amuseMenuView() -> AmuseMenuView {
return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
}
}
extension AmuseMenuView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups == nil { return 0 }
let pageNum = (groups!.count - 1) / 8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCleeID, for: indexPath) as! AmuseMenuCell
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
private func setupCellDataWithCell(cell : AmuseMenuCell, indexPath : IndexPath) {
//1.取出起始位置&终点位置
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
//2.判断越界问题
if endIndex > groups!.count - 1 {
endIndex = groups!.count - 1
}
//3.取出数据,并且赋值
cell.groups = Array(groups![startIndex...endIndex])
}
}
extension AmuseMenuView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(scrollView.contentOffset.x / scrollView.bounds.width)
}
}
| mit | e9effd68130963528cb141f008c0d84d | 26.033708 | 121 | 0.64921 | 4.991701 | false | false | false | false |
brentdax/swift | stdlib/public/SDK/Foundation/NSUndoManager.swift | 18 | 1166 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
extension UndoManager {
@available(*, unavailable, renamed: "registerUndo(withTarget:handler:)")
public func registerUndoWithTarget<TargetType : AnyObject>(_ target: TargetType, handler: (TargetType) -> Void) {
fatalError("This API has been renamed")
}
@available(macOS 10.11, iOS 9.0, *)
public func registerUndo<TargetType : AnyObject>(withTarget target: TargetType, handler: @escaping (TargetType) -> Void) {
__NSUndoManagerRegisterWithTargetHandler( self, target) { internalTarget in
handler(internalTarget as! TargetType)
}
}
}
| apache-2.0 | 5e7412784bc03a261d1cfed240948ad2 | 40.642857 | 124 | 0.638937 | 5.025862 | false | false | false | false |
alexmx/Combinations | CombinationsDemo/FormRow.swift | 1 | 1772 | //
// FormRow.swift
// Combinations
//
// Created by Alexandru Maimescu on 6/20/16.
// Copyright © 2016 Alexandru Maimescu. All rights reserved.
//
import Foundation
protocol Validatable {
func validate() throws
}
enum FormRowValidationError: Error {
case mandatoryField(fieldName: String)
case incorrectFormat(fieldName: String)
}
enum FormRowValueType: UInt {
case genericAlphanumeric
case genericNumeric
case email
case passcode
case multipleChoice
}
class FormRow {
var rowType: FormRowValueType = .genericAlphanumeric
var title: String?
var placeholder: String?
var value: String?
var maximumLength: UInt = 0
var values: [String]? {
didSet {
value = values?[selectedValueIndex]
}
}
var selectedValueIndex: Int = 0 {
didSet {
value = values?[selectedValueIndex]
}
}
var editable: Bool = true
var optional: Bool = false
var tag: UInt?
convenience init(title: String?, value: String?) {
self.init()
self.title = title
self.value = value
}
convenience init(title: String?, values: [String]) {
self.init(title: title, value: nil)
self.rowType = .multipleChoice
self.values = values
self.value = values[selectedValueIndex]
}
}
extension FormRow: Validatable {
func validate() throws {
guard optional == false else {
return
}
guard let value = value, !value.isEmpty else {
throw FormRowValidationError.mandatoryField(fieldName: title ?? "unknown")
}
}
}
| mit | ced67c0c1eaadba2738d4e36bd6d3126 | 18.677778 | 86 | 0.578204 | 4.624021 | false | false | false | false |
Brightify/Reactant | Source/Core/Styling/Extensions/CGAffineTransform+Shortcut.swift | 2 | 769 | //
// CGAffineTransform+Shortcut.swift
// Reactant
//
// Created by Filip Dolnik on 16.10.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import UIKit
public func + (lhs: CGAffineTransform, rhs: CGAffineTransform) -> CGAffineTransform {
return lhs.concatenating(rhs)
}
public func rotate(degrees: CGFloat) -> CGAffineTransform {
return rotate(degrees / 180 * .pi)
}
public func rotate(_ radians: CGFloat = 0) -> CGAffineTransform {
return CGAffineTransform(rotationAngle: radians)
}
public func translate(x: CGFloat = 0, y: CGFloat = 0) -> CGAffineTransform {
return CGAffineTransform(translationX: x, y: y)
}
public func scale(x: CGFloat = 1, y: CGFloat = 1) -> CGAffineTransform {
return CGAffineTransform(scaleX: x, y: y)
}
| mit | 78062db2dd34abf47c124673a2c43c60 | 25.482759 | 85 | 0.708333 | 3.918367 | false | false | false | false |
sonsongithub/reddift | application/FromFieldView.swift | 1 | 1804 | //
// FromFieldView.swift
// reddift
//
// Created by sonson on 2016/12/12.
// Copyright © 2016年 sonson. All rights reserved.
//
import Foundation
protocol FromFieldViewDelegate {
func didTapFromFieldView(sender: FromFieldView)
}
class FromFieldView: PostFieldView {
var delegate: FromFieldViewDelegate?
let button = UIButton(type: .custom)
override func setupSubviews() {
super.setupSubviews()
field.isEnabled = false
let views = ["button": button]
button.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(button)
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[button]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[button]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views: views))
button.addTarget(self, action: #selector(FromFieldView.didTapButton(sender:)), for: .touchUpInside)
if let name = UIApplication.appDelegate()?.session?.token?.name {
field.text = name
} else {
field.text = "anonymous"
}
NotificationCenter.default.addObserver(self, selector: #selector(FromFieldView.didUpdateToken(notification:)), name: OAuth2TokenRepositoryDidUpdateTokenName, object: nil)
}
@objc func didUpdateToken(notification: NSNotification) {
if let name = UIApplication.appDelegate()?.session?.token?.name {
field.text = name
} else {
field.text = "anonymous"
}
}
@objc func didTapButton(sender: Any) {
if let delegate = delegate {
delegate.didTapFromFieldView(sender: self)
}
}
}
| mit | 90757be41dc08a4f74ee63256fac7063 | 34.313725 | 178 | 0.659634 | 4.751979 | false | false | false | false |
lorentey/swift | test/SILOptimizer/mandatory_inlining.swift | 5 | 5708 | // RUN: %target-swift-frontend -sil-verify-all -primary-file %s -emit-sil -o - -verify | %FileCheck %s
// RUN: %target-swift-frontend -sil-verify-all -primary-file %s -emit-sil -o - -verify -enable-ownership-stripping-after-serialization
// These tests are deliberately shallow, because I do not want to depend on the
// specifics of SIL generation, which might change for reasons unrelated to this
// pass
func foo(_ x: Float) -> Float {
return bar(x);
}
// CHECK-LABEL: sil hidden @$s18mandatory_inlining3foo{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : $Float):
// CHECK-NEXT: debug_value %0 : $Float, let, name "x"
// CHECK-NEXT: return %0
@_transparent func bar(_ x: Float) -> Float {
return baz(x)
}
// CHECK-LABEL: sil hidden [transparent] @$s18mandatory_inlining3bar{{[_0-9a-zA-Z]*}}F
// CHECK-NOT: function_ref
// CHECK-NOT: apply
// CHECK: return
@_transparent func baz(_ x: Float) -> Float {
return x
}
// CHECK-LABEL: sil hidden [transparent] @$s18mandatory_inlining3baz{{[_0-9a-zA-Z]*}}F
// CHECK: return
func spam(_ x: Int) -> Int {
return x
}
// CHECK-LABEL: sil hidden @$s18mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F
@_transparent func ham(_ x: Int) -> Int {
return spam(x)
}
// CHECK-LABEL: sil hidden [transparent] @$s18mandatory_inlining3ham{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @$s18mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F
// CHECK: apply
// CHECK: return
func eggs(_ x: Int) -> Int {
return ham(x)
}
// CHECK-LABEL: sil hidden @$s18mandatory_inlining4eggs{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @$s18mandatory_inlining4spam{{[_0-9a-zA-Z]*}}F
// CHECK: apply
// CHECK: return
@_transparent func call_auto_closure(_ x: @autoclosure () -> Bool) -> Bool {
return x()
}
func test_auto_closure_with_capture(_ x: Bool) -> Bool {
return call_auto_closure(x)
}
// This should be fully inlined and simply return x; however, there's a lot of
// non-SSA cruft that I don't want this test to depend on, so I'm just going
// to verify that it doesn't have any function applications left
// CHECK-LABEL: sil hidden @{{.*}}test_auto_closure_with_capture
// CHECK-NOT: = apply
// CHECK: return
func test_auto_closure_without_capture() -> Bool {
return call_auto_closure(false)
}
// This should be fully inlined and simply return false, which is easier to check for
// CHECK-LABEL: sil hidden @$s18mandatory_inlining33test_auto_closure_without_captureSbyF
// CHECK: [[FV:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK: [[FALSE:%.*]] = struct $Bool ([[FV:%.*]] : $Builtin.Int1)
// CHECK: return [[FALSE]]
infix operator &&& : LogicalConjunctionPrecedence
infix operator ||| : LogicalDisjunctionPrecedence
@_transparent func &&& (lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool {
if lhs {
return rhs()
}
return false
}
@_transparent func ||| (lhs: Bool, rhs: @autoclosure () -> Bool) -> Bool {
if lhs {
return true
}
return rhs()
}
func test_chained_short_circuit(_ x: Bool, y: Bool, z: Bool) -> Bool {
return x &&& (y ||| z)
}
// The test below just makes sure there are no uninlined [transparent] calls
// left (i.e. the autoclosure and the short-circuiting boolean operators are
// recursively inlined properly)
// CHECK-LABEL: sil hidden @$s18mandatory_inlining26test_chained_short_circuit{{[_0-9a-zA-Z]*}}F
// CHECK-NOT: = apply [transparent]
// CHECK: return
// Union element constructors should be inlined automatically.
enum X {
case onetransp
case twotransp
}
func testInlineUnionElement() -> X {
return X.onetransp
// CHECK-LABEL: sil hidden @$s18mandatory_inlining22testInlineUnionElementAA1XOyF
// CHECK: enum $X, #X.onetransp!enumelt
// CHECK-NOT: = apply
// CHECK: return
}
@_transparent
func call_let_auto_closure(_ x: @autoclosure () -> Bool) -> Bool {
return x()
}
// CHECK-LABEL: sil hidden @{{.*}}test_let_auto_closure_with_value_capture
// CHECK: bb0(%0 : $Bool):
// CHECK-NEXT: debug_value %0 : $Bool
// CHECK-NEXT: return %0 : $Bool
// CHECK-LABEL: // end sil function '{{.*}}test_let_auto_closure_with_value_capture
func test_let_auto_closure_with_value_capture(_ x: Bool) -> Bool {
return call_let_auto_closure(x)
}
class C {}
// CHECK-LABEL: sil hidden [transparent] @$s18mandatory_inlining25class_constrained_generic{{[_0-9a-zA-Z]*}}F
@_transparent
func class_constrained_generic<T : C>(_ o: T) -> AnyClass? {
// CHECK: return
return T.self
}
// CHECK-LABEL: sil hidden @$s18mandatory_inlining6invokeyyAA1CCF : $@convention(thin) (@guaranteed C) -> () {
func invoke(_ c: C) {
// CHECK-NOT: function_ref @$s18mandatory_inlining25class_constrained_generic{{[_0-9a-zA-Z]*}}F
// CHECK-NOT: apply
// CHECK: init_existential_metatype
_ = class_constrained_generic(c)
// CHECK: return
}
// Make sure we don't crash.
@_transparent
public func mydo(_ what: @autoclosure () -> ()) {
what()
}
public class A {
public func bar() {}
public func foo(_ act: (@escaping () ->()) -> ()) {
act { [unowned self] in
mydo( self.bar() )
}
}
}
// This used to crash during mandatory inlining because noreturn folding would
// create sil instructions with undef in unreachable code.
func dontCrash() {
fatalError() // expected-note {{a call to a never-returning function}}
let k = "foo" // expected-warning {{will never be executed}}
switch k {
case "bar":
return
default:
fatalError("baz \(k)")
}
}
func switchLoopWithPartialApplyCallee(reportError: ((String) -> (Void))?) {
let reportError = reportError ?? { error in
print(error)
}
for _ in 0..<1 {
reportError("foo bar baz")
}
}
func switchLoopWithPartialApplyCaller() {
switchLoopWithPartialApplyCallee { error in
print(error)
}
}
| apache-2.0 | 450017b3f0b7ad983e3eac6304838f44 | 26.708738 | 134 | 0.665207 | 3.267315 | false | true | false | false |
kumabook/MusicFav | MusicFav/AddStreamTableViewController.swift | 1 | 4196 | //
// AddStreamTableViewController.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 8/15/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import UIKit
import ReactiveSwift
import FeedlyKit
import MusicFeeder
import MBProgressHUD
import PageMenu
class AddStreamTableViewController: UITableViewController {
let cellHeight: CGFloat = 100
let accessoryWidth: CGFloat = 30
let subscriptionRepository: SubscriptionRepository!
init(subscriptionRepository: SubscriptionRepository) {
self.subscriptionRepository = subscriptionRepository
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
subscriptionRepository = SubscriptionRepository()
super.init(nibName: nil, bundle: nil)
}
deinit {}
func getSubscribables() -> [FeedlyKit.Stream] {
return [] // should be overrided in subclass
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title:"Add".localize(),
style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(AddStreamTableViewController.add))
navigationItem.rightBarButtonItem?.isEnabled = false
tableView.allowsMultipleSelection = true
}
func reloadData(_ keepSelection: Bool) {
if keepSelection, let indexes = tableView.indexPathsForSelectedRows {
tableView.reloadData()
for index in indexes {
tableView.selectRow(at: index, animated: false, scrollPosition: UITableViewScrollPosition.none)
}
} else {
tableView.reloadData()
}
}
func isSelected(_ indexPath: IndexPath) -> Bool {
if let indexPaths = tableView.indexPathsForSelectedRows {
return indexPaths.contains(where: { $0 == indexPath})
}
return false
}
func updateAddButton() {
if let count = tableView.indexPathsForSelectedRows?.count {
navigationItem.rightBarButtonItem?.isEnabled = count > 0
} else {
navigationItem.rightBarButtonItem?.isEnabled = false
}
if let p = parent as? CAPSPageMenu, let pp = p.parent as? SearchStreamPageMenuController {
pp.updateAddButton()
}
}
func setAccessoryView(_ cell: UITableViewCell, indexPath: IndexPath) {
if isSelected(indexPath) {
var image = UIImage(named: "checkmark")
image = image!.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
let imageView = UIImageView(image: image)
imageView.frame = CGRect(x: 0, y: 0, width: accessoryWidth, height: cellHeight)
imageView.contentMode = UIViewContentMode.scaleAspectFit
imageView.tintColor = UIColor.theme
cell.accessoryView = imageView
} else {
cell.accessoryView = UIView(frame: CGRect(x: 0, y: 0, width: accessoryWidth, height: cellHeight))
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
setAccessoryView(cell, indexPath: indexPath)
}
updateAddButton()
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
setAccessoryView(cell, indexPath: indexPath)
}
updateAddButton()
}
func close() {
self.navigationController?.dismiss(animated: true, completion: nil)
}
@objc func add() {
let subscribables: [FeedlyKit.Stream] = getSubscribables()
Logger.sendUIActionEvent(self, action: "add", label: "")
let ctc = CategoryTableViewController(subscribables: subscribables, subscriptionRepository: subscriptionRepository)
navigationController?.pushViewController(ctc, animated: true)
}
}
| mit | d8c94c5189fdf6cf3663a1d6ffd7dcc4 | 36.464286 | 123 | 0.630362 | 5.407216 | false | false | false | false |
AndrewBennet/readinglist | ReadingList/ViewControllers/Lists/RemoveFromExistingLists.swift | 1 | 3409 | import Foundation
import UIKit
import CoreData
final class RemoveFromExistingLists: UITableViewController {
var book: Book!
private var resultsController: NSFetchedResultsController<List>!
override func viewDidLoad() {
super.viewDidLoad()
let fetchRequest = NSManagedObject.fetchRequest(List.self, batch: 40)
fetchRequest.predicate = NSPredicate(format: "%@ IN \(#keyPath(List.items)).\(#keyPath(ListItem.book))", book)
fetchRequest.sortDescriptors = [NSSortDescriptor(\List.sort), NSSortDescriptor(\List.name)]
resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: PersistentStoreManager.container.viewContext, sectionNameKeyPath: nil, cacheName: nil)
resultsController.delegate = self
try! resultsController.performFetch()
setEditing(true, animated: false)
}
@IBAction private func doneTapped(_ sender: Any) {
navigationController?.dismiss(animated: true)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return resultsController.sections!.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsController.sections![section].numberOfObjects
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExistingListCell", for: indexPath)
let list = resultsController.object(at: indexPath)
cell.textLabel!.text = list.name
cell.detailTextLabel!.text = "\(list.items.count) book\(list.items.count == 1 ? "" : "s")"
return cell
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return [UITableViewRowAction(style: .destructive, title: "Remove", color: .red) { _, indexPath in
let list = self.resultsController.object(at: indexPath)
list.removeBook(self.book)
list.managedObjectContext!.saveAndLogIfErrored()
UserEngagement.logEvent(.removeBookFromList)
}]
}
}
extension RemoveFromExistingLists: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.controllerDidChangeContent(controller)
if controller.sections![0].numberOfObjects == 0 {
navigationController?.popViewController(animated: true)
}
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.controllerWillChangeContent(controller)
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
tableView.controller(controller, didChange: anObject, at: indexPath, for: type, newIndexPath: newIndexPath)
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
tableView.controller(controller, didChange: sectionInfo, atSectionIndex: sectionIndex, for: type)
}
}
| gpl-3.0 | 0c1d79cba97cca6e8be6a0d8dd605b57 | 47.014085 | 209 | 0.73394 | 5.777966 | false | false | false | false |
manfengjun/KYMart | Section/Mine/Controller/KYUserInfoViewController.swift | 1 | 3180 | //
// KYUserInfoViewController.swift
// KYMart
//
// Created by Jun on 2017/6/18.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYUserInfoViewController: BaseViewController {
@IBOutlet weak var nickNameL: UITextField!
@IBOutlet weak var oldPassL: UITextField!
@IBOutlet weak var newPassL: UITextField!
var sexSelect:Int = 0
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.tabBarController?.tabBar.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// Do any additional setup after loading the view.
}
func setupUI() {
setBackButtonInNav()
if let text = SingleManager.instance.loginInfo?.nickname {
nickNameL.text = text
}
}
@IBAction func selectAction(_ sender: UITapGestureRecognizer) {
let tag = sender.view?.tag
sexSelect = tag! - 1
for i in 1..<4 {
let imageView = view.viewWithTag(i)?.viewWithTag(11) as! UIImageView
imageView.image = (i == tag ? UIImage(named: "cart_select_yes") : UIImage(named: "cart_select_no"))
}
}
@IBAction func saveInfoAction(_ sender: UIButton) {
if (nickNameL.text?.isEmpty)! {
Toast(content: "昵称不能为空")
}
let params = ["nickname":nickNameL.text!,"sex":String(sexSelect)]
sender.isUserInteractionEnabled = false
SJBRequestModel.push_fetchChangeUserInfoData(params: params as [String : AnyObject]) { (response, status) in
sender.isUserInteractionEnabled = true
if status == 1 {
SingleManager.instance.loginInfo?.nickname = self.nickNameL.text
self.Toast(content: "修改成功")
}
else
{
self.Toast(content: response as! String)
}
}
}
@IBAction func savePhoneAction(_ sender: UIButton) {
//修改密码
if (oldPassL.text?.isEmpty)! {
Toast(content: "旧密码不能为空")
}
if (newPassL.text?.isEmpty)! {
Toast(content: "新密码不能为空")
}
let params = ["old_password":oldPassL.text!,"new_password":newPassL.text!]
SJBRequestModel.push_fetchChangePasswordData(params: params as [String : AnyObject]) { (response, status) in
if status == 1{
self.Toast(content: "修改密码成功!")
}
else
{
self.Toast(content: response as! String)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 945c50b472456abed3b9770d8b9a6597 | 31.364583 | 116 | 0.594786 | 4.575847 | false | false | false | false |
JarlRyan/IOSNote | Swift/LearnSwift.playground/section-1.swift | 1 | 5844 | //
// main.swift
// LearnSwift
//
// Created by bingoogol on 14-6-5.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import Foundation
// 字符串
func demo1() {
var name = "王浩"
name = name + "bingo"
name = name + "\(100)"
var id = 50
var address:String = "重庆市"
println("id=\(id),name=\(name),address=\(address)")
}
// 类型
func demo2() {
let minIntValue = Int.min
let maxIntValue = Int.max
let minInt8Value = Int8.min
let maxInt8Value = Int8.max
let minUInt8Value = UInt8.min
let maxUInt8Value = UInt8.max
println("minIntValue=\(minIntValue),maxIntValue=\(maxIntValue)")
println("minInt8Value=\(minInt8Value),maxInt8Value=\(maxInt8Value)")
println("minUInt8Value=\(minUInt8Value),maxUInt8Value=\(maxUInt8Value)")
let value1 = 12_000_000 // 只是为了可读性
let value2 = 1_000_000.000_000_1
println("value1=\(value1),value2=\(value2)")
let value3:Float = 1.3
let value4:Double = 1.3
let value5 = 1.3
println("value3=\(value3),value4=\(value4),value5=\(value5)")
}
func add(num1:Int,num2:Int)->(Int,Int,Int) {
var result = num1 + num2
return (num1,num2,result)
}
// 多返回值
func demo3() {
let (num1,num2,result) = add(2, 3)
println("\(num1) + \(num2) = \(result)")
}
func sayHello(name:String) {
println("Hello \(name)")
}
// 函数也是一个对象,意味着可以直接当做一个变量来使用
func demo4() {
var fun = sayHello
fun("王浩")
}
// 数组
func demo5() {
var arr1 = ["Hello","World",5]
println(arr1)
println(arr1[2])
var arr2 = [] // 存放任意数据类型
var arr3 = String[]() // 只能存放特定类型
arr3.append("Hello")
arr3.append("Swift")
println(arr3)
}
// 字典
func demo6() {
var dict = ["name":"王浩","address":"重庆市"]
dict["sex"] = "男"
println(dict)
println(dict["name"])
var dict2:Dictionary<String,Int> = ["name":1,"address":2,"hehe":3,"sdfsdf":4]
if dict2.removeValueForKey("name") {
println("删除了")
} else {
println("没删除")
}
println(dict2.count)
for key in dict2.keys {
println(key)
}
for value in dict2.values {
println(value)
}
let keys = Array(dict2.keys)
println(keys)
let values = Array(dict2.values)
println(values)
}
// 循环
func demo7() {
var arr1 = String[]()
// 包含0,不包含5
for index in 0..5 {
arr1.append("Item \(index)")
}
println(arr1)
var arr2 = String[]()
// 包含0,且包含5
for index in 0...5 {
arr2.append("Item \(index)")
}
println(arr2)
for value in arr2 {
println(value)
}
for (index, value) in enumerate(arr2) {
println("enumerate index\(index),\(value)")
}
var i = 0
while i<arr2.count {
println(arr2[i])
i++
}
var dict = ["name":"王浩","address":"重庆市"]
for (key,value) in dict {
println("key=\(key),value=\(value)")
}
}
// 流程控制,可选变量
func demo8() {
for index in 0..5 {
if index%2 == 0 {
println(index)
}
}
var name:String? = "bingoogol"
//name = nil
if var name2 = name {
println(name2)
}
if name {
println(name)
}
}
class Animal {
func sayHi() {
println("Hi bingoogol")
}
func sayClassName() {
println("Animal")
}
}
class Cat : Animal {
var _name:String
init(name:String) {
self._name = name
}
override func sayClassName() {
println("Cat")
}
func sayName() {
println(self._name)
}
}
func demo9() {
var animal = Animal()
animal.sayHi()
animal.sayClassName()
var cat = Cat(name: "加菲猫")
cat.sayHi()
cat.sayClassName()
cat.sayName()
}
//(num:Int) -> Bool 闭包Closure参数类型
func hasClosureMath(arr:Int[],value:Int,cb:(num:Int,value:Int) -> Bool) ->Bool{
for item in arr {
if cb(num:item,value:value) {
return true
}
}
return false
}
//闭包
func demo10() {
var arr = [20,9,100,34,89,39]
// 找是否arr中有比110大的数字
var v1 = hasClosureMath(arr,110,{
(num:Int,value:Int) -> Bool in
return num >= value
//这里$0表示num $1表示value
//return $0 >= $1
})
println("v1 is \(v1)")
}
struct QFTest {
var x = 0;
var y = 0;
// 真正的构造函数
// 定义一个空的够着函数,构造函数是以init开头的,自动调用
init() {
println("init invoked")
}
//定义带有两个参数的构造函数
init(x:Int,y:Int) {
self.x = x
self.y = y
println("init(x:Int,y:Int) invoked")
}
// _ 这个可以让调用哪个的时候不用谢 x: y:
init(_ x:Int,_ y:Int) {
self.x = x
self.y = y
println("init(x:Int,y:Int) invoked")
}
func getCenter() -> Int {
return (x + y)/2
}
// 载调用的时候 xxx.addOffset(100,deltaY:100),不需要写deltaX
mutating func addOffset(deltaX:Int,deltaY:Int) {
// 结构体是一个拷贝的对象,默认是不能修改结构体内部的变量,加上mutating可以让函数修改结构体里面变量的值
self.x += deltaX
self.y += deltaY
}
}
func demo11() {
var s1 = QFTest(x:100,y:200)
println("x:\(s1.x) y:\(s1.y)")
var s2 = QFTest()
s2.x = 400
s2.y = 300
s2.addOffset(100,deltaY:100)
println("x:\(s1.x) y:\(s1.y) center:\(s2.getCenter())")
}
demo11()
| apache-2.0 | a57ddcb327ba0e783933c092347536f1 | 17.599303 | 81 | 0.533346 | 3.073115 | false | false | false | false |
tjw/swift | test/IRGen/witness_table_objc_associated_type.swift | 1 | 2294 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s -DINT=i%target-ptrsize
protocol A {}
protocol B {
associatedtype AA: A
func foo()
}
@objc protocol O {}
protocol C {
associatedtype OO: O
func foo()
}
struct SA: A {}
struct SB: B {
typealias AA = SA
func foo() {}
}
// CHECK-LABEL: @"$S34witness_table_objc_associated_type2SBVAA1BAAWP" = hidden constant [4 x i8*] [
// CHECK: i8* bitcast (%swift.metadata_response ([[INT]])* @"$S34witness_table_objc_associated_type2SAVMa" to i8*)
// CHECK: i8* bitcast (i8** ()* @"$S34witness_table_objc_associated_type2SAVAA1AAAWa" to i8*)
// CHECK: i8* bitcast {{.*}} @"$S34witness_table_objc_associated_type2SBVAA1BA2aDP3fooyyFTW"
// CHECK: ]
class CO: O {}
struct SO: C {
typealias OO = CO
func foo() {}
}
// CHECK-LABEL: @"$S34witness_table_objc_associated_type2SOVAA1CAAWP" = hidden constant [3 x i8*] [
// CHECK: i8* bitcast (%swift.metadata_response ([[INT]])* @"$S34witness_table_objc_associated_type2COCMa" to i8*)
// CHECK: i8* bitcast {{.*}} @"$S34witness_table_objc_associated_type2SOVAA1CA2aDP3fooyyFTW"
// CHECK: ]
// CHECK-LABEL: define hidden swiftcc void @"$S34witness_table_objc_associated_type0A25OffsetAfterAssociatedTypeyyxAA1BRzlF"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.B)
func witnessOffsetAfterAssociatedType<T: B>(_ x: T) {
// CHECK: [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.B, i32 3
// CHECK: [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]]
// CHECK: [[FOO:%.*]] = bitcast {{.*}} [[FOO_OPAQUE]]
// CHECK: call swiftcc void [[FOO]]
x.foo()
}
// CHECK-LABEL: define hidden swiftcc void @"$S34witness_table_objc_associated_type0A29OffsetAfterAssociatedTypeObjCyyxAA1CRzlF"(%swift.opaque* noalias nocapture, %swift.type* %T, i8** %T.C) {{.*}} {
func witnessOffsetAfterAssociatedTypeObjC<T: C>(_ x: T) {
// CHECK: [[FOO_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.C, i32 2
// CHECK: [[FOO_OPAQUE:%.*]] = load {{.*}} [[FOO_ADDR]]
// CHECK: [[FOO:%.*]] = bitcast {{.*}} [[FOO_OPAQUE]]
// CHECK: call swiftcc void [[FOO]]
x.foo()
}
| apache-2.0 | 63dbccc6a9b09b502ccaa2a52aa09ec8 | 41.481481 | 199 | 0.630776 | 3.190542 | false | false | false | false |
uasys/swift | stdlib/public/core/RandomAccessCollection.swift | 11 | 12503 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A collection that supports efficient random-access index traversal.
///
/// In most cases, it's best to ignore this protocol and use the
/// `RandomAccessCollection` protocol instead, because it has a more complete
/// interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'RandomAccessCollection' instead")
public typealias RandomAccessIndexable = _RandomAccessIndexable
public protocol _RandomAccessIndexable : _BidirectionalIndexable {
// FIXME(ABI)#54 (Recursive Protocol Constraints): there is no reason for this protocol
// to exist apart from missing compiler features that we emulate with it.
// rdar://problem/20531108
//
// This protocol is almost an implementation detail of the standard
// library.
}
/// A collection that supports efficient random-access index traversal.
///
/// Random-access collections can move indices any distance and
/// measure the distance between indices in O(1) time. Therefore, the
/// fundamental difference between random-access and bidirectional collections
/// is that operations that depend on index movement or distance measurement
/// offer significantly improved efficiency. For example, a random-access
/// collection's `count` property is calculated in O(1) instead of requiring
/// iteration of an entire collection.
///
/// Conforming to the RandomAccessCollection Protocol
/// =================================================
///
/// The `RandomAccessCollection` protocol adds further constraints on the
/// associated `Indices` and `SubSequence` types, but otherwise imposes no
/// additional requirements over the `BidirectionalCollection` protocol.
/// However, in order to meet the complexity guarantees of a random-access
/// collection, either the index for your custom type must conform to the
/// `Strideable` protocol or you must implement the `index(_:offsetBy:)` and
/// `distance(from:to:)` methods with O(1) efficiency.
public protocol RandomAccessCollection :
_RandomAccessIndexable, BidirectionalCollection
// FIXME(ABI) (Revert Where Clauses): Restore this:
// where SubSequence: RandomAccessCollection, Indices: RandomAccessCollection
{
/// A collection that represents a contiguous subrange of the collection's
/// elements.
associatedtype SubSequence
// FIXME(ABI) (Revert Where Clauses): Remove these two constraints:
: _RandomAccessIndexable, BidirectionalCollection
= RandomAccessSlice<Self>
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices
// FIXME(ABI) (Revert Where Clauses): Remove these two constraints:
: _RandomAccessIndexable, BidirectionalCollection
= DefaultRandomAccessIndices<Self>
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be nonuniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can result in an unexpected copy of the collection. To avoid
/// the unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
subscript(bounds: Range<Index>) -> SubSequence { get }
}
/// Supply the default "slicing" `subscript` for `RandomAccessCollection`
/// models that accept the default associated `SubSequence`,
/// `RandomAccessSlice<Self>`.
extension RandomAccessCollection where SubSequence == RandomAccessSlice<Self> {
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.index(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
@_inlineable
public subscript(bounds: Range<Index>) -> RandomAccessSlice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return RandomAccessSlice(base: self, bounds: bounds)
}
}
// TODO: swift-3-indexing-model - Make sure RandomAccessCollection has
// documented complexity guarantees, e.g. for index(_:offsetBy:).
// TODO: swift-3-indexing-model - (By creating an ambiguity?), try to
// make sure RandomAccessCollection models implement
// index(_:offsetBy:) and distance(from:to:), or they will get the
// wrong complexity.
/// Default implementation for random access collections.
extension _RandomAccessIndexable {
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position. The
/// operation doesn't require going beyond the limiting `numbers.endIndex`
/// value, so it succeeds.
///
/// let numbers = [10, 20, 30, 40, 50]
/// let i = numbers.index(numbers.startIndex, offsetBy: 4)
/// print(numbers[i])
/// // Prints "50"
///
/// The next example attempts to retrieve an index ten positions from
/// `numbers.startIndex`, but fails, because that distance is beyond the
/// index passed as `limit`.
///
/// let j = numbers.index(numbers.startIndex,
/// offsetBy: 10,
/// limitedBy: numbers.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - n: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// `limit` should be greater than `i` to have any effect. Likewise, if
/// `n < 0`, `limit` should be less than `i` to have any effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(1)
@_inlineable
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
// FIXME: swift-3-indexing-model: tests.
let l = distance(from: i, to: limit)
if n > 0 ? l >= 0 && l < n : l <= 0 && n < l {
return nil
}
return index(i, offsetBy: n)
}
}
extension RandomAccessCollection
where Index : Strideable,
Index.Stride == IndexDistance,
Indices == CountableRange<Index> {
/// The indices that are valid for subscripting the collection, in ascending
/// order.
@_inlineable
public var indices: CountableRange<Index> {
return startIndex..<endIndex
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
@_inlineable
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: tests for the trap.
_failEarlyRangeCheck(
i, bounds: Range(uncheckedBounds: (startIndex, endIndex)))
return i.advanced(by: 1)
}
@_inlineable
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
public func index(before i: Index) -> Index {
let result = i.advanced(by: -1)
// FIXME: swift-3-indexing-model: tests for the trap.
_failEarlyRangeCheck(
result, bounds: Range(uncheckedBounds: (startIndex, endIndex)))
return result
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from an
/// array's starting index and then prints the element at that position.
///
/// let numbers = [10, 20, 30, 40, 50]
/// let i = numbers.index(numbers.startIndex, offsetBy: 4)
/// print(numbers[i])
/// // Prints "50"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(1)
@_inlineable
public func index(_ i: Index, offsetBy n: Index.Stride) -> Index {
let result = i.advanced(by: n)
// This range check is not precise, tighter bounds exist based on `n`.
// Unfortunately, we would need to perform index manipulation to
// compute those bounds, which is probably too slow in the general
// case.
// FIXME: swift-3-indexing-model: tests for the trap.
_failEarlyRangeCheck(
result, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex)))
return result
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`.
///
/// - Complexity: O(1)
@_inlineable
public func distance(from start: Index, to end: Index) -> Index.Stride {
// FIXME: swift-3-indexing-model: tests for traps.
_failEarlyRangeCheck(
start, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex)))
_failEarlyRangeCheck(
end, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex)))
return start.distance(to: end)
}
}
| apache-2.0 | e547df165ddd27da27dc0529ca034efe | 40.956376 | 115 | 0.663681 | 4.380869 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.