repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
masbog/iOS-SDK | Examples/nearables/AccelerometerExample-Swift/AccelerometerExample-Swift/DetailViewController.swift | 8 | 2418 | //
// DetailViewController.swift
// AccelerometerExample-Swift
//
// Created by Grzegorz Krukiewicz-Gacek on 05.01.2015.
// Copyright (c) 2015 Estimote Inc. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, ESTNearableManagerDelegate {
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var orientationLabel: UILabel!
@IBOutlet weak var accelerometerLabel: UILabel!
var nearable:ESTNearable!
var nearableManager:ESTNearableManager!
override func viewDidLoad() {
super.viewDidLoad()
nearableManager = ESTNearableManager()
nearableManager.delegate = self
nearableManager .startRangingForIdentifier(nearable.identifier)
typeLabel.text = ESTNearableDefinitions.nameForType(nearable.type)
}
//MARK: - ESTNearableManager delegate
func nearableManager(manager: ESTNearableManager!, didRangeNearable nearable: ESTNearable!) {
// temperatureLabel.text = NSString(format: "%.1f°C", nearable.temperature)
var orientationString:String
if nearable.isMoving == false
{
switch nearable.orientation
{
case ESTNearableOrientation.Horizontal:
orientationString = "Sticker is on its back"
case ESTNearableOrientation.HorizontalUpsideDown:
orientationString = "Sticker is on its front"
case ESTNearableOrientation.Vertical:
orientationString = "Sticker is on its legs"
case ESTNearableOrientation.VerticalUpsideDown:
orientationString = "Sticker is on its head"
case ESTNearableOrientation.LeftSide:
orientationString = "Sticker is on its left side"
case ESTNearableOrientation.RightSide:
orientationString = "Sticker is on its right side"
case ESTNearableOrientation.Unknown:
orientationString = "Sticker orientation unknown"
}
}
else
{
orientationString = "Sticker is moving"
}
orientationLabel.text = orientationString
self.accelerometerLabel.text = NSString(format: "x axis: %dmG \n y axis: %dmG \n z axis: %dmG \n",
nearable.xAcceleration,
nearable.yAcceleration,
nearable.zAcceleration)
}
}
| mit | 097085a1c50700040c17b796832c43cf | 34.028986 | 106 | 0.645428 | 5.687059 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ColorSpace/ColorSpaceBase/ICC/iccProfile/iccType/iccXYZNumber.swift | 1 | 2104 | //
// iccXYZNumber.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
@frozen
@usableFromInline
struct iccXYZNumber: ByteCodable {
var x: Fixed16Number<BEInt32>
var y: Fixed16Number<BEInt32>
var z: Fixed16Number<BEInt32>
init(x: Fixed16Number<BEInt32>, y: Fixed16Number<BEInt32>, z: Fixed16Number<BEInt32>) {
self.x = x
self.y = y
self.z = z
}
init(_ xyz: XYZColorModel) {
self.x = Fixed16Number(xyz.x)
self.y = Fixed16Number(xyz.y)
self.z = Fixed16Number(xyz.z)
}
@usableFromInline
init(from data: inout Data) throws {
self.x = try data.decode(Fixed16Number.self)
self.y = try data.decode(Fixed16Number.self)
self.z = try data.decode(Fixed16Number.self)
}
@usableFromInline
func write<Target: ByteOutputStream>(to stream: inout Target) {
stream.encode(x)
stream.encode(y)
stream.encode(z)
}
}
| mit | 02f937ef7cec4406ee516c1d00899c8b | 34.661017 | 91 | 0.688213 | 3.889094 | false | false | false | false |
ubi-naist/SenStick | ios/Pods/iOSDFULibrary/iOSDFULibrary/Classes/Utilities/Streams/DFUStreamBin.swift | 4 | 3068 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
internal class DFUStreamBin : DFUStream {
private(set) var currentPart = 1
private(set) var parts = 1
private(set) var currentPartType: UInt8 = 0
/// Firmware binaries
private var binaries: Data
/// The init packet content
private var initPacketBinaries: Data?
private var firmwareSize: UInt32 = 0
var size: DFUFirmwareSize {
switch currentPartType {
case FIRMWARE_TYPE_SOFTDEVICE:
return DFUFirmwareSize(softdevice: firmwareSize, bootloader: 0, application: 0)
case FIRMWARE_TYPE_BOOTLOADER:
return DFUFirmwareSize(softdevice: 0, bootloader: firmwareSize, application: 0)
// case FIRMWARE_TYPE_APPLICATION:
default:
return DFUFirmwareSize(softdevice: 0, bootloader: 0, application: firmwareSize)
}
}
var currentPartSize: DFUFirmwareSize {
return size
}
init(urlToBinFile: URL, urlToDatFile: URL?, type: DFUFirmwareType) {
binaries = try! Data(contentsOf: urlToBinFile)
firmwareSize = UInt32(binaries.count)
if let dat = urlToDatFile {
initPacketBinaries = try? Data(contentsOf: dat)
}
self.currentPartType = type.rawValue
}
var data: Data {
return binaries
}
var initPacket: Data? {
return initPacketBinaries
}
func hasNextPart() -> Bool {
return false
}
func switchToNextPart() {
// do nothing
}
}
| mit | 077dd94d85b723e75275f9d1dcc8d767 | 38.844156 | 144 | 0.702738 | 5.029508 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/managers/TKContactsManager.swift | 1 | 4215 | //
// TKContactsManager.swift
// TripKit
//
// Created by Adrian Schönig on 20.05.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import Contacts
public class TKContactsManager: NSObject, TKPermissionManager {
public enum AddressKind {
case home
case work
public init?(label: String?) {
switch label {
case CNLabelHome: self = .home
case CNLabelWork: self = .work
default: return nil
}
}
}
public struct ContactAddress: Hashable {
public let name: String
public let image: TKImage?
public let kind: AddressKind?
public let address: String
public let postalAddress: CNPostalAddress
func matches(_ kind: AddressKind?) -> Bool {
return kind == nil || self.kind == kind
}
var locationName: String {
switch kind {
case nil: return Loc.PersonsPlace(name: name)
case .home?: return Loc.PersonsHome(name: name)
case .work?: return Loc.PersonsWork(name: name)
}
}
}
@objc(sharedInstance)
public static let shared = TKContactsManager()
public var openSettingsHandler: (() -> Void)? = nil
let queue: DispatchQueue
private let store: CNContactStore
private static let keysToFetch: [CNKeyDescriptor] = [
CNContactGivenNameKey as CNKeyDescriptor,
CNContactPostalAddressesKey as CNKeyDescriptor,
CNContactThumbnailImageDataKey as CNKeyDescriptor
]
private override init() {
self.queue = DispatchQueue(label: "com.skedgo.tripkit.contacts", qos: .userInitiated)
self.store = CNContactStore()
super.init()
}
public func fetchContacts(searchString: String, kind: AddressKind? = nil) throws -> [ContactAddress] {
assert(!Thread.isMainThread, "Don't call this on the main thread. It's slow.")
guard isAuthorized else { return [] }
let predicate = CNContact.predicateForContacts(matchingName: searchString)
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: TKContactsManager.keysToFetch)
return contacts.flatMap { $0.toContactAddresses() }.filter { $0.matches(kind) }
}
public func fetchMyLocations(limitTo kind: AddressKind? = nil) throws -> [ContactAddress] {
assert(!Thread.isMainThread, "Don't call this on the main thread. It's slow.")
guard isAuthorized else { return [] }
#if os(iOS) || os(tvOS)
return [] // not yet supported
#elseif os(OSX)
let contact = try store.unifiedMeContactWithKeys(toFetch: TKContactsManager.keysToFetch)
return contact.toContactAddresses().filter { $0.matches(kind) }
#endif
}
// MARK: - TKPermissionManager
public func askForPermission(_ completion: @escaping (Bool) -> Void) {
store.requestAccess(for: .contacts) { granted, _ in
completion(granted)
}
}
public var authorizationStatus: TKAuthorizationStatus {
switch CNContactStore.authorizationStatus(for: .contacts) {
case .authorized: return .authorized
case .denied: return .denied
case .notDetermined: return .notDetermined
case .restricted: return .restricted
@unknown default:
assertionFailure("Unhandled status")
return .denied
}
}
public var authorizationAlertText: String {
return Loc.ContactsAuthorizationAlertText
}
}
// MARK: - Helpers
extension CNContact {
fileprivate func toContactAddresses() -> [TKContactsManager.ContactAddress] {
// WARNING: Whatever we access here, needs to match `keysToFetch` otherwise
// exceptions fire.
let image = circularThumbnail()
return postalAddresses.map {
let singleLine = TKAddressFormatter.singleLineAddress(for: $0.value)
return TKContactsManager.ContactAddress(name: givenName, image: image, kind: TKContactsManager.AddressKind(label: $0.label), address: singleLine, postalAddress: $0.value)
}
}
fileprivate func circularThumbnail() -> TKImage? {
#if os(iOS) || os(tvOS)
guard let data = thumbnailImageData, let thumbnail = TKImage(data: data) else { return nil }
return TKImageBuilder.drawCircularImage(insideImage: thumbnail)
#elseif os(OSX)
return nil
#endif
}
}
| apache-2.0 | 30d81a707f8b09cae8d910f769e2641f | 28.879433 | 176 | 0.68882 | 4.530108 | false | false | false | false |
jazzychad/FlickrWatch | FlickrWatchSwift/FlickrWatchSwift WatchKit Extension/InterfaceController.swift | 1 | 4150 | //
// InterfaceController.swift
// FlickrWatchSwift WatchKit Extension
//
// Created by Chad Etzel on 3/15/15.
// Copyright (c) 2015 Charles Etzel. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet weak var mainLabel: WKInterfaceLabel!
@IBOutlet weak var digitImage0: WKInterfaceImage!
@IBOutlet weak var digitImage1: WKInterfaceImage!
@IBOutlet weak var digitImage2: WKInterfaceImage!
@IBOutlet weak var digitImage3: WKInterfaceImage!
var _dateFormatter : NSDateFormatter?
var _timer : NSTimer?
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
NSLog("%@ awakeWithContext", self)
FlickrKit.sharedFlickrKit().initializeWithAPIKey("FLICKR_KEY_HERE", sharedSecret: "FLICKR_SECRET_HERE")
mainLabel.setText("FlickrWatch Swift")
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
NSLog("%@ will activate", self)
var hourMode = NSUserDefaults.standardUserDefaults().integerForKey("FlickrWatchHourModeKey")
_dateFormatter = NSDateFormatter()
if hourMode == 0 {
_dateFormatter!.dateFormat = "hh:mm"
} else {
_dateFormatter!.dateFormat = "HH:mm"
}
_updateTimeDigits()
_timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: Selector("_updateTimeDigits"), userInfo: nil, repeats: true)
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
NSLog("%@ did deactivate", self)
super.didDeactivate()
_timer?.invalidate()
}
func _updateTimeDigits() {
var timeString = _dateFormatter!.stringFromDate(NSDate())
var hourMode = NSUserDefaults.standardUserDefaults().integerForKey("FlickrWatchHourModeKey")
var digit = timeString.substringWithRange(Range<String.Index>(start: advance(timeString.startIndex, 0), end: advance(timeString.startIndex, 1)))
if hourMode == 0 && digit == "0" {
digitImage0.setAlpha(0)
} else {
digitImage0.setAlpha(1)
_updateImage(digitImage0, withDigit: digit)
}
digit = timeString.substringWithRange(Range<String.Index>(start: advance(timeString.startIndex, 1), end: advance(timeString.startIndex, 2)))
_updateImage(digitImage1, withDigit: digit)
digit = timeString.substringWithRange(Range<String.Index>(start: advance(timeString.startIndex, 3), end: advance(timeString.startIndex, 4)))
_updateImage(digitImage2, withDigit: digit)
digit = timeString.substringWithRange(Range<String.Index>(start: advance(timeString.startIndex, 4), end: advance(timeString.startIndex, 5)))
_updateImage(digitImage3, withDigit: digit)
}
func _updateImage(digitImage : WKInterfaceImage, withDigit digit : String) {
var tag = digit
if tag == "0" {
tag = "00"
}
FlickrKit.sharedFlickrKit().call("flickr.groups.pools.getPhotos", args: ["tags": tag, "group_id": "54718308@N00", "extras": "url_sq"]) { (response, error) -> Void in
var photos = (response["photos"] as! [NSObject : AnyObject])["photo"] as! [[NSObject : AnyObject]]
NSLog("photos: %@", photos)
var randIndex = arc4random_uniform(UInt32(photos.count))
var photoDict = photos[Int(randIndex)]
var urlString = photoDict["url_sq"] as! String
var url = NSURL(string: urlString)
var imgData = NSURLConnection.sendSynchronousRequest(NSURLRequest(URL: url!), returningResponse: nil, error: nil)
if let data = imgData {
NSLog("data length: %lu", data.length)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
digitImage.setImageData(data)
});
}
}
}
}
| mit | 2a3994dfba93dee4fae8fa64499de3da | 33.583333 | 173 | 0.646988 | 4.715909 | false | false | false | false |
jiaopen/ImagePickerSheetController | ImagePickerSheetController/ImagePickerSheetController/ImagePreviewTableViewCell.swift | 1 | 1301 | //
// ImagePreviewTableViewCell.swift
// ImagePickerSheet
//
// Created by Laurin Brandner on 06/09/14.
// Copyright (c) 2014 Laurin Brandner. All rights reserved.
//
import UIKit
@objc class ImagePreviewTableViewCell : UITableViewCell {
var collectionView: ImagePickerCollectionView? {
willSet {
if let collectionView = collectionView {
collectionView.removeFromSuperview()
}
if let collectionView = newValue {
addSubview(collectionView)
}
}
}
// MARK: - Other Methods
override func prepareForReuse() {
collectionView = nil
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
// Setting the frame of the collectionView this large avoids a small animation glitch when resizing the previews. You'll get a beer from @larcus94 if you'll get it to work without this workaround :)
if let collectionView = collectionView {
collectionView.frame = CGRect(x: -bounds.width, y: bounds.minY, width: bounds.width*3, height: bounds.height)
collectionView.contentInset = UIEdgeInsetsMake(0.0, bounds.width, 0.0, bounds.width)
}
}
}
| mit | f71ca0f65e840023fd799bb12001e89b | 28.568182 | 206 | 0.617986 | 5.122047 | false | false | false | false |
nibty/skate-retro-tvos | RetroSkate/Grounds.swift | 1 | 3235 | //
// Grounds.swift
// Game
//
// Created by Nicholas Pettas on 11/10/15.
// Copyright © 2015 Nicholas Pettas. All rights reserved.
//
import SpriteKit
class Grounds: SKNode {
// Ground setup
var sidewalkPices = [Ground]()
var frontSidewalkPices = [Ground]()
var asphaltPieces = [Ground]()
override func update() {
// Update asphalt
for var i = 0; i < asphaltPieces.count; i++ {
updateGround(asphaltPieces, groundIndex: i)
}
// Update sidewalk
for var i = 0; i < sidewalkPices.count; i++ {
updateGround(sidewalkPices, groundIndex: i)
}
}
func setup() {
// Setup asphalt pieces
for var i = 0; i < GameManager.sharedInstance.ASP_PIECES; i++ {
let asphalt = Asphalt()
asphalt.startMoving()
asphaltPieces.append(asphalt)
setupGroud(asphaltPieces, index: i)
self.addChild(asphalt)
}
// Setup sidewalk pieces
for var i = 0; i < GameManager.sharedInstance.SIDEWALK_PIECES; i++ {
let sidewalk = Sidewalk()
sidewalk.startMoving()
sidewalkPices.append(sidewalk)
setupGroud(sidewalkPices, index: i)
self.addChild(sidewalk)
}
// Setup floor collider so the player will not fall through
let floor = SKSpriteNode(color: UIColor.clearColor(), size: CGSizeMake(GameManager.sharedInstance.FLOOR_WIDTH, GameManager.sharedInstance.FLOOR_HEIGHT))
self.addChild(floor)
floor.position = CGPointMake(GameManager.sharedInstance.FLOOR_POSITION_X, GameManager.sharedInstance.FLOOR_POSITION_Y)
floor.physicsBody = SKPhysicsBody(rectangleOfSize: floor.size)
floor.physicsBody!.categoryBitMask = GameManager.sharedInstance.COLLIDER_RIDEABLE
floor.physicsBody!.contactTestBitMask = GameManager.sharedInstance.COLLIDER_PLAYER
floor.physicsBody?.dynamic = false
}
func setupGroud(grounds: [Ground], index: Int) {
if index == 0 {
grounds[index].position = CGPointMake(GameManager.sharedInstance.GROUND_X_RESET, grounds[index].yPos)
} else {
grounds[index].position = CGPointMake(grounds[index].size.width + grounds[index - 1].position.x, grounds[index - 1].position.y)
}
}
func updateGround(grounds: [Ground], groundIndex: Int) {
var index: Int!
if grounds[groundIndex].position.x <= GameManager.sharedInstance.GROUND_X_RESET {
if groundIndex == 0 {
index = grounds.count - 1
} else {
index = groundIndex - 1
}
let newPost = CGPointMake(grounds[index].position.x + grounds[groundIndex].size.width, grounds[index].position.y)
grounds[groundIndex].position = newPost
}
}
override func removeAllActions() {
super.removeAllActions()
for node in sidewalkPices {
node.removeAllActions()
}
for node in asphaltPieces {
node.removeAllActions()
}
}
} | mit | 0ae19059923303b85f478207fbbc5abd | 32.350515 | 160 | 0.593074 | 4.51046 | false | false | false | false |
ashfurrow/RxSwift | RxSwift/Rx.swift | 4 | 1321 | //
// Rx.swift
// Rx
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if TRACE_RESOURCES
/**
Counts internal Rx resources (Observables, Observers, Disposables ...).
It provides a really simple way to detect leaks early during development.
*/
public var resourceCount: Int32 = 0
#endif
// Swift doesn't have a concept of abstract metods.
// This function is being used as a runtime check that abstract methods aren't being called.
@noreturn func abstractMethod() -> Void {
rxFatalError("Abstract method")
}
@noreturn func rxFatalError(lastMessage: String) {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
func incrementChecked(inout i: Int) throws -> Int {
if i == Int.max {
throw RxError.Overflow
}
let result = i
i += 1
return result
}
func decrementChecked(inout i: Int) throws -> Int {
if i == Int.min {
throw RxError.Overflow
}
let result = i
i -= 1
return result
}
extension NSObject {
func rx_synchronized<T>(@noescape action: () -> T) -> T {
objc_sync_enter(self)
let result = action()
objc_sync_exit(self)
return result
}
}
| mit | 9a69b7167719e9ea130df2270b5ad5cd | 22.589286 | 115 | 0.660863 | 3.8739 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalServiceKit/tests/Network/MessageSendJobQueueTest.swift | 1 | 8178 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import XCTest
@testable import SignalServiceKit
class MessageSenderJobQueueTest: SSKBaseTestSwift {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
// MARK: Dependencies
private var messageSender: OWSFakeMessageSender {
return MockSSKEnvironment.shared.messageSender as! OWSFakeMessageSender
}
// MARK:
func test_messageIsSent() {
let message: TSOutgoingMessage = OutgoingMessageFactory().create()
let expectation = sentExpectation(message: message)
let jobQueue = MessageSenderJobQueue()
jobQueue.setup()
self.write { transaction in
jobQueue.add(message: message.asPreparer, transaction: transaction)
}
self.wait(for: [expectation], timeout: 0.1)
}
func test_waitsForSetup() {
let message: TSOutgoingMessage = OutgoingMessageFactory().create()
let sentBeforeReadyExpectation = sentExpectation(message: message)
sentBeforeReadyExpectation.isInverted = true
let jobQueue = MessageSenderJobQueue()
self.write { transaction in
jobQueue.add(message: message.asPreparer, transaction: transaction)
}
self.wait(for: [sentBeforeReadyExpectation], timeout: 0.1)
let sentAfterReadyExpectation = sentExpectation(message: message)
jobQueue.setup()
self.wait(for: [sentAfterReadyExpectation], timeout: 0.1)
}
func test_respectsQueueOrder() {
let message1: TSOutgoingMessage = OutgoingMessageFactory().create()
let message2: TSOutgoingMessage = OutgoingMessageFactory().create()
let message3: TSOutgoingMessage = OutgoingMessageFactory().create()
let jobQueue = MessageSenderJobQueue()
self.write { transaction in
jobQueue.add(message: message1.asPreparer, transaction: transaction)
jobQueue.add(message: message2.asPreparer, transaction: transaction)
jobQueue.add(message: message3.asPreparer, transaction: transaction)
}
let sendGroup = DispatchGroup()
sendGroup.enter()
sendGroup.enter()
sendGroup.enter()
var sentMessages: [TSOutgoingMessage] = []
messageSender.sendMessageWasCalledBlock = { sentMessage in
sentMessages.append(sentMessage)
sendGroup.leave()
}
jobQueue.setup()
switch sendGroup.wait(timeout: .now() + 1.0) {
case .timedOut:
XCTFail("timed out waiting for sends")
case .success:
XCTAssertEqual([message1, message2, message3].map { $0.uniqueId }, sentMessages.map { $0.uniqueId })
}
}
func test_sendingInvisibleMessage() {
let jobQueue = MessageSenderJobQueue()
jobQueue.setup()
let message = OutgoingMessageFactory().buildDeliveryReceipt()
let expectation = sentExpectation(message: message)
self.write { transaction in
jobQueue.add(message: message.asPreparer, transaction: transaction)
}
self.wait(for: [expectation], timeout: 0.1)
}
func test_retryableFailure() {
let message: TSOutgoingMessage = OutgoingMessageFactory().create()
let jobQueue = MessageSenderJobQueue()
self.write { transaction in
jobQueue.add(message: message.asPreparer, transaction: transaction)
}
let finder = AnyJobRecordFinder()
var readyRecords: [SSKJobRecord] = []
self.read { transaction in
readyRecords = finder.allRecords(label: MessageSenderJobQueue.jobRecordLabel, status: .ready, transaction: transaction)
}
XCTAssertEqual(1, readyRecords.count)
let jobRecord = readyRecords.first!
XCTAssertEqual(0, jobRecord.failureCount)
// simulate permanent failure
let error = NSError(domain: "foo", code: 0, userInfo: nil)
error.isRetryable = true
self.messageSender.stubbedFailingError = error
let expectation = sentExpectation(message: message) {
jobQueue.isSetup = false
}
jobQueue.setup()
self.wait(for: [expectation], timeout: 0.1)
self.read { transaction in
jobRecord.anyReload(transaction: transaction)
}
XCTAssertEqual(1, jobRecord.failureCount)
XCTAssertEqual(.running, jobRecord.status)
let retryCount: UInt = MessageSenderJobQueue.maxRetries
(1..<retryCount).forEach { _ in
let expectedResend = sentExpectation(message: message)
// Manually kick queue restart.
//
// OWSOperation uses an NSTimer backed retry mechanism, but NSTimer's are not fired
// during `self.wait(for:,timeout:` unless the timer was scheduled on the
// `RunLoop.main`.
//
// We could move the timer to fire on the main RunLoop (and have the selector dispatch
// back to a background queue), but the production code is simpler if we just manually
// kick every retry in the test case.
XCTAssertNotNil(jobQueue.runAnyQueuedRetry())
self.wait(for: [expectedResend], timeout: 0.1)
}
// Verify one retry left
self.read { transaction in
jobRecord.anyReload(transaction: transaction)
}
XCTAssertEqual(retryCount, jobRecord.failureCount)
XCTAssertEqual(.running, jobRecord.status)
// Verify final send fails permanently
let expectedFinalResend = sentExpectation(message: message)
XCTAssertNotNil(jobQueue.runAnyQueuedRetry())
self.wait(for: [expectedFinalResend], timeout: 0.1)
self.read { transaction in
jobRecord.anyReload(transaction: transaction)
}
XCTAssertEqual(retryCount + 1, jobRecord.failureCount)
XCTAssertEqual(.permanentlyFailed, jobRecord.status)
// No remaining retries
XCTAssertNil(jobQueue.runAnyQueuedRetry())
}
func test_permanentFailure() {
let message: TSOutgoingMessage = OutgoingMessageFactory().create()
let jobQueue = MessageSenderJobQueue()
self.write { transaction in
jobQueue.add(message: message.asPreparer, transaction: transaction)
}
let finder = AnyJobRecordFinder()
var readyRecords: [SSKJobRecord] = []
self.read { transaction in
readyRecords = finder.allRecords(label: MessageSenderJobQueue.jobRecordLabel, status: .ready, transaction: transaction)
}
XCTAssertEqual(1, readyRecords.count)
let jobRecord = readyRecords.first!
XCTAssertEqual(0, jobRecord.failureCount)
// simulate permanent failure
let error = NSError(domain: "foo", code: 0, userInfo: nil)
error.isRetryable = false
self.messageSender.stubbedFailingError = error
let expectation = sentExpectation(message: message) {
jobQueue.isSetup = false
}
jobQueue.setup()
self.wait(for: [expectation], timeout: 0.1)
self.read { transaction in
jobRecord.anyReload(transaction: transaction)
}
XCTAssertEqual(1, jobRecord.failureCount)
XCTAssertEqual(.permanentlyFailed, jobRecord.status)
}
// MARK: Private
private func sentExpectation(message: TSOutgoingMessage, block: @escaping () -> Void = { }) -> XCTestExpectation {
let expectation = self.expectation(description: "sent message")
messageSender.sendMessageWasCalledBlock = { [weak messageSender] sentMessage in
guard sentMessage.uniqueId == message.uniqueId else {
XCTFail("unexpected sentMessage: \(sentMessage)")
return
}
expectation.fulfill()
block()
guard let strongMessageSender = messageSender else {
return
}
strongMessageSender.sendMessageWasCalledBlock = nil
}
return expectation
}
}
| gpl-3.0 | ddcee9d9a0f6dd934cd93340856c237c | 33.361345 | 131 | 0.642333 | 5.265937 | false | true | false | false |
PJayRushton/stats | Stats/TeamActionSectionController.swift | 1 | 2335 | //
// TeamActionSectionController.swift
// Stats
//
// Created by Parker Rushton on 3/31/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import IGListKit
class TeamActionSection: ListDiffable {
var team: Team
var menuItem: HomeMenuItem
var badgeCount: Int?
init(team: Team, menuItem: HomeMenuItem, badgeCount: Int? = nil) {
self.team = team
self.menuItem = menuItem
self.badgeCount = badgeCount
}
func diffIdentifier() -> NSObjectProtocol {
return NSNumber(value: menuItem.rawValue)
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
guard let other = object as? TeamActionSection else { return false }
return team == other.team && menuItem.title == other.menuItem.title && badgeCount == other.badgeCount
}
}
class TeamActionSectionController: ListSectionController {
var actionSection: TeamActionSection!
var didSelectItem: ((HomeMenuItem) -> Void) = { _ in }
override init() {
super.init()
inset = UIEdgeInsets.zero
}
}
extension TeamActionSectionController {
override func sizeForItem(at index: Int) -> CGSize {
guard let collectionContext = collectionContext else { return .zero }
let fullWidth = collectionContext.containerSize.width
let headerHeight = collectionContext.containerSize.width * (2 / 3)
let rows = CGFloat(HomeMenuItem.allValues.count) / actionSection.menuItem.itemsPerRow
let height = (collectionContext.containerSize.height - headerHeight) / rows
let width = fullWidth / actionSection.menuItem.itemsPerRow
return CGSize(width: width, height: height)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
let cell = collectionContext?.dequeueReusableCellFromStoryboard(withIdentifier: HomeCollectionViewCell.reuseIdentifier, for: self, at: index) as! HomeCollectionViewCell
cell.update(with: actionSection.menuItem, badgeCount: actionSection.badgeCount)
return cell
}
override func didUpdate(to object: Any) {
actionSection = object as? TeamActionSection
}
override func didSelectItem(at index: Int) {
didSelectItem(actionSection.menuItem)
}
}
| mit | 4141eeedeb04b3f55aea3d1bf6aebe6a | 30.540541 | 176 | 0.675664 | 5.09607 | false | false | false | false |
vhart/PPL-iOS | PPL-iOS/PPL-iOS/WorkoutLogCollectionViewCell.swift | 1 | 1473 | //
// WorkoutLogCollectionViewCell.swift
// PPL-iOS
//
// Created by Jovanny Espinal on 2/22/16.
// Copyright © 2016 Jovanny Espinal. All rights reserved.
//
import UIKit
class WorkoutLogCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var typeOfWorkoutLabel: UILabel!
@IBOutlet var exerciseNameLabels: [UILabel]!
@IBOutlet var exerciseSetxRepxWeightLabels: [UILabel]!
@IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
// MARK: Label Formatting
extension WorkoutLogCollectionViewCell {
func updateExerciseLabels(exercises: [Exercise])
{
clearExerciseLabesl()
for i in 0..<exercises.count {
let sets = exercises[i].numberOfSets.copyToArray() as! [Set]
exerciseNameLabels[i].text = exercises[i].abbreviatedExerciseName()
exerciseSetxRepxWeightLabels[i].text = "\(sets.count)x\(sets.first!.numberOfReps) \(exercises[i].weight.cleanValue)lbs"
exerciseSetxRepxWeightLabels[i].textColor = UIColor.lightGrayColor()
exerciseSetxRepxWeightLabels[i].sizeToFit()
exerciseNameLabels[i].sizeToFit()
}
}
func clearExerciseLabesl()
{
for i in 0..<exerciseNameLabels.count {
exerciseNameLabels[i].text = ""
exerciseSetxRepxWeightLabels[i].text = ""
}
}
}
| mit | 3cf86f646538c0892b6072bdabd76c9e | 28.44 | 131 | 0.63587 | 4.58567 | false | false | false | false |
yanif/circator | MetabolicCompass/View Controller/TabController/FilterCells/DashboardFilterCell.swift | 1 | 1313 | //
// DashboardFilterCell.swift
// MetabolicCompass
//
// Created by Inaiur on 5/6/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import UIKit
protocol DashboardFilterCellDelegate: NSObjectProtocol {
func didChangeSelectionStatus(selected: Bool)
}
class DashboardFilterCell: UITableViewCell {
@IBOutlet weak var checkBoxButton: UIButton!
@IBOutlet weak var nameLabel: UILabel!
weak var delegate: DashboardFilterCellDelegate?
var data: DashboardFilterCellData? {
didSet {
assert(data != nil)
guard data != nil else { return }
self.nameLabel.text = data!.title;
self.checkBoxButton.selected = data!.selected
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.checkBoxButton.userInteractionEnabled = false
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@IBAction func didPressButton(sender: AnyObject) {
self.checkBoxButton.selected = !self.checkBoxButton.selected;
self.data?.selected = self.checkBoxButton.selected
if let delegate = self.delegate {
delegate.didChangeSelectionStatus(self.checkBoxButton.selected)
}
}
}
| apache-2.0 | e2299e37a898a3724888a5ead63bed0c | 26.333333 | 75 | 0.675305 | 4.736462 | false | false | false | false |
aikdong/CNTV | COCNTV/QRCode.swift | 1 | 4552 | //
// QRCode.swift
// QRCode
//
// Created by 刘凡 on 15/5/15.
// Copyright (c) 2015年 joyios. All rights reserved.
//
import UIKit
import AVFoundation
public class QRCode: NSObject {
/// corner line width
var lineWidth: CGFloat
/// corner stroke color
var strokeColor: UIColor
/// the max count for detection
var maxDetectedCount: Int
/// current count for detection
var currentDetectedCount: Int = 0
/// the scan rect, default is the bounds of the scan view, can modify it if need
public var scanFrame: CGRect = CGRectZero
/// init function
///
/// - returns: the scanner object
public override init() {
self.lineWidth = 4
self.strokeColor = UIColor.greenColor()
self.maxDetectedCount = 20
super.init()
}
/// init function
///
/// - parameter autoRemoveSubLayers: remove sub layers auto after detected code image
/// - parameter lineWidth: line width, default is 4
/// - parameter strokeColor: stroke color, default is Green
/// - parameter maxDetectedCount: max detecte count, default is 20
///
/// - returns: the scanner object
public init(lineWidth: CGFloat = 4, strokeColor: UIColor = UIColor.greenColor(), maxDetectedCount: Int = 20) {
self.lineWidth = lineWidth
self.strokeColor = strokeColor
self.maxDetectedCount = maxDetectedCount
}
// MARK: - Generate QRCode Image
/// generate image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
///
/// - returns: the generated image
class public func generateImage(stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25) -> UIImage? {
return generateImage(stringValue, avatarImage: avatarImage, avatarScale: avatarScale, color: CIColor(color: UIColor.blackColor()), backColor: CIColor(color: UIColor.whiteColor()))
}
/// Generate Qrcode Image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
/// - parameter color: the CI color for forenground, default is black
/// - parameter backColor: th CI color for background, default is white
///
/// - returns: the generated image
class public func generateImage(stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25, color: CIColor, backColor: CIColor) -> UIImage? {
// generate qrcode image
let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
qrFilter.setDefaults()
qrFilter.setValue(stringValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false), forKey: "inputMessage")
let ciImage = qrFilter.outputImage
// scale qrcode image
let colorFilter = CIFilter(name: "CIFalseColor")!
colorFilter.setDefaults()
colorFilter.setValue(ciImage, forKey: "inputImage")
colorFilter.setValue(color, forKey: "inputColor0")
colorFilter.setValue(backColor, forKey: "inputColor1")
let transform = CGAffineTransformMakeScale(10, 10)
let transformedImage = qrFilter.outputImage!.imageByApplyingTransform(transform)
let image = UIImage(CIImage: transformedImage)
if avatarImage != nil {
return insertAvatarImage(image, avatarImage: avatarImage!, scale: avatarScale)
}
return image
}
class func insertAvatarImage(codeImage: UIImage, avatarImage: UIImage, scale: CGFloat) -> UIImage {
let rect = CGRectMake(0, 0, codeImage.size.width, codeImage.size.height)
UIGraphicsBeginImageContext(rect.size)
codeImage.drawInRect(rect)
let avatarSize = CGSizeMake(rect.size.width * scale, rect.size.height * scale)
let x = (rect.width - avatarSize.width) * 0.5
let y = (rect.height - avatarSize.height) * 0.5
avatarImage.drawInRect(CGRectMake(x, y, avatarSize.width, avatarSize.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
} | mit | 14d28fc402088871eec80a5d99791df2 | 36.578512 | 187 | 0.644743 | 5.051111 | false | false | false | false |
Ethenyl/JAMFKit | JamfKit/Sources/Models/NetbootServer.swift | 1 | 5465 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
/// Represents a physical netboot server, contains information about the server and it's configuration.
@objc(JMFKNetbootServer)
public final class NetbootServer: BaseObject, Endpoint {
// MARK: - Constants
public static let Endpoint = "netbootservers"
static let IpAddressKey = "ip_address"
static let DefaultImageKey = "default_image"
static let SpecificImageKey = "specific_image"
static let TargetPlatformKey = "target_platform"
static let SharePointKey = "share_point"
static let SetKey = "set"
static let ImageKey = "image"
static let ProtocolKey = "protocol"
static let ConfigureManuallyKey = "configure_manually"
static let BootArgumentsKey = "boot_args"
static let BootFileKey = "boot_file"
static let BootDeviceKey = "boot_device"
// MARK: - Properties
@objc
public var ipAddress = ""
@objc
public var isDefaultImage = false
@objc
public var isSpecificImage = false
@objc
public var targetPlatform = ""
@objc
public var sharePoint = ""
@objc
public var set = ""
@objc
public var image = ""
@objc
public var filesystemProtocol = ""
@objc
public var configureManually = false
@objc
public var bootArguments = ""
@objc
public var bootFile = ""
@objc
public var bootDevice = ""
public override var description: String {
return "[\(String(describing: NetbootServer.self))][\(identifier) - \(self.ipAddress)]"
}
// MARK: - Initialization
public required init?(json: [String: Any], node: String = "") {
ipAddress = json[NetbootServer.IpAddressKey] as? String ?? ""
isDefaultImage = json[NetbootServer.DefaultImageKey] as? Bool ?? false
isSpecificImage = json[NetbootServer.SpecificImageKey] as? Bool ?? false
targetPlatform = json[NetbootServer.TargetPlatformKey] as? String ?? ""
sharePoint = json[NetbootServer.SharePointKey] as? String ?? ""
set = json[NetbootServer.SetKey] as? String ?? ""
image = json[NetbootServer.ImageKey] as? String ?? ""
filesystemProtocol = json[NetbootServer.ProtocolKey] as? String ?? ""
configureManually = json[NetbootServer.ConfigureManuallyKey] as? Bool ?? false
bootArguments = json[NetbootServer.BootArgumentsKey] as? String ?? ""
bootFile = json[NetbootServer.BootFileKey] as? String ?? ""
bootDevice = json[NetbootServer.BootDeviceKey] as? String ?? ""
super.init(json: json)
}
public override init?(identifier: UInt, name: String) {
super.init(identifier: identifier, name: name)
}
// MARK: - Functions
public override func toJSON() -> [String: Any] {
var json = super.toJSON()
json[NetbootServer.IpAddressKey] = ipAddress
json[NetbootServer.DefaultImageKey] = isDefaultImage
json[NetbootServer.SpecificImageKey] = isSpecificImage
json[NetbootServer.TargetPlatformKey] = targetPlatform
json[NetbootServer.SharePointKey] = sharePoint
json[NetbootServer.SetKey] = set
json[NetbootServer.ImageKey] = image
json[NetbootServer.ProtocolKey] = filesystemProtocol
json[NetbootServer.ConfigureManuallyKey] = configureManually
json[NetbootServer.BootArgumentsKey] = bootArguments
json[NetbootServer.BootFileKey] = bootFile
json[NetbootServer.BootDeviceKey] = bootDevice
return json
}
}
// MARK: - Creatable
extension NetbootServer: Creatable {
public func createRequest() -> URLRequest? {
return getCreateRequest()
}
}
// MARK: - Readable
extension NetbootServer: Readable {
public static func readAllRequest() -> URLRequest? {
return getReadAllRequest()
}
public static func readRequest(identifier: String) -> URLRequest? {
return getReadRequest(identifier: identifier)
}
public func readRequest() -> URLRequest? {
return getReadRequest()
}
/// Returns a GET **URLRequest** based on the supplied name.
public static func readRequest(name: String) -> URLRequest? {
return getReadRequest(name: name)
}
/// Returns a GET **URLRequest** based on the email.
public func readRequestWithName() -> URLRequest? {
return getReadRequestWithName()
}
}
// MARK: - Updatable
extension NetbootServer: Updatable {
public func updateRequest() -> URLRequest? {
return getUpdateRequest()
}
/// Returns a PUT **URLRequest** based on the name.
public func updateRequestWithName() -> URLRequest? {
return getUpdateRequestWithName()
}
}
// MARK: - Deletable
extension NetbootServer: Deletable {
public static func deleteRequest(identifier: String) -> URLRequest? {
return getDeleteRequest(identifier: identifier)
}
public func deleteRequest() -> URLRequest? {
return getDeleteRequest()
}
/// Returns a DELETE **URLRequest** based on the supplied name.
public static func deleteRequest(name: String) -> URLRequest? {
return getDeleteRequest(name: name)
}
/// Returns a DELETE **URLRequest** based on the name.
public func deleteRequestWithName() -> URLRequest? {
return getDeleteRequestWithName()
}
}
| mit | 3b000f6aebbb606304fd07eed0b7a018 | 28.695652 | 103 | 0.670022 | 4.706288 | false | false | false | false |
the-grid/Portal | PortalTests/Fixtures/BlockTypeFixtures.swift | 1 | 373 | import Argo
import Portal
let blockTypeResponseBody = "text"
let blockTypeJson = JSON.String(blockTypeResponseBody)
let blockTypeModel = BlockType(rawValue: blockTypeResponseBody)!
let updatedBlockTypeResponseBody = "code"
let updatedBlockTypeJson = JSON.String(updatedBlockTypeResponseBody)
let updatedBlockTypeModel = BlockType(rawValue: updatedBlockTypeResponseBody)!
| mit | 8150093d1b4b3eede71f90ad7da73f50 | 36.3 | 78 | 0.849866 | 4.604938 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/Recording/RecordingManager.swift | 1 | 11648 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
protocol RecordingManagerDelegate: class {
/// Called when the recording manager fired a visual trigger.
///
/// - Parameters:
/// - recordingManager: The recording manager.
/// - trigger: The trigger.
/// - sensor: The sensor that the trigger was fired for.
func recordingManager(_ recordingManager: RecordingManager,
didFireVisualTrigger trigger: SensorTrigger,
forSensor sensor: Sensor)
/// Called when the recording manager fired a trigger that should start recording.
///
/// - Parameters:
/// - recordingManager: The recording manager.
/// - trigger: The trigger.
func recordingManager(_ recordingManager: RecordingManager,
didFireStartRecordingTrigger trigger: SensorTrigger)
/// Called when the recording manager fired a trigger that should stop recording.
///
/// - Parameters:
/// - recordingManager: The recording manager.
/// - trigger: The trigger.
func recordingManager(_ recordingManager: RecordingManager,
didFireStopRecordingTrigger trigger: SensorTrigger)
/// Called when recording manager creates a note trigger.
///
/// - Parameters:
/// - recordingManager: The recording manager.
/// - trigger: The trigger.
/// - sensor: The sensor associated with the note trigger.
/// - timestamp: The timestamp when the trigger fired.
func recordingManager(_ recordingManager: RecordingManager,
didFireNoteTrigger trigger: SensorTrigger,
forSensor sensor: Sensor,
atTimestamp timestamp: Int64)
/// Called by the recording manager during recording, to update with recording session timing
/// info.
///
/// - Parameters:
/// - recordingManager: The recording manager.
/// - hasRecordedForDuration: The duration of the recording session.
func recordingManager(_ recordingManager: RecordingManager,
hasRecordedForDuration duration: Int64)
/// Called by the recording manager when a sensor exceeded the maximum allowed trigger fire limit.
///
/// - Parameters:
/// - recordingManager: The recording manager.
/// - sensor: The sensor that the trigger fired for.
func recordingManager(_ recordingManager: RecordingManager,
didExceedTriggerFireLimitForSensor sensor: Sensor)
}
/// Expose a static property so any any class can see if recording is active.
public struct RecordingState {
/// Whether or not the recording manager is recording.
public static fileprivate(set) var isRecording = false
}
/// Manages sensor recorders, which record to the database and updates its listeners.
class RecordingManager: RecorderDelegate {
/// The recording manager delegate.
weak var delegate: RecordingManagerDelegate?
/// Whether or not the recording manager is recording. Setting this value will update all
/// recorders to either store to the database or not.
var isRecording = false {
didSet {
RecordingState.isRecording = isRecording
for recorder in recorders {
recorder.shouldStoreDataToDatabase = isRecording
}
}
}
/// True if any of the recorders has yet to record a data point since recording began, otherwise
/// false. Always returns false if a recording is not in progress.
var isRecordingMissingData: Bool {
guard isRecording else { return false }
for recorder in recorders where !recorder.hasRecordedOneDataPoint {
return true
}
return false
}
/// The recording start date.
var recordingStartDate: DataPoint.Millis?
/// The recording manager is ready when all sensors set to record are ready.
var isReady: Bool {
for recorder in recorders where recorder.sensor.state != .ready {
return false
}
return true
}
/// The recorders monitoring sensor data.
private var recorders = [Recorder]()
/// The sensors being recorded.
var recordingSensors: [Sensor] {
return recorders.map { $0.sensor }
}
/// The ID of the trial to record for.
private var trialID: String?
/// An array of snapshots for the currently observing sensors.
var sensorSnapshots: [SensorSnapshot] {
var snapshots = [SensorSnapshot]()
for recorder in self.recorders {
// Skip recorder if the sensor does not have proper user permission.
guard recorder.sensor.state == .ready else {
continue
}
// Skip recorder if no data point has been recorded.
guard let lastDataPoint = recorder.lastDataPoint else {
continue
}
let snapshot = SensorSnapshot()
snapshot.sensorSpec = SensorSpec(sensor: recorder.sensor)
snapshot.timestamp = lastDataPoint.x
snapshot.value = lastDataPoint.y
snapshots.append(snapshot)
}
return snapshots
}
private let sensorDataManager: SensorDataManager
// MARK: - Public
/// Designated initializer.
///
/// - Parameter sensorDataManager: The sensor data manager.
init(sensorDataManager: SensorDataManager) {
self.sensorDataManager = sensorDataManager
}
deinit {
UIApplication.shared.isIdleTimerDisabled = false
}
/// Saves recorded data. Should be called periodically during recording.
func save() {
sensorDataManager.savePrivateContext()
}
/// Returns a recorder for a sensor ID.
///
/// - Parameter sensorID: A sensor ID.
/// - Returns: A recorder.
func recorder(forSensorID sensorID: String) -> Recorder? {
return recorders.first(where: { $0.sensor.sensorId == sensorID })
}
/// Removes a recorder from the recording manager.
///
/// - Parameter recorder: The recorder to remove.
private func remove(recorder: Recorder) {
recorder.removeSensorListener()
if let index = recorders.firstIndex(where: { $0 == recorder }) {
recorders.remove(at: index)
}
}
// MARK: Listeners
/// Creates a recorder for `sensor` and begins updating the `listener` with data. If a listener is
/// added for a sensor that already has a recorder, the existing object will be removed and a new
/// one will be created.
///
/// - Parameters:
/// - sensor: The sensor to listen to data for.
/// - triggers: The triggers to fire for the sensor.
/// - block: The block to call to update the listener.
func addListener(forSensor sensor: Sensor,
triggers: [SensorTrigger],
using block: @escaping RecorderListener) {
if let sensorRecorder = recorder(forSensorID: sensor.sensorId) {
remove(recorder: sensorRecorder)
}
let aRecorder = Recorder(sensor: sensor,
delegate: self,
triggers: triggers,
listener: block,
sensorDataManager: sensorDataManager)
recorders.append(aRecorder)
}
/// Removes the recorder associated with a sensor.
///
/// - Parameter sensor: The sensor to remove the listener for.
func removeListener(for sensor: Sensor) throws {
guard let aRecorder = recorder(forSensorID: sensor.sensorId) else { return }
remove(recorder: aRecorder)
}
// MARK: Start/end recording
/// Starts recording, which will begin recording to the database. If called more than once, this
/// method does nothing. To commit the data call `endRecording()`.
func startRecording(trialID: String) {
guard !isRecording else { return }
self.trialID = trialID
recorders.forEach { $0.prepareForRecordingToDatabase() }
isRecording = true
recordingStartDate = Date().millisecondsSince1970
UIApplication.shared.isIdleTimerDisabled = true
}
/// Ends a recording, which will stop writing data to the database.
///
/// - Parameters:
/// - isCancelled: True if the recording was cancelled, otherwise false. Default is false.
/// - removeCancelledData: True if data from a cancelled recording should be removed, otherwise
/// false (data is left in the database). Only has impact if
/// `isCancelled` is true. Default is true.
func endRecording(isCancelled: Bool = false, removeCancelledData: Bool = true) {
isRecording = false
if !isCancelled {
sensorDataManager.savePrivateContext()
} else if removeCancelledData, let trialID = trialID {
// If cancelled, remove data.
sensorDataManager.removeData(forTrialID: trialID)
}
trialID = nil
recordingStartDate = nil
UIApplication.shared.isIdleTimerDisabled = false
recorders.forEach { $0.hasRecordedOneDataPoint = false }
}
// MARK: - Triggers
/// Adds a trigger for a sensor that is already being listened to.
///
/// - Parameters:
/// - trigger: The trigger to add.
/// - sensor: The sensor to add the trigger for.
func add(trigger: SensorTrigger, forSensor sensor: Sensor) {
guard let recorder = recorder(forSensorID: sensor.sensorId) else { return }
recorder.add(trigger: trigger)
}
/// Removes all triggers for all sensors.
func removeAllTriggers() {
for recorder in recorders {
recorder.removeAllTriggers()
}
}
/// Removes a trigger from a sensor.
///
/// - Parameters:
/// - trigger: The trigger to remove.
/// - sensor: The sensor to remove the trigger from.
private func remove(trigger: SensorTrigger, forSensor sensor: Sensor) {
guard let recorder = recorder(forSensorID: sensor.sensorId) else { return }
recorder.remove(trigger: trigger)
}
// MARK: - RecorderDelegate
func recorder(_ recorder: Recorder, didFireStartRecordingTrigger trigger: SensorTrigger) {
delegate?.recordingManager(self, didFireStartRecordingTrigger: trigger)
}
func recorder(_ recorder: Recorder, didFireStopRecordingTrigger trigger: SensorTrigger) {
delegate?.recordingManager(self, didFireStopRecordingTrigger: trigger)
}
func recorder(_ recorder: Recorder, didFireVisualTrigger trigger: SensorTrigger) {
delegate?.recordingManager(self, didFireVisualTrigger: trigger, forSensor: recorder.sensor)
}
func recorder(_ recorder: Recorder,
didFireNoteTrigger trigger: SensorTrigger,
at timestamp: Int64) {
delegate?.recordingManager(self,
didFireNoteTrigger: trigger,
forSensor: recorder.sensor,
atTimestamp: timestamp)
}
func recorderDidReceiveData(_ recorder: Recorder) {
guard isRecording, let recordingStartDate = recordingStartDate else { return }
let duration = Date().millisecondsSince1970 - recordingStartDate
delegate?.recordingManager(self, hasRecordedForDuration: duration)
}
func recorderTrialID(_ recorder: Recorder) -> String? {
return trialID
}
func recorder(_ recorder: Recorder, didExceedTriggerFireLimitForSensor sensor: Sensor) {
delegate?.recordingManager(self, didExceedTriggerFireLimitForSensor: sensor)
}
}
| apache-2.0 | 3fe7fe3a5545f70220cc29c1c0de4c0d | 34.404255 | 100 | 0.68149 | 4.937685 | false | false | false | false |
djschilling/SOPA-iOS | SOPA/helper/LogFileHandler.swift | 1 | 1594 | //
// LogFileHandler.swift
// SOPA
//
// Created by Raphael Schilling on 13.09.18.
// Copyright © 2018 David Schilling. All rights reserved.
//
import Foundation
struct LogFileHandler: TextOutputStream {
/// Appends the given string to the stream.
mutating func write(_ string: String) {
let paths = FileManager.default.urls(for: .documentDirectory, in: .allDomainsMask)
let documentDirectoryPath = paths.first!
let log = documentDirectoryPath.appendingPathComponent("log.txt")
do {
let handle = try FileHandle(forWritingTo: log)
handle.seekToEndOfFile()
handle.write(string.data(using: .utf8)!)
handle.closeFile()
} catch {
print(error.localizedDescription)
do {
try string.data(using: .utf8)?.write(to: log)
} catch {
print(error.localizedDescription)
}
}
}
func readLog() -> String{
let file = "log.txt" //this is the file. we will write to and read from it
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
do {
let text = try String(contentsOf: fileURL, encoding: .utf8)
return text
}
catch {
print("File not found")
}
}
return "File not found"
}
static var logger: LogFileHandler = LogFileHandler()
}
| apache-2.0 | b6986dd00e41fb73a2c626f8b923fd2b | 29.056604 | 99 | 0.562461 | 4.798193 | false | false | false | false |
tadija/AEImage | Example/AEImageExample/ExampleImageViewController.swift | 1 | 1540 | /**
* https://github.com/tadija/AEImage
* Copyright © 2016-2019 Marko Tadić
* Licensed under the MIT license
*/
import UIKit
import AEImage
class ExampleImageViewController: ImageMotionViewController {
override var prefersStatusBarHidden: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
imageScrollView.displayMode = .fillHeight
imageScrollView.infiniteScroll = .horizontal
isMotionEnabled = true
motionSensitivity = 1.5
image = #imageLiteral(resourceName: "demo")
}
@IBAction func didRecognizeDoubleTapGesture(_ sender: UITapGestureRecognizer) {
let imageScrollView = self.imageScrollView
imageScrollView.isInfiniteScrollEnabled = false
UIView.animate(
withDuration: 0.25,
delay: 0,
options: [
.allowUserInteraction, .beginFromCurrentState, .curveEaseOut,
],
animations: {
let minScale = imageScrollView.minimumZoomScale
if imageScrollView.zoomScale > minScale {
imageScrollView.setZoomScale(minScale, animated: false)
} else {
let point = sender.location(in: imageScrollView.stackView)
let rect = CGRect(origin: point, size: .zero)
imageScrollView.zoom(to: rect, animated: false)
}
}) { _ in
imageScrollView.isInfiniteScrollEnabled = true
}
}
}
| mit | c3a04ef006c8e98bc99283fbdfc5c686 | 29.156863 | 83 | 0.607282 | 5.572464 | false | false | false | false |
konduruvijaykumar/ios-sample-apps | GMapsLocationPlacesDemo/GMapsLocationPlacesDemo/ViewController.swift | 1 | 8313 | //
// ViewController.swift
// GMapsLocationPlacesDemo
//
// Created by Vijay Konduru on 14/02/17.
// Copyright © 2017 PJay. All rights reserved.
//
//https://developers.google.com/places/web-service/search
//https://developers.google.com/places/web-service/supported_types
//http://stackoverflow.com/questions/29398678/encoding-url-using-swift-code
//http://stackoverflow.com/questions/24879659/how-to-encode-a-url-in-swift
//http://stackoverflow.com/questions/24551816/swift-encode-url
//http://stackoverflow.com/questions/40939037/how-to-change-google-maps-marker-color-when-selected-in-swift
// This app did not work really well, in order keep track of possibilities tried out. I am leaving this as it is and making a proper attempt
import UIKit
import GoogleMaps
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func loadView() {
// IMP: atributes in json for nearby places
// latitude: results -> geometry -> location -> lat
// longitude: results -> geometry -> location -> lat
// title: results -> name
let camera = GMSCameraPosition.camera(withLatitude: 12.94982,longitude: 77.64302, zoom: 12);
let mapView = GMSMapView.map(withFrame: .zero, camera: camera);
let marker = GMSMarker();
marker.position = camera.target;
marker.title = "Embassy Golf Links";// name in json
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.icon = GMSMarker.markerImage(with: UIColor.cyan);
marker.map = mapView;
self.view = mapView;
loadNearByPlaceMarkers(mapView: mapView);
}
func loadNearByPlaceMarkers(mapView: GMSMapView){
let config = URLSessionConfiguration.default; // Session Configuration
let session = URLSession(configuration: config); // Load configuration into Session
let myUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=12.94982,77.64302&radius=3000&type=bank|atm&name=citi|icici|sbi|axis|hdfc&key=YOUR_SERVER_API_KEY";
//let urlWithQueryParam = myUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed);
let urlWithQueryParam = myUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed);
//let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?")!
//let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=12.94982,77.64302&radius=5000&type=bank|atm&name=citi|boa|chase&key=YOUR_SERVER_API_KEY")!;
let url = URL(string: urlWithQueryParam!)!;
//var request = URLRequest.init(url: url);
//request.httpMethod = "GET";
//request.addValue("12.94982,77.64302", forHTTPHeaderField: "location");
//request.addValue("50000", forHTTPHeaderField: "radius");
//request.addValue("bank|atm", forHTTPHeaderField: "type");
//request.addValue("citi|boa|chase", forHTTPHeaderField: "name");
//request.addValue("YOUR_SERVER_API_KEY", forHTTPHeaderField: "key");
let task = session.dataTask(with: url, completionHandler:
{
(data, response, error) in
// https://www.youtube.com/watch?v=LQ0he_I5_4g
// http://stackoverflow.com/questions/30206983/gmsthreadexception-occur-when-displaying-gmsmarkers-on-ios-simulator
if(error != nil) {
//print(error!.localizedDescription);
print("error = \(error)");
}else{
// Read the JSON
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary;
if let mainJSON = json {
let resultsArray = mainJSON["results"] as? [AnyObject];
//print("\(resultsArray)!");
for resultsJson in resultsArray!{
let name = resultsJson["name"] as! String;
//let icon = resultsJson["icon"] as! String;
//print(name,icon);
let geometry = resultsJson["geometry"] as AnyObject;
let location = geometry["location"] as AnyObject;
let lat = location["lat"] as! Double;
let lng = location["lng"] as! Double;
//print(name, "\t", icon, "\t", lat, "\t", lng);
DispatchQueue.main.async {
let marker = GMSMarker();
marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lng);
marker.appearAnimation = kGMSMarkerAnimationPop;
//marker.icon = URL(string: icon)!;//self.downloadMarkerImage(iconUrl: icon, marker: marker);
marker.title = name;
marker.map = mapView;
}
}
}
} catch {
print("Something Wrong Happened")
}
}
}
);
task.resume();
/**
// Adding Many markers or nearby locations in map
let camera = GMSCameraPosition.camera(withLatitude: 12.971891,longitude: 77.641154, zoom: 18);
let mapView = GMSMapView.map(withFrame: .zero, camera: camera);
let marker = GMSMarker();
marker.position = camera.target;
marker.title = "Indiranagar";
marker.snippet = "Bengaluru, KA, India";
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = mapView;
view = mapView;
let marker1 = GMSMarker();
marker1.position = CLLocationCoordinate2D(latitude: 12.972249, longitude: 77.640746);
marker1.appearAnimation = kGMSMarkerAnimationPop;
marker1.map = mapView;
let marker2 = GMSMarker();
marker2.position = CLLocationCoordinate2D(latitude: 12.971964, longitude: 77.642140);
marker2.appearAnimation = kGMSMarkerAnimationPop;
marker2.map = mapView;
*/
}
// Only issues not working
/*
func downloadMarkerImage(iconUrl: String, marker: GMSMarker) -> UIImage {
//print(iconUrl);
let config = URLSessionConfiguration.default; // Session Configuration
let session = URLSession(configuration: config); // Load configuration into Session
//let formattedUrl = url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed);//Not required
let url = URL(string: iconUrl)!;
var markerImage = #imageLiteral(resourceName: "default_marker.png");
let task = session.downloadTask(with: url, completionHandler: {
(data, response, error) in
if(nil != error){
print("Error:: ",error!);
}else{
if(nil != data){
let imagedata = data as? Data;
markerImage = UIImage(data: imagedata!)!;
}
}
})
task.resume();
return markerImage;
}
*/
}
// Don't known how this work, what i have done can be wrong
/*
extension UIImage {
func downloadMarkerImage(from url: String, marker: GMSMarker) {
let urlRequest = URLRequest(url: URL(string: url)!);
let task = URLSession.shared.dataTask(with: urlRequest, completionHandler: {
(data, response, error) in
if(nil == error){
marker.icon = UIImage(data: data!);
}
});
task.resume();
}
}
*/
| apache-2.0 | f20f6a80aafa889f8edac83de9acf460 | 44.173913 | 194 | 0.576877 | 4.785262 | false | true | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTManufacturerNameString.swift | 1 | 1806 | //
// GATTManufacturerNameString.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/21/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Manufacturer Name String
The value of this characteristic is a UTF-8 string representing the name of the manufacturer of the device.
[Manufacturer Name String](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.manufacturer_name_string.xml)
*/
@frozen
public struct GATTManufacturerNameString: GATTCharacteristic {
public static var uuid: BluetoothUUID { return .manufacturerNameString }
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init?(data: Data) {
guard let rawValue = String(data: data, encoding: .utf8)
else { return nil }
self.init(rawValue: rawValue)
}
public var data: Data {
return Data(rawValue.utf8)
}
}
extension GATTManufacturerNameString: Equatable {
public static func == (lhs: GATTManufacturerNameString, rhs: GATTManufacturerNameString) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension GATTManufacturerNameString: CustomStringConvertible {
public var description: String {
return rawValue
}
}
extension GATTManufacturerNameString: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(rawValue: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(rawValue: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(rawValue: value)
}
}
| mit | b880d0d296d962bd7a628a492cdaaa83 | 22.75 | 156 | 0.658726 | 5.084507 | false | false | false | false |
abarnert/swiftprimes | primes6.swift | 1 | 1451 | // Because of rdar://problem/17127940 we cannot use qualified names
// (https://devforums.apple.com/message/976286#976286), but we can still
// use modules, right? Well, no. If you build itertools with -emit-module
// and import it here, the names aren't in the main namespace, and also
// aren't in the itertools namespace, so no matter which way you write
// things you'll get either a compile error or a link error. If you
// instead try to do what Xcode does and just compile all the source
// files together, you'll get a compiler error because there's
// top-level code in a file that isn't called main.swift in a multi-file
// compile job. (Seriously...) So, this seems like a dead end until they
// fix one of these problems.
//import itertools
func make_isprime() -> (Int -> Bool) {
var memo = Int[]()
func isprime(n: Int) -> Bool {
for prime in memo {
if n % prime == 0 { return false }
}
memo.append(n)
return true
}
return isprime
}
func intifyarg1() -> Int? {
if C_ARGC == 2 {
let limitstr = String.fromCString(C_ARGV[1])
if let limit = limitstr.toInt() {
return limit
}
}
return nil
}
if let limit = intifyarg1() {
let primes = filter(count(start: 2), make_isprime())
let limited = takewhile(primes, { $0 <= limit })
let s = " ".join(map(limited, { $0.description }))
println("\(s)")
} else {
println("\(C_ARGV[0]) LIMIT")
}
| mit | 07888a6c9e66b6034ba524088a80e4b3 | 31.977273 | 73 | 0.640248 | 3.504831 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentityTests/Unit/Categories/CGImage+StripeIdentityUnitTest.swift | 1 | 8091 | //
// CGImage+StripeIdentityUnitTest.swift
// StripeIdentityTests
//
// Created by Mel Ludowise on 12/10/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import CoreImage
import XCTest
@testable import StripeIdentity
final class CGImage_StripeIdentityUnitTest: XCTestCase {
let imageSizeLandscape = CGSize(width: 1600, height: 900)
let imageSizePortrait = CGSize(width: 900, height: 1600)
private var cgImageLandscape: CGImage!
private var cgImagePortrait: CGImage!
override func setUp() {
super.setUp()
cgImageLandscape = makeImage(ofSize: imageSizeLandscape)
cgImagePortrait = makeImage(ofSize: imageSizePortrait)
}
// Tests that the padding is based on width when > height
func testComputePaddingLandscapeMaxImageWidthOrHeight() {
// Equivalent to pixel coordinates (200, 200, 400, 200)
// for landscape image
let normalizedRegion = CGRect(x: 0.125, y: 0.2222, width: 0.25, height: 0.2222)
let padding = cgImageLandscape.computePixelPadding(
padding: 0.08,
normalizedRegion: normalizedRegion,
computationMethod: .maxImageWidthOrHeight
)
// Actual padding should be 0.08 * 1600 = 128px
XCTAssertEqual(padding, 128, accuracy: 0.5)
}
// Tests that the padding is based on height when > width
func testComputePaddingPortraitMaxImageWidthOrHeight() {
// Equivalent to pixel coordinates (200, 200, 200, 400)
// for portrait image
let normalizedRegion = CGRect(x: 0.2222, y: 0.125, width: 0.2222, height: 0.25)
let padding = cgImagePortrait.computePixelPadding(
padding: 0.08,
normalizedRegion: normalizedRegion,
computationMethod: .maxImageWidthOrHeight
)
// Actual padding should be 0.08 * 1600 = 128px
XCTAssertEqual(padding, 128, accuracy: 0.5)
}
func testComputePaddingLandscapeRegionWidth() {
// Equivalent to pixel coordinates (200, 200, 400, 200)
// for landscape image
let normalizedRegion = CGRect(x: 0.125, y: 0.2222, width: 0.25, height: 0.2222)
let padding = cgImageLandscape.computePixelPadding(
padding: 0.08,
normalizedRegion: normalizedRegion,
computationMethod: .regionWidth
)
// Actual padding should be 0.08 * 400 = 32px
XCTAssertEqual(padding, 32, accuracy: 0.5)
}
func testComputePaddingPortraitRegionWidth() {
// Equivalent to pixel coordinates (200, 200, 200, 400)
// for portrait image
let normalizedRegion = CGRect(x: 0.2222, y: 0.125, width: 0.2222, height: 0.25)
let padding = cgImagePortrait.computePixelPadding(
padding: 0.08,
normalizedRegion: normalizedRegion,
computationMethod: .regionWidth
)
// Actual padding should be 0.08 * 200 = 16px
XCTAssertEqual(padding, 16, accuracy: 0.5)
}
func testComputePixelCropArea() {
// Equivalent to pixel coordinates (200, 200, 200, 200)
// for landscape image
let normalizedRegion = CGRect(x: 0.125, y: 0.2222, width: 0.125, height: 0.2222)
let pixelPadding: CGFloat = 100
let expectedCropArea = CGRect(x: 100, y: 100, width: 400, height: 400)
let actualCropArea = cgImageLandscape.computePixelCropArea(
normalizedRegion: normalizedRegion,
pixelPadding: pixelPadding
)
XCTAssertEqual(round(actualCropArea.minX), expectedCropArea.minX)
XCTAssertEqual(round(actualCropArea.minY), expectedCropArea.minY)
XCTAssertEqual(round(actualCropArea.width), expectedCropArea.width)
XCTAssertEqual(round(actualCropArea.height), expectedCropArea.height)
}
// Tests when an image's width and height are bigger than the max dimensions
func testComputeScaleTooBigAllDimensions() {
let maxDimension = CGSize(width: 800, height: 800)
let scale = cgImageLandscape.computeScale(maxPixelDimension: maxDimension)
// Actual scale should be 800 / 1600 = 0.5
XCTAssertEqual(scale, 0.5)
}
// Tests when an image's width is bigger than max dimension, but not height
func testComputeScaleTooBigWidth() {
let maxDimension = CGSize(width: 1000, height: 1000)
let scale = cgImageLandscape.computeScale(maxPixelDimension: maxDimension)
// Actual scale should be 1000 / 1600 = 0.625
XCTAssertEqual(scale, 0.625)
}
// Tests when an image's height is bigger than max dimension, but not height
func testComputeScaleTooBigHeight() {
let maxDimension = CGSize(width: 1000, height: 1000)
let scale = cgImagePortrait.computeScale(maxPixelDimension: maxDimension)
// Actual scale should be 1000 / 1600 = 0.625
XCTAssertEqual(scale, 0.625)
}
// Tests when an image is the exact size of the max dimension
func testComputeScaleExactSize() {
let maxDimension = imageSizeLandscape
let scale = cgImageLandscape.computeScale(maxPixelDimension: maxDimension)
// Actual scale should be 1
XCTAssertEqual(scale, 1)
}
// Tests when an image is smaller than the max dimension
func testComputeScaleSmaller() throws {
let maxDimension = CGSize(width: 2000, height: 2000)
let scaledImage = try cgImageLandscape.scaledDown(toMaxPixelDimension: maxDimension)
XCTAssertEqual(CGFloat(scaledImage.width), imageSizeLandscape.width)
XCTAssertEqual(CGFloat(scaledImage.height), imageSizeLandscape.height)
}
// Tests when an image's width and height are bigger than the max dimensions
func testScaleImageTooBigAllDimensions() throws {
let maxDimension = CGSize(width: 800, height: 800)
let scaledImage = try cgImageLandscape.scaledDown(toMaxPixelDimension: maxDimension)
XCTAssertEqual(CGFloat(scaledImage.width), 800)
XCTAssertEqual(CGFloat(scaledImage.height), 450)
}
// Tests when an image's width is bigger than max dimension, but not height
func testScaleImageTooBigWidth() throws {
let maxDimension = CGSize(width: 1000, height: 1000)
let scaledImage = try cgImageLandscape.scaledDown(toMaxPixelDimension: maxDimension)
XCTAssertEqual(CGFloat(scaledImage.width), 1000)
XCTAssertEqual(CGFloat(scaledImage.height), 562)
}
// Tests when an image's height is bigger than max dimension, but not height
func testScaleImageTooBigHeight() throws {
let maxDimension = CGSize(width: 1000, height: 1000)
let scaledImage = try cgImagePortrait.scaledDown(toMaxPixelDimension: maxDimension)
XCTAssertEqual(CGFloat(scaledImage.width), 562)
XCTAssertEqual(CGFloat(scaledImage.height), 1000)
}
// Tests when an image is the exact size of the max dimension
func testScaleImageExactSize() throws {
let maxDimension = imageSizeLandscape
let scaledImage = try cgImageLandscape.scaledDown(toMaxPixelDimension: maxDimension)
XCTAssertEqual(CGFloat(scaledImage.width), imageSizeLandscape.width)
XCTAssertEqual(CGFloat(scaledImage.height), imageSizeLandscape.height)
}
// Tests when an image is smaller than the max dimension
func testScaleImageSmaller() throws {
let maxDimension = CGSize(width: 2000, height: 2000)
let scaledImage = try cgImageLandscape.scaledDown(toMaxPixelDimension: maxDimension)
XCTAssertEqual(CGFloat(scaledImage.width), imageSizeLandscape.width)
XCTAssertEqual(CGFloat(scaledImage.height), imageSizeLandscape.height)
}
}
extension CGImage_StripeIdentityUnitTest {
fileprivate func makeImage(ofSize size: CGSize) -> CGImage {
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let uiImage = UIGraphicsImageRenderer(size: size, format: format).image { context in
context.fill(CGRect(origin: .zero, size: size))
}
return uiImage.cgImage!
}
}
| mit | ca7e7a0f3a6d6d9bcab37d002037af46 | 37.708134 | 92 | 0.685414 | 4.941967 | false | true | false | false |
FraDeliro/ISaMaterialLogIn | Example/Pods/Material/Sources/iOS/Switch.swift | 1 | 17613 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(SwitchStyle)
public enum SwitchStyle: Int {
case light
case dark
}
@objc(SwitchState)
public enum SwitchState: Int {
case on
case off
}
@objc(SwitchSize)
public enum SwitchSize: Int {
case small
case medium
case large
}
@objc(SwitchDelegate)
public protocol SwitchDelegate {
/**
A Switch delegate method for state changes.
- Parameter control: Switch control.
- Parameter state: SwitchState value.
*/
func switchDidChangeState(control: Switch, state: SwitchState)
}
open class Switch: UIControl {
/// Will layout the view.
open var willLayout: Bool {
return 0 < width && 0 < height && nil != superview
}
/// An internal reference to the switchState public property.
fileprivate var internalSwitchState = SwitchState.off
/// Track thickness.
fileprivate var trackThickness: CGFloat = 0
/// Button diameter.
fileprivate var buttonDiameter: CGFloat = 0
/// Position when in the .on state.
fileprivate var onPosition: CGFloat = 0
/// Position when in the .off state.
fileprivate var offPosition: CGFloat = 0
/// The bounce offset when animating.
fileprivate var bounceOffset: CGFloat = 3
/// An Optional delegation method.
open weak var delegate: SwitchDelegate?
/// Indicates if the animation should bounce.
@IBInspectable
open var isBounceable = true {
didSet {
bounceOffset = isBounceable ? 3 : 0
}
}
/// Button on color.
@IBInspectable
open var buttonOnColor = Color.clear {
didSet {
styleForState(state: switchState)
}
}
/// Button off color.
@IBInspectable
open var buttonOffColor = Color.clear {
didSet {
styleForState(state: switchState)
}
}
/// Track on color.
@IBInspectable
open var trackOnColor = Color.clear {
didSet {
styleForState(state: switchState)
}
}
/// Track off color.
@IBInspectable
open var trackOffColor = Color.clear {
didSet {
styleForState(state: switchState)
}
}
/// Button on disabled color.
@IBInspectable
open var buttonOnDisabledColor = Color.clear {
didSet {
styleForState(state: switchState)
}
}
/// Track on disabled color.
@IBInspectable
open var trackOnDisabledColor = Color.clear {
didSet {
styleForState(state: switchState)
}
}
/// Button off disabled color.
@IBInspectable
open var buttonOffDisabledColor = Color.clear {
didSet {
styleForState(state: switchState)
}
}
/// Track off disabled color.
@IBInspectable
open var trackOffDisabledColor = Color.clear {
didSet {
styleForState(state: switchState)
}
}
/// Track view reference.
open fileprivate(set) var track: UIView {
didSet {
prepareTrack()
}
}
/// Button view reference.
open fileprivate(set) var button: FabButton {
didSet {
prepareButton()
}
}
@IBInspectable
open override var isEnabled: Bool {
didSet {
styleForState(state: internalSwitchState)
}
}
/// A boolean indicating if the switch is on or not.
@IBInspectable
public var isOn: Bool {
get {
return .on == internalSwitchState
}
set(value) {
updateSwitchState(state: .on, animated: true, isTriggeredByUserInteraction: false)
}
}
/// Switch state.
open var switchState: SwitchState {
get {
return internalSwitchState
}
set(value) {
if value != internalSwitchState {
internalSwitchState = value
}
}
}
/// Switch style.
open var switchStyle = SwitchStyle.dark {
didSet {
switch switchStyle {
case .light:
buttonOnColor = Color.blue.darken2
trackOnColor = Color.blue.lighten3
buttonOffColor = Color.blueGrey.lighten4
trackOffColor = Color.grey.lighten3
buttonOnDisabledColor = Color.grey.lighten2
trackOnDisabledColor = Color.grey.lighten3
buttonOffDisabledColor = Color.grey.lighten2
trackOffDisabledColor = Color.grey.lighten3
case .dark:
buttonOnColor = Color.blue.lighten1
trackOnColor = Color.blue.lighten2.withAlphaComponent(0.5)
buttonOffColor = Color.grey.lighten3
trackOffColor = Color.blueGrey.lighten4.withAlphaComponent(0.5)
buttonOnDisabledColor = Color.grey.darken3
trackOnDisabledColor = Color.grey.lighten1.withAlphaComponent(0.2)
buttonOffDisabledColor = Color.grey.darken3
trackOffDisabledColor = Color.grey.lighten1.withAlphaComponent(0.2)
}
}
}
/// Switch size.
open var switchSize = SwitchSize.medium {
didSet {
switch switchSize {
case .small:
trackThickness = 12
buttonDiameter = 18
case .medium:
trackThickness = 18
buttonDiameter = 24
case .large:
trackThickness = 24
buttonDiameter = 32
}
frame.size = intrinsicContentSize
}
}
open override var intrinsicContentSize: CGSize {
switch switchSize {
case .small:
return CGSize(width: 24, height: 24)
case .medium:
return CGSize(width: 30, height: 30)
case .large:
return CGSize(width: 36, height: 36)
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
track = UIView()
button = FabButton()
super.init(coder: aDecoder)
prepare()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init(state:style:size:) initializer, or set the CGRect
to CGRectNull.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
track = UIView()
button = FabButton()
super.init(frame: frame)
prepare()
}
/**
An initializer that sets the state, style, and size of the Switch instance.
- Parameter state: A SwitchState value.
- Parameter style: A SwitchStyle value.
- Parameter size: A SwitchSize value.
*/
public init(state: SwitchState = .off, style: SwitchStyle = .dark, size: SwitchSize = .medium) {
track = UIView()
button = FabButton()
super.init(frame: .zero)
prepare()
prepareSwitchState(state: state)
prepareSwitchStyle(style: style)
prepareSwitchSize(size: size)
}
open override func layoutSubviews() {
super.layoutSubviews()
guard willLayout else {
return
}
reload()
}
/// Reloads the view.
open func reload() {
let w: CGFloat = intrinsicContentSize.width
let px: CGFloat = (width - w) / 2
track.frame = CGRect(x: px, y: (height - trackThickness) / 2, width: w, height: trackThickness)
track.cornerRadius = min(w, trackThickness) / 2
button.frame = CGRect(x: px, y: (height - buttonDiameter) / 2, width: buttonDiameter, height: buttonDiameter)
onPosition = width - px - buttonDiameter
offPosition = px
if .on == internalSwitchState {
button.x = onPosition
}
}
open override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
styleForState(state: internalSwitchState)
}
/**
Toggle the Switch state, if On will be Off, and if Off will be On.
- Parameter completion: An Optional completion block.
*/
open func toggle(completion: ((Switch) -> Void)? = nil) {
updateSwitchState(state: .on == internalSwitchState ? .off : .on, animated: true, isTriggeredByUserInteraction: false, completion: completion)
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard track.frame.contains(layer.convert(touches.first!.location(in: self), from: layer)) else {
return
}
updateSwitchState(state: .on == internalSwitchState ? .on : .off, animated: true, isTriggeredByUserInteraction: true)
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
contentScaleFactor = Screen.scale
prepareTrack()
prepareButton()
prepareSwitchState()
prepareSwitchStyle()
prepareSwitchSize()
}
}
extension Switch {
/**
Set the switchState property with an option to animate.
- Parameter state: The SwitchState to set.
- Parameter animated: A Boolean indicating to set the animation or not.
- Parameter completion: An Optional completion block.
*/
open func setSwitchState(state: SwitchState, animated: Bool = true, completion: ((Switch) -> Void)? = nil) {
updateSwitchState(state: state, animated: animated, isTriggeredByUserInteraction: false, completion: completion)
}
/**
Set the switchState property with an option to animate.
- Parameter state: The SwitchState to set.
- Parameter animated: A Boolean indicating to set the animation or not.
- Parameter isTriggeredByUserInteraction: A boolean indicating whether the
state was changed by a user interaction, true if yes, false otherwise.
- Parameter completion: An Optional completion block.
*/
fileprivate func updateSwitchState(state: SwitchState, animated: Bool, isTriggeredByUserInteraction: Bool, completion: ((Switch) -> Void)? = nil) {
guard isEnabled && internalSwitchState != state else {
return
}
internalSwitchState = state
if animated {
animateToState(state: state) { [weak self] _ in
guard isTriggeredByUserInteraction else {
return
}
guard let s = self else {
return
}
s.sendActions(for: .valueChanged)
completion?(s)
s.delegate?.switchDidChangeState(control: s, state: s.internalSwitchState)
}
} else {
button.x = .on == state ? self.onPosition : self.offPosition
styleForState(state: state)
guard isTriggeredByUserInteraction else {
return
}
sendActions(for: .valueChanged)
completion?(self)
delegate?.switchDidChangeState(control: self, state: internalSwitchState)
}
}
}
extension Switch {
/**
Updates the coloring for the enabled state.
- Parameter state: SwitchState.
*/
fileprivate func updateColorForState(state: SwitchState) {
if .on == state {
button.backgroundColor = buttonOnColor
track.backgroundColor = trackOnColor
} else {
button.backgroundColor = buttonOffColor
track.backgroundColor = trackOffColor
}
}
/**
Updates the coloring for the disabled state.
- Parameter state: SwitchState.
*/
fileprivate func updateColorForDisabledState(state: SwitchState) {
if .on == state {
button.backgroundColor = buttonOnDisabledColor
track.backgroundColor = trackOnDisabledColor
} else {
button.backgroundColor = buttonOffDisabledColor
track.backgroundColor = trackOffDisabledColor
}
}
/**
Updates the style based on the state.
- Parameter state: The SwitchState to set the style to.
*/
fileprivate func styleForState(state: SwitchState) {
if isEnabled {
updateColorForState(state: state)
} else {
updateColorForDisabledState(state: state)
}
}
}
extension Switch {
/**
Set the switchState property with an animate.
- Parameter state: The SwitchState to set.
- Parameter completion: An Optional completion block.
*/
fileprivate func animateToState(state: SwitchState, completion: ((Switch) -> Void)? = nil) {
isUserInteractionEnabled = false
UIView.animate(withDuration: 0.15,
delay: 0.05,
options: [.curveEaseIn, .curveEaseOut],
animations: { [weak self] in
guard let s = self else {
return
}
s.button.x = .on == state ? s.onPosition + s.bounceOffset : s.offPosition - s.bounceOffset
s.styleForState(state: state)
}) { [weak self] _ in
UIView.animate(withDuration: 0.15,
animations: { [weak self] in
guard let s = self else {
return
}
s.button.x = .on == state ? s.onPosition : s.offPosition
}) { [weak self] _ in
guard let s = self else {
return
}
s.isUserInteractionEnabled = true
completion?(s)
}
}
}
}
extension Switch {
/**
Handle the TouchUpOutside and TouchCancel events.
- Parameter sender: A UIButton.
- Parameter event: A UIEvent.
*/
@objc
fileprivate func handleTouchUpOutsideOrCanceled(sender: FabButton, event: UIEvent) {
guard let v = event.touches(for: sender)?.first else {
return
}
let q: CGFloat = sender.x + v.location(in: sender).x - v.previousLocation(in: sender).x
updateSwitchState(state: q > (width - button.width) / 2 ? .on : .off, animated: true, isTriggeredByUserInteraction: true)
}
/// Handles the TouchUpInside event.
@objc
fileprivate func handleTouchUpInside() {
updateSwitchState(state: isOn ? .off : .on, animated: true, isTriggeredByUserInteraction: true)
}
/**
Handle the TouchDragInside event.
- Parameter sender: A UIButton.
- Parameter event: A UIEvent.
*/
@objc
fileprivate func handleTouchDragInside(sender: FabButton, event: UIEvent) {
guard let v = event.touches(for: sender)?.first else {
return
}
let q: CGFloat = max(min(sender.x + v.location(in: sender).x - v.previousLocation(in: sender).x, onPosition), offPosition)
guard q != sender.x else {
return
}
sender.x = q
}
}
extension Switch {
/// Prepares the track.
fileprivate func prepareTrack() {
addSubview(track)
}
/// Prepares the button.
fileprivate func prepareButton() {
button.addTarget(self, action: #selector(handleTouchUpInside), for: .touchUpInside)
button.addTarget(self, action: #selector(handleTouchDragInside), for: .touchDragInside)
button.addTarget(self, action: #selector(handleTouchUpOutsideOrCanceled), for: .touchCancel)
button.addTarget(self, action: #selector(handleTouchUpOutsideOrCanceled), for: .touchUpOutside)
addSubview(button)
}
/**
Prepares the switchState property. This is used mainly to allow
init to set the state value and have an effect.
- Parameter state: The SwitchState to set.
*/
fileprivate func prepareSwitchState(state: SwitchState = .off) {
updateSwitchState(state: state, animated: false, isTriggeredByUserInteraction: false)
}
/**
Prepares the switchStyle property. This is used mainly to allow
init to set the state value and have an effect.
- Parameter style: The SwitchStyle to set.
*/
fileprivate func prepareSwitchStyle(style: SwitchStyle = .light) {
switchStyle = style
}
/**
Prepares the switchSize property. This is used mainly to allow
init to set the size value and have an effect.
- Parameter size: The SwitchSize to set.
*/
fileprivate func prepareSwitchSize(size: SwitchSize = .medium) {
switchSize = size
}
}
| mit | 246c3d88021b3fb489845f1eea204e78 | 29.107692 | 151 | 0.646227 | 4.571243 | false | false | false | false |
trill-lang/trill | Sources/AST/Operators.swift | 2 | 5568 | ///
/// Operators.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import Foundation
import Source
public enum Associativity {
case left, right, none
}
public enum BuiltinOperator: String, CustomStringConvertible {
case plus = "+"
case minus = "-"
case star = "*"
case divide = "/"
case mod = "%"
case assign = "="
case equalTo = "=="
case notEqualTo = "!="
case lessThan = "<"
case lessThanOrEqual = "<="
case greaterThan = ">"
case greaterThanOrEqual = ">="
case and = "&&"
case or = "||"
case xor = "^"
case ampersand = "&"
case bitwiseOr = "|"
case not = "!"
case bitwiseNot = "~"
case leftShift = "<<"
case rightShift = ">>"
case plusAssign = "+="
case minusAssign = "-="
case timesAssign = "*="
case divideAssign = "/="
case modAssign = "%="
case andAssign = "&="
case orAssign = "|="
case xorAssign = "^="
case rightShiftAssign = ">>="
case leftShiftAssign = "<<="
public var isPrefix: Bool {
return self == .bitwiseNot || self == .not ||
self == .minus || self == .ampersand ||
self == .star
}
public var isInfix: Bool {
return self != .bitwiseNot && self != .not
}
public var isCompoundAssign: Bool {
return self.associatedOp != nil
}
public var isAssign: Bool {
return self.isCompoundAssign || self == .assign
}
public var associatedOp: BuiltinOperator? {
switch self {
case .modAssign: return .mod
case .plusAssign: return .plus
case .timesAssign: return .star
case .divideAssign: return .divide
case .minusAssign: return .minus
case .leftShiftAssign: return .leftShift
case .rightShiftAssign: return .rightShift
case .andAssign: return .and
case .orAssign: return .or
case .xorAssign: return .xor
default: return nil
}
}
public var infixPrecedence: Int {
switch self {
case .leftShift: return 160
case .rightShift: return 160
case .star: return 150
case .divide: return 150
case .mod: return 150
case .ampersand: return 150
case .plus: return 140
case .minus: return 140
case .xor: return 140
case .bitwiseOr: return 140
case .equalTo: return 130
case .notEqualTo: return 130
case .lessThan: return 130
case .lessThanOrEqual: return 130
case .greaterThan: return 130
case .greaterThanOrEqual: return 130
case .and: return 120
case .or: return 110
case .assign: return 90
case .plusAssign: return 90
case .minusAssign: return 90
case .timesAssign: return 90
case .divideAssign: return 90
case .modAssign: return 90
case .andAssign: return 90
case .orAssign: return 90
case .xorAssign: return 90
case .rightShiftAssign: return 90
case .leftShiftAssign: return 90
// prefix-only
case .not: return 999
case .bitwiseNot: return 999
}
}
public var description: String { return self.rawValue }
}
public class PrefixOperatorExpr: Expr {
public let op: BuiltinOperator
public let opRange: SourceRange?
public let rhs: Expr
public init(op: BuiltinOperator, rhs: Expr, opRange: SourceRange? = nil, sourceRange: SourceRange? = nil) {
self.rhs = rhs
self.op = op
self.opRange = opRange
super.init(sourceRange: sourceRange)
}
public func typeForArgType(_ argType: DataType) -> DataType? {
switch (self.op, argType) {
case (.minus, .int): return argType
case (.minus, .floating): return argType
case (.star, .pointer(let type)): return type
case (.not, .bool): return .bool
case (.ampersand, let type): return .pointer(type: type)
case (.bitwiseNot, .int): return argType
default: return nil
}
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["operator"] = "\(op)"
return superAttrs
}
}
public class InfixOperatorExpr: Expr {
public let op: BuiltinOperator
public let opRange: SourceRange?
public let lhs: Expr
public let rhs: Expr
public var decl: OperatorDecl? = nil
public init(op: BuiltinOperator, lhs: Expr, rhs: Expr, opRange: SourceRange? = nil, sourceRange: SourceRange? = nil) {
self.lhs = lhs
self.op = op
self.opRange = opRange
self.rhs = rhs
super.init(sourceRange: sourceRange)
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["operator"] = "\(op)"
if let decl = decl {
superAttrs["decl"] = decl.formattedName
}
return superAttrs
}
}
public class OperatorDecl: FuncDecl {
public let op: BuiltinOperator
public let opRange: SourceRange?
public init(op: BuiltinOperator,
args: [ParamDecl],
genericParams: [GenericParamDecl],
returnType: TypeRefExpr,
body: CompoundStmt?,
modifiers: [DeclModifier],
opRange: SourceRange? = nil,
sourceRange: SourceRange? = nil) {
self.op = op
self.opRange = opRange
super.init(name: Identifier(name: "\(op)"),
returnType: returnType,
args: args,
genericParams: genericParams,
body: body,
modifiers: modifiers,
sourceRange: sourceRange)
}
public override func attributes() -> [String : Any] {
var superAttrs = super.attributes()
superAttrs["operator"] = "\(op)"
superAttrs["name"] = nil
superAttrs["kind"] = nil
return superAttrs
}
}
| mit | 680daa5c942682e9dd803af0bd14e7f9 | 24.897674 | 120 | 0.639907 | 4.170787 | false | false | false | false |
mozilla-mobile/focus-ios | Blockzilla/Settings/Controller/SearchSettingsViewController.swift | 1 | 9785 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Telemetry
protocol SearchSettingsViewControllerDelegate: AnyObject {
func searchSettingsViewController(_ searchSettingsViewController: SearchSettingsViewController, didSelectEngine engine: SearchEngine)
}
class SearchSettingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
weak var delegate: SearchSettingsViewControllerDelegate?
private let searchEngineManager: SearchEngineManager
private var isInEditMode = false
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .insetGrouped)
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .singleLine
tableView.allowsSelection = true
tableView.estimatedRowHeight = UITableView.automaticDimension
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
init(searchEngineManager: SearchEngineManager) {
self.searchEngineManager = searchEngineManager
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = UIConstants.strings.settingsSearchLabel
navigationController?.navigationBar.tintColor = .accent
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
tableView.selectRow(at: IndexPath(row: 0, section: 1), animated: false, scrollPosition: .none)
tableView.tableFooterView = UIView()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: UIConstants.strings.Edit, style: .plain, target: self, action: #selector(SearchSettingsViewController.toggleEditing))
navigationItem.rightBarButtonItem?.accessibilityIdentifier = "edit"
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return UIConstants.strings.InstalledSearchEngines
} else {
return nil
}
}
func numberOfSections(in tableView: UITableView) -> Int {
if isInEditMode {
return 1
} else {
return 2
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfEngines = searchEngineManager.engines.count
if isInEditMode { // NOTE: This is false when a user is swiping to delete but tableView.isEditing is true
return numberOfEngines
}
switch section {
case 1:
return 1
default:
return numberOfEngines + 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let engines = searchEngineManager.engines
if indexPath.item == engines.count {
let cell = UITableViewCell(style: .default, reuseIdentifier: "addSearchEngine")
cell.textLabel?.text = UIConstants.strings.AddSearchEngineButton
cell.textLabel?.textColor = .primaryText
cell.accessibilityIdentifier = "addSearchEngine"
cell.selectionStyle = .gray
return cell
} else if indexPath.section == 1 && indexPath.row == 0 {
let cell = UITableViewCell(style: .default, reuseIdentifier: "restoreDefaultEngines")
cell.textLabel?.text = UIConstants.strings.RestoreSearchEnginesLabel
cell.textLabel?.font = .body17
cell.textLabel?.numberOfLines = 0
cell.textLabel?.lineBreakMode = .byWordWrapping
cell.accessibilityIdentifier = "restoreDefaults"
if searchEngineManager.hasDisabledDefaultEngine() {
cell.textLabel?.textColor = .primaryText
cell.selectionStyle = .gray
cell.isUserInteractionEnabled = true
} else {
cell.textLabel?.textColor = .inputPlaceholder
cell.selectionStyle = .none
cell.isUserInteractionEnabled = false
}
return cell
} else {
let engine = engines[indexPath.item]
let cell = UITableViewCell(style: .default, reuseIdentifier: engine.image == nil ? "empty-image-cell" : nil)
cell.textLabel?.text = engine.name
cell.textLabel?.textColor = .primaryText
cell.imageView?.image = engine.image?.createScaled(size: CGSize(width: 24, height: 24))
cell.selectionStyle = .gray
cell.accessibilityIdentifier = engine.name
cell.contentView.translatesAutoresizingMaskIntoConstraints = false
cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
cell.textLabel?.translatesAutoresizingMaskIntoConstraints = false
if tableView.isEditing {
NSLayoutConstraint.activate([
cell.contentView.leadingAnchor.constraint(equalTo: cell.leadingAnchor)
])
if let imageView = cell.imageView, let label = cell.textLabel {
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: UIConstants.layout.settingsViewOffset),
imageView.centerYAnchor.constraint(equalTo: cell.centerYAnchor),
label.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: UIConstants.layout.settingsSearchViewImageOffset),
label.centerYAnchor.constraint(equalTo: imageView.centerYAnchor)
])
}
}
if engine === searchEngineManager.activeEngine {
cell.accessoryType = .checkmark
if tableView.isEditing {
cell.textLabel?.textColor = .inputPlaceholder.withAlphaComponent(0.5)
cell.separatorInset = UIEdgeInsets(top: 0, left: 93, bottom: 0, right: 0)
cell.tintColor = tableView.tintColor.withAlphaComponent(0.5)
cell.imageView?.alpha = 0.5
}
}
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.row == searchEngineManager.engines.count+1 ? 44*2 : 44
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let engines = searchEngineManager.engines
if indexPath.item == engines.count {
// Add search engine tapped
let vc = AddSearchEngineViewController(delegate: self, searchEngineManager: searchEngineManager)
navigationController?.pushViewController(vc, animated: true)
} else if indexPath.section == 1 {
// Restore default engines tapped
if searchEngineManager.hasDisabledDefaultEngine() {
searchEngineManager.restoreDisabledDefaultEngines()
tableView.reloadData()
}
} else {
let engine = engines[indexPath.item]
searchEngineManager.activeEngine = engine
Telemetry.default.configuration.defaultSearchEngineProvider = engine.name
_ = navigationController?.popViewController(animated: true)
delegate?.searchSettingsViewController(self, didSelectEngine: engine)
}
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
let engines = searchEngineManager.engines
if indexPath.row >= engines.count {
// Can not edit the add engine or restore default rows
return false
}
let engine = engines[indexPath.row]
return engine != searchEngineManager.activeEngine
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return indexPath.section == 1 ? .none : .delete
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
searchEngineManager.removeEngine(engine: searchEngineManager.engines[indexPath.row])
tableView.reloadData()
}
}
@objc func toggleEditing() {
isInEditMode = !isInEditMode
navigationItem.rightBarButtonItem?.title = tableView.isEditing ? UIConstants.strings.Edit : UIConstants.strings.Done
tableView.setEditing(!tableView.isEditing, animated: true)
tableView.reloadData()
navigationItem.hidesBackButton = tableView.isEditing
}
}
extension SearchSettingsViewController: AddSearchEngineDelegate {
func addSearchEngineViewController(_ addSearchEngineViewController: AddSearchEngineViewController, name: String, searchTemplate: String) {
let engine = searchEngineManager.addEngine(name: name, template: searchTemplate)
tableView.reloadData()
delegate?.searchSettingsViewController(self, didSelectEngine: engine)
}
}
| mpl-2.0 | c66d77039ec15b65dbbd35c00ee91414 | 41.916667 | 184 | 0.662647 | 5.845281 | false | false | false | false |
maple1994/RxZhiHuDaily | RxZhiHuDaily/View/NewsTableViewCell.swift | 1 | 2597 | //
// NewsTableViewCell.swift
// MPZhiHuDaily
//
// Created by Maple on 2017/8/21.
// Copyright © 2017年 Maple. All rights reserved.
//
import UIKit
import SnapKit
/// 新闻列表Cell
class NewsTableViewCell: UITableViewCell {
var model: MPStoryModel? {
didSet {
if let myModel = model {
titleLabel.text = myModel.title
if let path = model?.images?.first {
iconImgView.kf.setImage(with: URL.init(string: path))
titleLabel.snp.updateConstraints({ (make) in
make.right.equalToSuperview().offset(-105)
})
}else {
iconImgView.image = nil
titleLabel.snp.updateConstraints({ (make) in
make.right.equalToSuperview().offset(-15)
})
}
morePicIcon.isHidden = !myModel.multipic
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("")
}
fileprivate func setupUI() {
contentView.addSubview(titleLabel)
contentView.addSubview(iconImgView)
contentView.addSubview(morePicIcon)
titleLabel.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(15)
make.top.equalTo(iconImgView)
make.right.equalToSuperview().offset(-105)
}
iconImgView.snp.makeConstraints { (make) in
make.right.equalToSuperview().offset(-15)
make.centerY.equalToSuperview()
make.width.equalTo(75)
make.height.equalTo(60)
}
morePicIcon.snp.makeConstraints { (make) in
make.bottom.equalTo(iconImgView)
make.trailing.equalTo(iconImgView)
make.width.equalTo(32)
make.height.equalTo(14)
}
}
// MARK: - View
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15)
label.numberOfLines = 0
return label
}()
fileprivate lazy var iconImgView: UIImageView = {
let iv = UIImageView()
return iv
}()
fileprivate lazy var morePicIcon: UIImageView = {
let iv = UIImageView()
iv.image = UIImage(named: "Home_Morepic")
return iv
}()
}
| mit | 57596575881d21d367d3c119d2e52127 | 26.221053 | 74 | 0.554138 | 4.879245 | false | false | false | false |
ktilakraj/MuvizzCode | SlideMenuControllerSwift/DataManager/DataManager.swift | 1 | 6840 | //
// DataManager.swift
// Muvizz
//
// Created by tilak raj verma on 22/12/16.
// Copyright © 2016 Yuji Hato. All rights reserved.
//
import Foundation
public class DataManager {
static let sharedInstance = DataManager()
var arrSubCatagories = [DefaultDataModel]()
var arrLanguages = [DefaultDataModel]()
func doSomthing() {
print("Hello check singlton")
}
func getBannerData(onsuccess:@escaping (AnyObject?,Bool)-> Void) -> Void {
let urlSring = "\(Constants.API_BASE_URL)banners"
getDatafromUrl(urlString: urlSring) { (data, response, error) in
if data != nil {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let theBanner_root = BannerMain.init(jsonObject as AnyObject)
onsuccess(theBanner_root as AnyObject?,true)
}
catch {
onsuccess(nil,false)
}
}
else {
onsuccess(nil,false)
}
}
}
func getOtherDataFromMenthod(_ methodParam:String,sectionName:SectionType,onsuccess:@escaping (AnyObject?,Bool)-> Void) -> Void
{
let urlSring = "\(Constants.API_BASE_URL)movies?categories%5B%5D=\(methodParam)"
getDatafromUrl(urlString: urlSring) { (data, response, error) in
if data != nil {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let tempObject = jsonObject as? [String: AnyObject]
let theBanner_root = OtherDataSubRoot.init((tempObject?["data"] as? [AnyObject])!,headrTitle:sectionName)
onsuccess(theBanner_root as AnyObject?,true)
}
catch {
onsuccess(nil,false)
}
}
else {
onsuccess(nil,false)
}
}
}
func getMoviesDataFromMenthod(_ methodParam:String,sectionName:SectionType,onsuccess:@escaping (AnyObject?,Bool)-> Void) -> Void
{
let urlSring = "\(Constants.API_BASE_URL)movies?\(methodParam)"
getDatafromUrl(urlString: urlSring) { (data, response, error) in
if data != nil {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let tempObject = jsonObject as? [String: AnyObject]
let theBanner_root = OtherDataSubRoot.init((tempObject?["data"] as? [AnyObject])!,headrTitle: sectionName)
onsuccess(theBanner_root as AnyObject?,true)
}
catch {
onsuccess(nil,false)
}
}
else {
onsuccess(nil,false)
}
}
}
func getBundleDataFromMenthod(_ methodParam:String,sectionName:SectionType,onsuccess:@escaping (AnyObject?,Bool)-> Void) -> Void
{
let urlSring = "\(Constants.API_BASE_URL)products/bundles\(methodParam)"
getDatafromUrl(urlString: urlSring) { (data, response, error) in
if data != nil {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let tempObject = jsonObject as? [AnyObject]
let theBanner_root = OtherDataSubRoot.init(tempObject!,headrTitle: sectionName)
onsuccess(theBanner_root as AnyObject?,true)
}
catch {
onsuccess(nil,false)
}
}
else {
onsuccess(nil,false)
}
}
}
func getDatafromUrl(urlString:String,oncompletion:@escaping (Data?, URLResponse?, Error?)->Void) -> Void
{
let url = URL(string: urlString)!
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
return
}
if let response = response as? HTTPURLResponse {
if response.statusCode / 100 != 2
{
return
}
oncompletion(data,response,error)
}
}
task.resume()
}
func getData(urlString:String,oncompletion:@escaping (_ data:[DefaultDataModel])->Void) {
let urlString:String = urlString
getDatafromUrl(urlString: urlString) { (data, response, error) in
var arrData = [DefaultDataModel]()
if error == nil && data != nil {
do {
let responseData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let thedata = responseData as? [AnyObject]
for indata in thedata! {
let tempData = indata as? [String:AnyObject]
arrData.append(DefaultDataModel.init(tempData!))
}
} catch {
print("the error in response:\(error.localizedDescription)")
}
}
oncompletion(arrData)
}
}
//MARK:Language
func getLanguageData(onSuccess:@escaping ()->Void) {
getData(urlString: "http://api.muvizz.com/api/v1/languages") { (
arr) in
if arr.count > 0 {
self.arrLanguages = arr
}
onSuccess()
}
}
//MARK:Catagories
func getCatagoriesData(onSuccess:@escaping ()->Void) {
getData(urlString: "http://api.muvizz.com/api/v1/categories") { (
arr) in
if arr.count > 0 {
self.arrSubCatagories = arr
}
onSuccess()
}
}
}
| mit | 153531242d892fcd0b499be886343c7f | 31.879808 | 145 | 0.494078 | 5.528698 | false | false | false | false |
doubleencore/POM-Logging | POM-Logging/POM-Logging/TextFileTaskLogAdaptor.swift | 1 | 1576 | //
// TextFileTaskLogAdaptor.swift
// Copyright © 2017 Possible Mobile. All rights reserved.
//
import Foundation
class TextFileTaskLogAdaptor {
// MARK: - Properties
let fileHandle: FileHandle?
// MARK: - Initialization
init(logName: String, clear: Bool) {
let docsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
let filePath = docsPath.appending("/\(logName)")
if !FileManager.default.fileExists(atPath: filePath) {
FileManager.default.createFile(atPath: filePath, contents: nil, attributes: nil)
}
if clear {
try? "".write(toFile: filePath, atomically: true, encoding: .utf8)
}
fileHandle = FileHandle(forWritingAtPath: filePath)
print("📝 Log started at \(filePath)")
}
// MARK: - Public
func write(line: String) {
guard let fileHandle = fileHandle else { return }
guard let data = "\n\(line)".data(using: .utf8) else { return }
fileHandle.seekToEndOfFile()
fileHandle.write(data)
}
}
// MARK: - <TaskLogAdaptor>
extension TextFileTaskLogAdaptor: TaskLogAdaptor {
func task(_ task: PerformanceLog.Task, didCrossWaypoint waypoint: String) {
let message = "🏴 \(task.category) \(task.name): \(waypoint)"
write(line: message)
}
func didEndTask(_ task: PerformanceLog.Task) {
let message = "⏱ \(Date()), \(task.formattedDurationDescription)"
write(line: message)
}
}
| mit | ca8a563527879f79e4baa797c6dbe8de | 25.116667 | 107 | 0.622208 | 4.555233 | false | false | false | false |
Mazy-ma/DemoBySwift | CircularImageLoaderAnimation/CircularImageLoaderAnimation/CustomImageView.swift | 1 | 1267 | //
// CustomImageView.swift
// CircularImageLoaderAnimation
//
// Created by Mazy on 2017/6/28.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class CustomImageView: UIImageView {
let progressIndicatorView = CircularLoaderView(frame: CGRect.zero)
var displayLink: CADisplayLink?
var progress: CGFloat = 0
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubview(progressIndicatorView)
progressIndicatorView.frame = bounds
progressIndicatorView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
displayLink = CADisplayLink(target: self, selector: #selector(simulateDownload))
displayLink?.preferredFramesPerSecond = 60
displayLink?.add(to: RunLoop.current, forMode: .commonModes)
displayLink?.isPaused = false
}
func simulateDownload() {
progress += 1
progressIndicatorView.progress = progress/30
if progress == 30 {
displayLink?.isPaused = true
displayLink?.invalidate()
displayLink = nil
// 切割
progressIndicatorView.reveal()
}
}
}
| apache-2.0 | 45928616edd5eb5d2367f32548b99865 | 24.2 | 88 | 0.613492 | 5.625 | false | false | false | false |
CarlosMChica/swift-dojos | SocialNetworkKata/SocialNetworkKataTest/doubles/PostRepositorySpy.swift | 1 | 531 | class PostRepositorySpy: PostRepository {
var storeCalled = false
var storedPost: Post!
var timelineOfCalled = false
var timelineLoadedOfUser: User!
let timelinePosts: [Post]
override init() {
timelinePosts = [Post]()
}
init(posts: [Post]) {
self.timelinePosts = posts
}
override func store(post: Post) {
storeCalled = true
storedPost = post
}
override func timelineOf(user: User) -> [Post] {
timelineOfCalled = true
timelineLoadedOfUser = user
return timelinePosts
}
}
| apache-2.0 | 21b6e6489850d38d0376356c605c2bdf | 17.310345 | 50 | 0.6742 | 3.992481 | false | false | false | false |
jum/Charts | Source/Charts/Renderers/CandleStickChartRenderer.swift | 3 | 16341 | //
// CandleStickChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class CandleStickChartRenderer: LineScatterCandleRadarRenderer
{
@objc open weak var dataProvider: CandleChartDataProvider?
@objc public init(dataProvider: CandleChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard let dataProvider = dataProvider, let candleData = dataProvider.candleData else { return }
// If we redraw the data, remove and repopulate accessible elements to update label values and frames
accessibleChartElements.removeAll()
// Make the chart header the first element in the accessible elements array
if let chart = dataProvider as? CandleStickChartView {
let element = createAccessibleHeader(usingChart: chart,
andData: candleData,
withDefaultDescription: "CandleStick Chart")
accessibleChartElements.append(element)
}
for set in candleData.dataSets as! [ICandleChartDataSet] where set.isVisible
{
drawDataSet(context: context, dataSet: set)
}
}
private var _shadowPoints = [CGPoint](repeating: CGPoint(), count: 4)
private var _rangePoints = [CGPoint](repeating: CGPoint(), count: 2)
private var _openPoints = [CGPoint](repeating: CGPoint(), count: 2)
private var _closePoints = [CGPoint](repeating: CGPoint(), count: 2)
private var _bodyRect = CGRect()
private var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2)
@objc open func drawDataSet(context: CGContext, dataSet: ICandleChartDataSet)
{
guard
let dataProvider = dataProvider
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
let barSpace = dataSet.barSpace
let showCandleBar = dataSet.showCandleBar
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
context.saveGState()
context.setLineWidth(dataSet.shadowWidth)
for j in _xBounds
{
// get the entry
guard let e = dataSet.entryForIndex(j) as? CandleChartDataEntry else { continue }
let xPos = e.x
let open = e.open
let close = e.close
let high = e.high
let low = e.low
let doesContainMultipleDataSets = (dataProvider.candleData?.dataSets.count ?? 1) > 1
var accessibilityMovementDescription = "neutral"
var accessibilityRect = CGRect(x: CGFloat(xPos) + 0.5 - barSpace,
y: CGFloat(low * phaseY),
width: (2 * barSpace) - 1.0,
height: (CGFloat(abs(high - low) * phaseY)))
trans.rectValueToPixel(&accessibilityRect)
if showCandleBar
{
// calculate the shadow
_shadowPoints[0].x = CGFloat(xPos)
_shadowPoints[1].x = CGFloat(xPos)
_shadowPoints[2].x = CGFloat(xPos)
_shadowPoints[3].x = CGFloat(xPos)
if open > close
{
_shadowPoints[0].y = CGFloat(high * phaseY)
_shadowPoints[1].y = CGFloat(open * phaseY)
_shadowPoints[2].y = CGFloat(low * phaseY)
_shadowPoints[3].y = CGFloat(close * phaseY)
}
else if open < close
{
_shadowPoints[0].y = CGFloat(high * phaseY)
_shadowPoints[1].y = CGFloat(close * phaseY)
_shadowPoints[2].y = CGFloat(low * phaseY)
_shadowPoints[3].y = CGFloat(open * phaseY)
}
else
{
_shadowPoints[0].y = CGFloat(high * phaseY)
_shadowPoints[1].y = CGFloat(open * phaseY)
_shadowPoints[2].y = CGFloat(low * phaseY)
_shadowPoints[3].y = _shadowPoints[1].y
}
trans.pointValuesToPixel(&_shadowPoints)
// draw the shadows
var shadowColor: NSUIColor! = nil
if dataSet.shadowColorSameAsCandle
{
if open > close
{
shadowColor = dataSet.decreasingColor ?? dataSet.color(atIndex: j)
}
else if open < close
{
shadowColor = dataSet.increasingColor ?? dataSet.color(atIndex: j)
}
else
{
shadowColor = dataSet.neutralColor ?? dataSet.color(atIndex: j)
}
}
if shadowColor === nil
{
shadowColor = dataSet.shadowColor ?? dataSet.color(atIndex: j)
}
context.setStrokeColor(shadowColor.cgColor)
context.strokeLineSegments(between: _shadowPoints)
// calculate the body
_bodyRect.origin.x = CGFloat(xPos) - 0.5 + barSpace
_bodyRect.origin.y = CGFloat(close * phaseY)
_bodyRect.size.width = (CGFloat(xPos) + 0.5 - barSpace) - _bodyRect.origin.x
_bodyRect.size.height = CGFloat(open * phaseY) - _bodyRect.origin.y
trans.rectValueToPixel(&_bodyRect)
// draw body differently for increasing and decreasing entry
if open > close
{
accessibilityMovementDescription = "decreasing"
let color = dataSet.decreasingColor ?? dataSet.color(atIndex: j)
if dataSet.isDecreasingFilled
{
context.setFillColor(color.cgColor)
context.fill(_bodyRect)
}
else
{
context.setStrokeColor(color.cgColor)
context.stroke(_bodyRect)
}
}
else if open < close
{
accessibilityMovementDescription = "increasing"
let color = dataSet.increasingColor ?? dataSet.color(atIndex: j)
if dataSet.isIncreasingFilled
{
context.setFillColor(color.cgColor)
context.fill(_bodyRect)
}
else
{
context.setStrokeColor(color.cgColor)
context.stroke(_bodyRect)
}
}
else
{
let color = dataSet.neutralColor ?? dataSet.color(atIndex: j)
context.setStrokeColor(color.cgColor)
context.stroke(_bodyRect)
}
}
else
{
_rangePoints[0].x = CGFloat(xPos)
_rangePoints[0].y = CGFloat(high * phaseY)
_rangePoints[1].x = CGFloat(xPos)
_rangePoints[1].y = CGFloat(low * phaseY)
_openPoints[0].x = CGFloat(xPos) - 0.5 + barSpace
_openPoints[0].y = CGFloat(open * phaseY)
_openPoints[1].x = CGFloat(xPos)
_openPoints[1].y = CGFloat(open * phaseY)
_closePoints[0].x = CGFloat(xPos) + 0.5 - barSpace
_closePoints[0].y = CGFloat(close * phaseY)
_closePoints[1].x = CGFloat(xPos)
_closePoints[1].y = CGFloat(close * phaseY)
trans.pointValuesToPixel(&_rangePoints)
trans.pointValuesToPixel(&_openPoints)
trans.pointValuesToPixel(&_closePoints)
// draw the ranges
var barColor: NSUIColor! = nil
if open > close
{
accessibilityMovementDescription = "decreasing"
barColor = dataSet.decreasingColor ?? dataSet.color(atIndex: j)
}
else if open < close
{
accessibilityMovementDescription = "increasing"
barColor = dataSet.increasingColor ?? dataSet.color(atIndex: j)
}
else
{
barColor = dataSet.neutralColor ?? dataSet.color(atIndex: j)
}
context.setStrokeColor(barColor.cgColor)
context.strokeLineSegments(between: _rangePoints)
context.strokeLineSegments(between: _openPoints)
context.strokeLineSegments(between: _closePoints)
}
let axElement = createAccessibleElement(withIndex: j,
container: dataProvider,
dataSet: dataSet)
{ (element) in
element.accessibilityLabel = "\(doesContainMultipleDataSets ? "\(dataSet.label ?? "Dataset")" : "") " + "\(xPos) - \(accessibilityMovementDescription). low: \(low), high: \(high), opening: \(open), closing: \(close)"
element.accessibilityFrame = accessibilityRect
}
accessibleChartElements.append(axElement)
}
// Post this notification to let VoiceOver account for the redrawn frames
accessibilityPostLayoutChangedNotification()
context.restoreGState()
}
open override func drawValues(context: CGContext)
{
guard
let dataProvider = dataProvider,
let candleData = dataProvider.candleData
else { return }
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
var dataSets = candleData.dataSets
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0 ..< dataSets.count
{
guard let
dataSet = dataSets[i] as? IBarLineScatterCandleBubbleChartDataSet,
shouldDrawValues(forDataSet: dataSet)
else { continue }
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let iconsOffset = dataSet.iconsOffset
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let lineHeight = valueFont.lineHeight
let yOffset: CGFloat = lineHeight + 5.0
for j in _xBounds
{
guard let e = dataSet.entryForIndex(j) as? CandleChartDataEntry else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.high * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
if dataSet.isDrawValuesEnabled
{
ChartUtils.drawText(
context: context,
text: formatter.stringForValue(
e.high,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
point: CGPoint(
x: pt.x,
y: pt.y - yOffset),
align: .center,
attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: dataSet.valueTextColorAt(j)])
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
ChartUtils.drawImage(context: context,
image: icon,
x: pt.x + iconsOffset.x,
y: pt.y + iconsOffset.y,
size: icon.size)
}
}
}
}
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let candleData = dataProvider.candleData
else { return }
context.saveGState()
for high in indices
{
guard
let set = candleData.getDataSetByIndex(high.dataSetIndex) as? ICandleChartDataSet,
set.isHighlightEnabled
else { continue }
guard let e = set.entryForXValue(high.x, closestToY: high.y) as? CandleChartDataEntry else { continue }
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if set.highlightLineDashLengths != nil
{
context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
let lowValue = e.low * Double(animator.phaseY)
let highValue = e.high * Double(animator.phaseY)
let y = (lowValue + highValue) / 2.0
let pt = trans.pixelForValues(x: e.x, y: y)
high.setDraw(pt: pt)
// draw the lines
drawHighlightLines(context: context, point: pt, set: set)
}
context.restoreGState()
}
private func createAccessibleElement(withIndex idx: Int,
container: CandleChartDataProvider,
dataSet: ICandleChartDataSet,
modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement {
let element = NSUIAccessibilityElement(accessibilityContainer: container)
// The modifier allows changing of traits and frame depending on highlight, rotation, etc
modifier(element)
return element
}
}
| apache-2.0 | d34556bce34e2aa0caa60456b855ac23 | 37.907143 | 232 | 0.484242 | 6.185087 | false | false | false | false |
Constructor-io/constructorio-client-swift | AutocompleteClient/FW/API/Parser/Autocomplete/CIOAutocompleteResponseParser.swift | 1 | 4708 | //
// CIOAutocompleteResponseParser.swift
// Constructor.io
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
struct CIOAutocompleteResponseParser: AbstractAutocompleteResponseParser {
weak var delegate: ResponseParserDelegate?
init() {}
func parse(autocompleteResponseData: Data) throws -> CIOAutocompleteResponse {
do {
if let json = try JSONSerialization.jsonObject(with: autocompleteResponseData) as? JSONObject {
let isSingleSection = json.keys.contains(Constants.Response.singleSectionResultField)
return isSingleSection ? try parse(singleSectionJson: json) : try parse(multiSectionJson: json)
} else {
throw CIOError(errorType: .invalidResponse)
}
} catch {
throw CIOError(errorType: .invalidResponse)
}
}
private func parse(singleSectionJson json: JSONObject) throws -> CIOAutocompleteResponse {
guard let section = json[Constants.Response.singleSectionResultField] as? [JSONObject] else {
throw CIOError(errorType: .invalidResponse)
}
let results = self.jsonToAutocompleteItems(jsonObjects: section)
var metadata = json
metadata[Constants.Response.singleSectionResultField] = nil
return CIOAutocompleteResponse(sections: [Constants.Response.singleSectionResultField: results], json: json)
}
private func parse(multiSectionJson json: JSONObject) throws -> CIOAutocompleteResponse {
guard let sections = json[Constants.Response.multiSectionResultField] as? [String: [JSONObject]] else {
throw CIOError(errorType: .invalidResponse)
}
var results = [String: [CIOAutocompleteResult]]()
for section in sections {
results[section.key] = self.jsonToAutocompleteItems(jsonObjects: section.value)
}
var metadata = json
metadata[Constants.Response.multiSectionResultField] = nil
return CIOAutocompleteResponse(sections: results, json: json)
}
fileprivate func jsonToAutocompleteItems(jsonObjects: [JSONObject]) -> [CIOAutocompleteResult] {
return jsonObjects.compactMap { CIOResult(json: $0) }
.enumerated()
.reduce([CIOAutocompleteResult](), { (arr, enumeratedAutocompleteResult) in
let autocompleteResult = enumeratedAutocompleteResult.element
let index = enumeratedAutocompleteResult.offset
let first = CIOAutocompleteResult(result: autocompleteResult, group: nil)
// If the base result is filtered out, we don't show
// the group search options.
if let shouldParseResult = self.delegateShouldParseResult(autocompleteResult, nil), shouldParseResult == false {
return []
}
var itemsInGroups: [CIOAutocompleteResult] = []
// create a parse handler to avoid code duplication down below
let parseItemHandler = { (group: CIOGroup) in
let itemInGroup = CIOAutocompleteResult(result: autocompleteResult, group: group)
itemsInGroups.append(itemInGroup)
}
let groups = autocompleteResult.data.groups
let maximumNumberOfGroupItems = self.delegateMaximumGroupsShownPerResult(result: autocompleteResult, at: index)
groupLoop: for group in groups {
if itemsInGroups.count >= maximumNumberOfGroupItems {
break groupLoop
}
if let shouldParseResultInGroup = self.delegateShouldParseResult(autocompleteResult, group) {
if shouldParseResultInGroup {
// method implemented by the delegate and returns true
parseItemHandler(group)
}
} else {
// method not implemeneted by the delegate
// we parse the result by default
parseItemHandler(group)
}
}
return arr + [first] + itemsInGroups
})
}
fileprivate func delegateMaximumGroupsShownPerResult(result: CIOResult, at index: Int) -> Int {
return self.delegate?.maximumGroupsShownPerResult(result: result, at: index) ?? Int.max
}
fileprivate func delegateShouldParseResult(_ result: CIOResult, _ group: CIOGroup?) -> Bool? {
return self.delegate?.shouldParseResult(result: result, inGroup: group)
}
}
| mit | 3f30c45c5071740509e9c55dff377581 | 40.654867 | 128 | 0.629276 | 5.550708 | false | false | false | false |
jakeheis/SwiftCLI | Sources/SwiftCLI/CLI.swift | 1 | 6691 | //
// CLI.swift
// SwiftCLI
//
// Created by Jake Heiser on 7/20/14.
// Copyright (c) 2014 jakeheis. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
public class CLI {
/// The name of the CLI; used in help messages
public let name: String
/// The version of the CLI; if non-nil, a VersionCommand is automatically created
public let version: String?
/// The description of the CLI; used in help messages
public var description: String?
/// The array of commands (or command groups)
public var commands: [Routable]
/// A built-in help command; set to nil if this functionality is not wanted
public lazy var helpCommand: HelpCommand? = HelpCommand(cli: self)
/// A built-in version command; set to nil if this functionality is not wanted
public lazy var versionCommand: VersionCommand? = {
if let version = version {
return VersionCommand(version: version)
}
return nil
}()
/// Options which every command inherits
public var globalOptions: [Option] = []
/// Option groups which every command inherits
public var globalOptionGroups: [OptionGroup] = []
/// A built-in help flag which each command automatically inherits; set to nil if this functionality is not wanted
public var helpFlag: Flag? = Flag("-h", "--help", description: "Show help information")
/// A map of command name aliases; by default, default maps "--version" to 'version'
public var aliases: [String : String] = [
"--version": "version"
]
public var helpMessageGenerator: HelpMessageGenerator = DefaultHelpMessageGenerator()
public var argumentListManipulators: [_ArgumentListManipulator] = []
public var parser = Parser()
/// Creates a new CLI
///
/// - Parameter name: the name of the CLI executable
/// - Parameter version: the current version of the CLI
/// - Parameter description: a brief description of the CLI
public init(name: String, version: String? = nil, description: String? = nil, commands: [Routable] = []) {
self.name = name
self.version = version
self.description = description
self.commands = commands
}
/// Create a single-command CLI; useful for example if you were implementing the 'ln' command
///
/// - Parameter singleCommand: the single command
public convenience init(singleCommand: Command) {
self.init(name: singleCommand.name, commands: [singleCommand])
parser.routeBehavior = .automatically(singleCommand)
}
/// Kicks off the entire CLI process, routing to and executing the command specified by the passed arguments.
/// Uses the arguments passed in the command line. Exits the program upon completion.
///
/// - Returns: Never
public func goAndExit() -> Never {
let result = go()
exit(result)
}
/// Kicks off the entire CLI process, routing to and executing the command specified by the passed arguments.
/// Uses the arguments passed in the command line.
///
/// - Returns: an Int32 representing the success of the CLI in routing to and executing the correct
/// command. Usually should be passed to `exit(result)`
@discardableResult
public func go() -> Int32 {
return go(with: ArgumentList(arguments: Array(CommandLine.arguments.dropFirst())))
}
/// Kicks off the entire CLI process, routing to and executing the command specified by the passed arguments.
///
/// - Parameter arguments: the arguments to execute with; should not include CLI name (i.e. if you wanted to execute "greeter greet world", 'arguments' should be ["greet", "world"])
/// - Returns: an Int32 representing the success of the CLI in routing to and executing the correct command. Usually should be passed to `exit(result)`
@discardableResult
public func go(with arguments: [String]) -> Int32 {
return go(with: ArgumentList(arguments: arguments))
}
// MARK: - Internal/private
func go(with arguments: ArgumentList) -> Int32 {
argumentListManipulators.forEach { $0.manipulate(arguments: arguments) }
var exitStatus: Int32 = 0
do {
let path = try parse(arguments: arguments)
if helpFlag?.wrappedValue == true {
helpMessageGenerator.writeUsageStatement(for: path, to: stdout)
} else {
try path.command.execute()
}
} catch let error as ProcessError {
if let message = error.message {
stderr <<< message
}
exitStatus = Int32(error.exitStatus)
} catch let error {
helpMessageGenerator.writeUnrecognizedErrorMessage(for: error, to: stderr)
exitStatus = 1
}
return exitStatus
}
private func parse(arguments: ArgumentList) throws -> CommandPath {
do {
return try parser.parse(cli: self, arguments: arguments)
} catch let error as RouteError {
helpMessageGenerator.writeRouteErrorMessage(for: error, to: stderr)
throw CLI.Error()
} catch let error as OptionError {
if let command = error.command, command.command is HelpCommand {
return command
}
helpMessageGenerator.writeMisusedOptionsStatement(for: error, to: stderr)
throw CLI.Error()
} catch let error as ParameterError {
if error.command.command is HelpCommand || helpFlag?.wrappedValue == true {
return error.command
}
helpMessageGenerator.writeParameterErrorMessage(for: error, to: stderr)
throw CLI.Error()
}
}
}
extension CLI: CommandGroup {
public var shortDescription: String {
return description ?? ""
}
public var longDescription: String {
return description ?? ""
}
public var children: [Routable] {
var extra: [Routable] = []
if let helpCommand = helpCommand {
extra.append(helpCommand)
}
if let versionCommand = versionCommand {
extra.append(versionCommand)
}
return commands + extra
}
public var options: [Option] {
if let helpFlag = helpFlag {
return globalOptions + [helpFlag]
}
return globalOptions
}
public var optionGroups: [OptionGroup] {
return globalOptionGroups
}
}
| mit | 68422479fd6f00bf52af9f8adcae34c2 | 34.215789 | 185 | 0.624122 | 4.89466 | false | false | false | false |
Snail93/iOSDemos | SnailSwiftDemos/SnailSwiftDemos/Foundations/ViewControllers/NSUserDefaultViewController.swift | 2 | 3027 | //
// NSUserDefaultViewController.swift
// SnailSwiftDemos
//
// Created by Jian Wu on 2016/11/15.
// Copyright © 2016年 Snail. All rights reserved.
//
/*
NSUserDefaults是一个单例,在整个程序中只有一个实例对象,他可以用于数据的永久保存,而且简单实用
支持的数据类型有:NSNumber(NSInteger、float、double),NSString,NSDate,NSArray,NSDictionary,BOOL
注意:
1、对相同的Key赋值约等于一次覆盖,要保证每一个Key的唯一性
2、 NSUserDefaults 存储的对象全是不可变的(这一点非常关键,弄错的话程序会出bug),
例如,如果我想要存储一个 NSMutableArray 对象,我必须先创建一个不可变数组(NSArray)再将它存入NSUserDefaults中去
*/
import UIKit
class NSUserDefaultViewController: CustomViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
saveCustomClass()
}
//MARK: - 初识
func commonAction() {
let password = "Password"
let intValue = 555
UserDefaults.standard.set(intValue, forKey: "IntValue")
UserDefaults.standard.set(password, forKey: "Password")
print("IntValue:\(UserDefaults.standard.integer(forKey: "IntValue"))")
print("Password:\(UserDefaults.standard.object(forKey: "Password"))")
let arr = ["data1","data2"]
UserDefaults.standard.set(arr, forKey: "Arr")
if let temp = UserDefaults.standard.object(forKey: "Arr"){
var ar = temp as! Array<String>
ar.append("data3")
print(ar.last)
}
}
/*
MARK: - 使用NSUserDefaults存储自定义对象
1、要想NSUserDefaults能存储自定义类型,就必须遵守NSCoding的协议
2、并且实现encodeWithCoder和initWithCoder方法即可
*/
func saveCustomClass() {
//TODO:自定义对象的Data形式存储
let cat = Cat(name: "Snail", age: "124")
let catData = NSKeyedArchiver.archivedData(withRootObject: cat)
UserDefaults.standard.set(catData, forKey: "CatData")
let catDataa = UserDefaults.standard.object(forKey: "CatData") as! Data
let catt = NSKeyedUnarchiver.unarchiveObject(with: catDataa) as! Cat
print(catt.name + catt.age)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | fcf74c1707a36f289d3bb909a81edfeb | 29.752941 | 106 | 0.644606 | 4.243506 | false | false | false | false |
davidisaaclee/VectorKit | Example/Tests/CustomVectors.swift | 1 | 2146 | //
// CustomVectors.swift
// VectorKit
//
// Created by David Lee on 4/9/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import VectorKit
extension Float: Field {
public static let additionIdentity: Float = 0
public static let multiplicationIdentity: Float = 1
public func toThePowerOf(exponent: Float) -> Float {
return powf(self, exponent)
}
}
public final class CustomVector2 {
let x: Float
let y: Float
public init(x: Float, y: Float) {
self.x = x
self.y = y
}
public convenience init<T where T: CollectionType, T.Generator.Element == Float>(collection: T) {
var g = collection.generate()
guard let x = g.next(), let y = g.next() else {
fatalError()
}
self.init(x: x, y: y)
}
}
extension CustomVector2: Vector {
public typealias Index = Int
public static let additionIdentity: CustomVector2 = CustomVector2(collection: [0, 0])
public static let multiplicationIdentity: CustomVector2 = CustomVector2(collection: [1, 1])
public var numberOfDimensions: Int { return 2 }
public subscript(index: Int) -> Float {
switch index {
case 0:
return x
case 1:
return y
default:
fatalError()
}
}
}
extension CustomVector2: Equatable {}
public struct CustomVector3 {
let x: Float
let y: Float
let z: Float
public init(x: Float, y: Float, z: Float) {
self.x = x
self.y = y
self.z = z
}
public init<T where T: CollectionType, T.Generator.Element == Float>(collection: T) {
var g = collection.generate()
guard let x = g.next(), let y = g.next(), let z = g.next() else {
fatalError()
}
self.init(x: x, y: y, z: z)
}
}
extension CustomVector3: Vector {
public typealias Index = Int
public static let additionIdentity: CustomVector3 = CustomVector3(collection: [0, 0, 0])
public static let multiplicationIdentity: CustomVector3 = CustomVector3(collection: [1, 1, 1])
public var numberOfDimensions: Int { return 3 }
public subscript(index: Int) -> Float {
switch index {
case 0:
return self.x
case 1:
return self.y
case 2:
return self.z
default:
fatalError()
}
}
}
extension CustomVector3: Equatable {} | mit | bcf426c747b567176382abef0a012db2 | 19.245283 | 98 | 0.682517 | 3.230422 | false | false | false | false |
delannoyk/SoundcloudSDK | sources/SoundcloudSDK/model/Activity.swift | 1 | 1056 | //
// Activity.swift
// Soundcloud
//
// Created by Kevin DELANNOY on 03/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import Foundation
public enum Activity {
case trackActivity(Track)
case trackSharing(Track)
case playlistActivity(Playlist)
}
extension Activity {
init?(JSON: JSONObject) {
guard let type = JSON["type"].stringValue else {
return nil
}
switch type {
case "track":
guard let track = Track(JSON: JSON["origin"]) else {
return nil
}
self = .trackActivity(track)
case "track-sharing", "track-repost":
guard let track = Track(JSON: JSON["origin"]) else {
return nil
}
self = .trackSharing(track)
case "playlist":
guard let playlist = Playlist(JSON: JSON["origin"]) else {
return nil
}
self = .playlistActivity(playlist)
default:
return nil
}
}
}
| mit | 1b3170e2dff71bb188d02fe022b0f65f | 21.934783 | 70 | 0.536493 | 4.586957 | false | false | false | false |
mastersoftwaresolutions/Iphone-Swift-Widgets-ios8 | Mausam/TodayViewController.swift | 1 | 13473 | //
// TodayViewController.swift
// Mausam
//
// Created by Poonam Parmar on 3/14/15.
// Copyright (c) 2015 MSS. All rights reserved.
//
import UIKit
import NotificationCenter
import CoreLocation
@objc (TodayViewController)
class TodayViewController: UIViewController, NCWidgetProviding, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var waitLbl :UILabel = UILabel()
// forecast.io apiKey
private let apiKey = "011f57a8593545db6f22c0a975829f6d"
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
self.preferredContentSize = CGSizeMake(0,250);
waitLbl.backgroundColor = UIColor .clearColor()
waitLbl.textColor = UIColor .whiteColor()
waitLbl.textAlignment = NSTextAlignment.Center
waitLbl.text = "Please wait.."
waitLbl.font = UIFont.boldSystemFontOfSize(15)
self.waitLbl.hidden = false
self.view.addSubview(waitLbl)
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
if UIScreen.mainScreen().nativeBounds.height == 480 {
waitLbl.frame = CGRectMake(0, 100, 320, 40)
}
if UIScreen.mainScreen().nativeBounds.height == 960 {
waitLbl.frame = CGRectMake(0, 100, 320, 40)
}
if UIScreen.mainScreen().nativeBounds.height == 1136 {
waitLbl.frame = CGRectMake(0, 100, 320, 40)
}
if UIScreen.mainScreen().nativeBounds.height == 1334 {
waitLbl.frame = CGRectMake(0, 100, 375, 40)
}
if UIScreen.mainScreen().nativeBounds.height == 2208 {
waitLbl.frame = CGRectMake(0, 100, 414, 40) }
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsetsZero;
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.NewData)
}
// MARK: Location
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue:CLLocationCoordinate2D = manager.location.coordinate
println("locations = \(locValue.latitude), \(locValue.longitude)")
locationManager.stopUpdatingLocation()
var string1 = locValue.latitude
var string2 = locValue.longitude
var appleSummary = "\(string1),\(string2)"
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
let forecastURL = NSURL(string: "\(string1),\(string2)", relativeToURL: baseURL)
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil){
let dataObject = NSData(contentsOfURL: location)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
let currentWeather = Weather(weatherDictionary: weatherDictionary)
var backImage:UIImageView = UIImageView()
backImage.frame = CGRectMake(0, 0, self.view.frame.size.width, 250)
self.view.addSubview(backImage)
var profileImage:UIImageView = UIImageView()
self.view.addSubview(profileImage)
var dateLbl :UILabel = UILabel()
dateLbl.backgroundColor = UIColor .clearColor()
dateLbl.textColor = UIColor .whiteColor()
dateLbl.textAlignment = NSTextAlignment.Center
dateLbl.font = UIFont.boldSystemFontOfSize(16)
self.view.addSubview(dateLbl)
var tempLbl :UILabel = UILabel()
tempLbl.backgroundColor = UIColor .clearColor()
tempLbl.textColor = UIColor .whiteColor()
tempLbl.textAlignment = NSTextAlignment.Center
tempLbl.font = UIFont.boldSystemFontOfSize(50)
self.view.addSubview(tempLbl)
var humidLbl :UILabel = UILabel()
humidLbl.backgroundColor = UIColor .clearColor()
humidLbl.textColor = UIColor .whiteColor()
humidLbl.textAlignment = NSTextAlignment.Left
humidLbl.text = "Humidity"
humidLbl.font = UIFont.boldSystemFontOfSize(16)
self.view.addSubview(humidLbl)
var humidIsLbl :UILabel = UILabel()
humidIsLbl.backgroundColor = UIColor .clearColor()
humidIsLbl.textColor = UIColor .whiteColor()
humidIsLbl.textAlignment = NSTextAlignment.Left
humidIsLbl.font = UIFont.boldSystemFontOfSize(16)
self.view.addSubview(humidIsLbl)
var rainLbl :UILabel = UILabel()
rainLbl.backgroundColor = UIColor .clearColor()
rainLbl.textColor = UIColor .whiteColor()
rainLbl.text = "Rain"
rainLbl.textAlignment = NSTextAlignment.Left
rainLbl.font = UIFont.boldSystemFontOfSize(16)
self.view.addSubview(rainLbl)
var rainIsLbl :UILabel = UILabel()
rainIsLbl.backgroundColor = UIColor .clearColor()
rainIsLbl.textColor = UIColor .whiteColor()
rainIsLbl.textAlignment = NSTextAlignment.Left
rainIsLbl.font = UIFont.boldSystemFontOfSize(16)
self.view.addSubview(rainIsLbl)
var discriptionLbl :UILabel = UILabel()
discriptionLbl.backgroundColor = UIColor .clearColor()
discriptionLbl.textColor = UIColor .whiteColor()
discriptionLbl.textAlignment = NSTextAlignment.Center
discriptionLbl.font = UIFont.boldSystemFontOfSize(25)
self.view.addSubview(discriptionLbl)
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
if UIScreen.mainScreen().nativeBounds.height == 480 {
profileImage.frame = CGRectMake(130, 10, 50, 50)
dateLbl.frame = CGRectMake(0, 60, 320, 40)
tempLbl.frame = CGRectMake(0, 80, 320, 80)
humidLbl.frame = CGRectMake(30, 120, 100, 80)
humidIsLbl.frame = CGRectMake(30, 145, 150, 80)
rainLbl.frame = CGRectMake(240, 120, 70, 80)
rainIsLbl.frame = CGRectMake(240, 145, 70, 80)
discriptionLbl.frame = CGRectMake(0, 190, 320, 60)
}
if UIScreen.mainScreen().nativeBounds.height == 960 {
profileImage.frame = CGRectMake(130, 10, 50, 50)
dateLbl.frame = CGRectMake(0, 60, 320, 40)
tempLbl.frame = CGRectMake(0, 80, 320, 80)
humidLbl.frame = CGRectMake(30, 120, 100, 80)
humidIsLbl.frame = CGRectMake(30, 145, 150, 80)
rainLbl.frame = CGRectMake(240, 120, 70, 80)
rainIsLbl.frame = CGRectMake(240, 145, 70, 80)
discriptionLbl.frame = CGRectMake(0, 190, 320, 60)
}
if UIScreen.mainScreen().nativeBounds.height == 1136 {
profileImage.frame = CGRectMake(130, 10, 50, 50)
dateLbl.frame = CGRectMake(0, 60, 320, 40)
tempLbl.frame = CGRectMake(0, 80, 320, 80)
humidLbl.frame = CGRectMake(30, 120, 100, 80)
humidIsLbl.frame = CGRectMake(30, 145, 150, 80)
rainLbl.frame = CGRectMake(240, 120, 70, 80)
rainIsLbl.frame = CGRectMake(240, 145, 70, 80)
discriptionLbl.frame = CGRectMake(0, 190, 320, 60)
}
if UIScreen.mainScreen().nativeBounds.height == 1334 {
profileImage.frame = CGRectMake(180, 10, 50, 50)
dateLbl.frame = CGRectMake(0, 60, 375, 40)
tempLbl.frame = CGRectMake(0, 80, 375, 80)
humidLbl.frame = CGRectMake(30, 120, 100, 80)
humidIsLbl.frame = CGRectMake(30, 145, 150, 80)
rainLbl.frame = CGRectMake(240, 120, 70, 80)
rainIsLbl.frame = CGRectMake(240, 145, 70, 80)
discriptionLbl.frame = CGRectMake(0, 190, 375, 60)
}
if UIScreen.mainScreen().nativeBounds.height == 2208 {
profileImage.frame = CGRectMake(180, 10, 50, 50)
dateLbl.frame = CGRectMake(0, 60, 414, 40)
tempLbl.frame = CGRectMake(0, 80, 414, 80)
humidLbl.frame = CGRectMake(70, 120, 100, 80)
humidIsLbl.frame = CGRectMake(70, 145, 150, 80)
rainLbl.frame = CGRectMake(280, 120, 70, 80)
rainIsLbl.frame = CGRectMake(280, 145, 70, 80)
discriptionLbl.frame = CGRectMake(0, 190, 414, 60)
}
}
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.waitLbl.hidden = true
backImage.image = currentWeather.Backicon!
profileImage.image = currentWeather.icon!
let formatter = NSDateFormatter()
formatter.timeStyle = .ShortStyle
dateLbl.text = formatter.stringFromDate(NSDate())
var Ftemp:Double
Ftemp = currentWeather.temperature
var CelciusTemp:Double
CelciusTemp = (Ftemp - 32.0) / 1.8
var resultTemp = NSString(format:"%.f", CelciusTemp)
tempLbl.text = "\(resultTemp)°"
discriptionLbl.text = "\(currentWeather.summary)"
humidIsLbl.text = "\(Int(currentWeather.humidity * 100))%"
rainIsLbl.text = "\(Int(currentWeather.precipProbability))%"
// })
}
else {
self.waitLbl.hidden = true
var noImage:UIImageView = UIImageView()
noImage.frame = CGRectMake(0, 0, self.view.frame.size.width, 250)
noImage.image = UIImage (named: "Clearnight")
self.view.addSubview(noImage)
let networkIssueController = UIAlertController(title: "Error", message: "Unable to load", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
networkIssueController.addAction(okButton)
let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
networkIssueController.addAction(cancelButton)
self.presentViewController(networkIssueController, animated: true, completion: nil)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
})
}
})
downloadTask.resume()
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error while updating location " + error.localizedDescription)
}
}
| gpl-2.0 | 3d9cef1d1f7be7940b66e2698d5512f8 | 41.904459 | 194 | 0.526128 | 5.882969 | false | false | false | false |
meetkei/KxUI | KxUI/Device/KUDevice.swift | 1 | 2261 | //
// Copyright (c) 2016 Keun young Kim <[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 Foundation
import CoreTelephony
public struct KUDevice {
public static var mainScreenWidth: CGFloat {
return UIScreen.main.bounds.width
}
public static var mainScreenHeight: CGFloat {
return UIScreen.main.bounds.height
}
public static var mainScreenBounds: CGRect {
return UIScreen.main.bounds
}
public static func canPhoneCall() -> Bool {
var canCall = false
let url = URL(string: "tel://")
if UIApplication.shared.canOpenURL(url!) {
let info = CTTelephonyNetworkInfo()
guard let carrier = info.subscriberCellularProvider else {
return canCall
}
let mnc = carrier.mobileNetworkCode
#if swift(>=3.2)
if let mnc = mnc, mnc.count > 0 {
canCall = true
}
#else
if let mnc = mnc, mnc.characters.count > 0 {
canCall = true
}
#endif
}
return canCall
}
}
| mit | 1cf3fb44298046179902adbe8ab7943c | 30.84507 | 81 | 0.636002 | 4.820896 | false | false | false | false |
huonw/swift | test/Serialization/Recovery/typedefs.swift | 1 | 17387 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-sil -o - -emit-module-path %t/Lib.swiftmodule -module-name Lib -I %S/Inputs/custom-modules -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck -check-prefix CHECK-VTABLE %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules | %FileCheck %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules -Xcc -DBAD > %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY %s < %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY-NEGATIVE %s < %t.txt
// RUN: %target-swift-frontend -typecheck -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST -DVERIFY %s -verify
// RUN: %target-swift-frontend -emit-silgen -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s | %FileCheck -check-prefix CHECK-SIL %s
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/custom-modules -DTEST %s | %FileCheck -check-prefix CHECK-IR %s
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s | %FileCheck -check-prefix CHECK-IR %s
#if TEST
import Typedefs
import Lib
// CHECK-SIL-LABEL: sil hidden @$S8typedefs11testSymbolsyyF
func testSymbols() {
// Check that the symbols are not using 'Bool'.
// CHECK-SIL: function_ref @$S3Lib1xs5Int32Vvau
_ = Lib.x
// CHECK-SIL: function_ref @$S3Lib9usesAssocs5Int32VSgvau
_ = Lib.usesAssoc
} // CHECK-SIL: end sil function '$S8typedefs11testSymbolsyyF'
// CHECK-IR-LABEL: define{{.*}} void @"$S8typedefs18testVTableBuilding4usery3Lib4UserC_tF
public func testVTableBuilding(user: User) {
// The important thing in this CHECK line is the "i64 30", which is the offset
// for the vtable slot for 'lastMethod()'. If the layout here
// changes, please check that offset is still correct.
// CHECK-IR-NOT: ret
// CHECK-IR: getelementptr inbounds void (%T3Lib4UserC*)*, void (%T3Lib4UserC*)** %{{[0-9]+}}, {{i64 30|i32 33}}
_ = user.lastMethod()
} // CHECK-IR: ret void
#if VERIFY
let _: String = useAssoc(ImportedType.self) // expected-error {{cannot convert value of type 'Int32?' to specified type 'String'}}
let _: Bool? = useAssoc(ImportedType.self) // expected-error {{cannot convert value of type 'Int32?' to specified type 'Bool?'}}
let _: Int32? = useAssoc(ImportedType.self)
let _: String = useAssoc(AnotherType.self) // expected-error {{cannot convert value of type 'AnotherType.Assoc?' (aka 'Optional<Int32>') to specified type 'String'}}
let _: Bool? = useAssoc(AnotherType.self) // expected-error {{cannot convert value of type 'AnotherType.Assoc?' (aka 'Optional<Int32>') to specified type 'Bool?'}}
let _: Int32? = useAssoc(AnotherType.self)
let _ = wrapped // expected-error {{use of unresolved identifier 'wrapped'}}
let _ = unwrapped // okay
_ = usesWrapped(nil) // expected-error {{use of unresolved identifier 'usesWrapped'}}
_ = usesUnwrapped(nil) // expected-error {{'nil' is not compatible with expected argument type 'Int32'}}
let _: WrappedAlias = nil // expected-error {{use of undeclared type 'WrappedAlias'}}
let _: UnwrappedAlias = nil // expected-error {{'nil' cannot initialize specified type 'UnwrappedAlias' (aka 'Int32')}} expected-note {{add '?'}}
let _: ConstrainedWrapped<Int> = nil // expected-error {{use of undeclared type 'ConstrainedWrapped'}}
let _: ConstrainedUnwrapped<Int> = nil // expected-error {{type 'Int' does not conform to protocol 'HasAssoc'}}
func testExtensions(wrapped: WrappedInt, unwrapped: UnwrappedInt) {
wrapped.wrappedMethod() // expected-error {{value of type 'WrappedInt' (aka 'Int32') has no member 'wrappedMethod'}}
unwrapped.unwrappedMethod() // expected-error {{value of type 'UnwrappedInt' has no member 'unwrappedMethod'}}
***wrapped // This one works because of the UnwrappedInt extension.
***unwrapped // expected-error {{cannot convert value of type 'UnwrappedInt' to expected argument type 'Int32'}}
let _: WrappedProto = wrapped // expected-error {{value of type 'WrappedInt' (aka 'Int32') does not conform to specified type 'WrappedProto'}}
let _: UnwrappedProto = unwrapped // expected-error {{value of type 'UnwrappedInt' does not conform to specified type 'UnwrappedProto'}}
}
public class UserDynamicSub: UserDynamic {
override init() {}
}
// FIXME: Bad error message; really it's that the convenience init hasn't been
// inherited.
_ = UserDynamicSub(conveniently: 0) // expected-error {{argument passed to call that takes no arguments}}
public class UserDynamicConvenienceSub: UserDynamicConvenience {
override init() {}
}
_ = UserDynamicConvenienceSub(conveniently: 0)
public class UserSub : User {} // expected-error {{cannot inherit from class 'User' because it has overridable members that could not be loaded}}
#endif // VERIFY
#else // TEST
import Typedefs
prefix operator ***
// CHECK-LABEL: class User {
// CHECK-RECOVERY-LABEL: class User {
open class User {
// CHECK: var unwrappedProp: UnwrappedInt?
// CHECK-RECOVERY: var unwrappedProp: Int32?
public var unwrappedProp: UnwrappedInt?
// CHECK: var wrappedProp: WrappedInt?
// CHECK-RECOVERY: /* placeholder for _ */
// CHECK-RECOVERY: /* placeholder for _ */
// CHECK-RECOVERY: /* placeholder for _ */
public var wrappedProp: WrappedInt?
// CHECK: func returnsUnwrappedMethod() -> UnwrappedInt
// CHECK-RECOVERY: func returnsUnwrappedMethod() -> Int32
public func returnsUnwrappedMethod() -> UnwrappedInt { fatalError() }
// CHECK: func returnsWrappedMethod() -> WrappedInt
// CHECK-RECOVERY: /* placeholder for returnsWrappedMethod() */
public func returnsWrappedMethod() -> WrappedInt { fatalError() }
// CHECK: func constrainedUnwrapped<T>(_: T) where T : HasAssoc, T.Assoc == UnwrappedInt
// CHECK-RECOVERY: func constrainedUnwrapped<T>(_: T) where T : HasAssoc, T.Assoc == Int32
public func constrainedUnwrapped<T: HasAssoc>(_: T) where T.Assoc == UnwrappedInt { fatalError() }
// CHECK: func constrainedWrapped<T>(_: T) where T : HasAssoc, T.Assoc == WrappedInt
// CHECK-RECOVERY: /* placeholder for constrainedWrapped(_:) */
public func constrainedWrapped<T: HasAssoc>(_: T) where T.Assoc == WrappedInt { fatalError() }
// CHECK: subscript(_: WrappedInt) -> () { get }
// CHECK-RECOVERY: /* placeholder for _ */
public subscript(_: WrappedInt) -> () { return () }
// CHECK: subscript<T>(_: T) -> () where T : HasAssoc, T.Assoc == WrappedInt { get }
// CHECK-RECOVERY: /* placeholder for _ */
public subscript<T: HasAssoc>(_: T) -> () where T.Assoc == WrappedInt { return () }
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public init(wrapped: WrappedInt) {}
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
// CHECK: convenience init<T>(generic: T) where T : HasAssoc, T.Assoc == WrappedInt
// CHECK-RECOVERY: /* placeholder for init(generic:) */
public convenience init<T: HasAssoc>(generic: T) where T.Assoc == WrappedInt { self.init() }
// CHECK: required init(wrappedRequired: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequired:) */
public required init(wrappedRequired: WrappedInt) {}
// CHECK: {{^}} init(wrappedRequiredInSub: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredInSub:) */
public init(wrappedRequiredInSub: WrappedInt) {}
// CHECK: dynamic init(wrappedDynamic: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedDynamic:) */
@objc public dynamic init(wrappedDynamic: WrappedInt) {}
// CHECK: dynamic required init(wrappedRequiredDynamic: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredDynamic:) */
@objc public dynamic required init(wrappedRequiredDynamic: WrappedInt) {}
public func lastMethod() {}
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// This is mostly to check when changes are necessary for the CHECK-IR lines
// above.
// CHECK-VTABLE-LABEL: sil_vtable [serialized] User {
// (10 words of normal class metadata on 64-bit platforms, 13 on 32-bit)
// 10 CHECK-VTABLE-NEXT: #User.unwrappedProp!getter.1:
// 11 CHECK-VTABLE-NEXT: #User.unwrappedProp!setter.1:
// 12 CHECK-VTABLE-NEXT: #User.unwrappedProp!materializeForSet.1:
// 13 CHECK-VTABLE-NEXT: #User.wrappedProp!getter.1:
// 14 CHECK-VTABLE-NEXT: #User.wrappedProp!setter.1:
// 15 CHECK-VTABLE-NEXT: #User.wrappedProp!materializeForSet.1:
// 16 CHECK-VTABLE-NEXT: #User.returnsUnwrappedMethod!1:
// 17 CHECK-VTABLE-NEXT: #User.returnsWrappedMethod!1:
// 18 CHECK-VTABLE-NEXT: #User.constrainedUnwrapped!1:
// 19 CHECK-VTABLE-NEXT: #User.constrainedWrapped!1:
// 20 CHECK-VTABLE-NEXT: #User.subscript!getter.1:
// 21 CHECK-VTABLE-NEXT: #User.subscript!getter.1:
// 22 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 23 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 24 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 25 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 26 CHECK-VTABLE-NEXT: #User.init!allocator.1:
// 27 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 28 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 29 CHECK-VTABLE-NEXT: #User.init!allocator.1:
// 30 CHECK-VTABLE-NEXT: #User.lastMethod!1:
// CHECK-VTABLE: }
// CHECK-LABEL: class UserConvenience
// CHECK-RECOVERY-LABEL: class UserConvenience
open class UserConvenience {
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: convenience init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public convenience init(wrapped: WrappedInt) { self.init() }
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserDynamic
// CHECK-RECOVERY-LABEL: class UserDynamic
open class UserDynamic {
// CHECK: init()
// CHECK-RECOVERY: init()
@objc public dynamic init() {}
// CHECK: init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
@objc public dynamic init(wrapped: WrappedInt) {}
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
@objc public dynamic convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserDynamicConvenience
// CHECK-RECOVERY-LABEL: class UserDynamicConvenience
open class UserDynamicConvenience {
// CHECK: init()
// CHECK-RECOVERY: init()
@objc public dynamic init() {}
// CHECK: convenience init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
@objc public dynamic convenience init(wrapped: WrappedInt) { self.init() }
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
@objc public dynamic convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserSub
// CHECK-RECOVERY-LABEL: class UserSub
open class UserSub : User {
// CHECK: init(wrapped: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public override init(wrapped: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequired: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequired:) */
public required init(wrappedRequired: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequiredInSub: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredInSub:) */
public required override init(wrappedRequiredInSub: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequiredDynamic: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredDynamic:) */
public required init(wrappedRequiredDynamic: WrappedInt) { super.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-DAG: let x: MysteryTypedef
// CHECK-RECOVERY-DAG: let x: Int32
public let x: MysteryTypedef = 0
public protocol HasAssoc {
associatedtype Assoc
}
extension ImportedType: HasAssoc {}
public struct AnotherType: HasAssoc {
public typealias Assoc = MysteryTypedef
}
public func useAssoc<T: HasAssoc>(_: T.Type) -> T.Assoc? { return nil }
// CHECK-DAG: let usesAssoc: ImportedType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc: Int32?
public let usesAssoc = useAssoc(ImportedType.self)
// CHECK-DAG: let usesAssoc2: AnotherType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc2: AnotherType.Assoc?
public let usesAssoc2 = useAssoc(AnotherType.self)
// CHECK-DAG: let wrapped: WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: let wrapped:
public let wrapped = WrappedInt(0)
// CHECK-DAG: let unwrapped: UnwrappedInt
// CHECK-RECOVERY-DAG: let unwrapped: Int32
public let unwrapped: UnwrappedInt = 0
// CHECK-DAG: let wrappedMetatype: WrappedInt.Type
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedMetatype:
public let wrappedMetatype = WrappedInt.self
// CHECK-DAG: let wrappedOptional: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedOptional:
public let wrappedOptional: WrappedInt? = nil
// CHECK-DAG: let wrappedIUO: WrappedInt!
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedIUO:
public let wrappedIUO: WrappedInt! = nil
// CHECK-DAG: let wrappedArray: [WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedArray:
public let wrappedArray: [WrappedInt] = []
// CHECK-DAG: let wrappedDictionary: [Int : WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedDictionary:
public let wrappedDictionary: [Int: WrappedInt] = [:]
// CHECK-DAG: let wrappedTuple: (WrappedInt, Int)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple:
public let wrappedTuple: (WrappedInt, Int)? = nil
// CHECK-DAG: let wrappedTuple2: (Int, WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple2:
public let wrappedTuple2: (Int, WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure: ((WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure:
public let wrappedClosure: ((WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosure2: (() -> WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure2:
public let wrappedClosure2: (() -> WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure3: ((Int, WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure3:
public let wrappedClosure3: ((Int, WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosureInout: ((inout WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosureInout:
public let wrappedClosureInout: ((inout WrappedInt) -> Void)? = nil
// CHECK-DAG: var wrappedFirst: WrappedInt?
// CHECK-DAG: var normalSecond: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFirst:
// CHECK-RECOVERY-DAG: var normalSecond: Int?
public var wrappedFirst: WrappedInt?, normalSecond: Int?
// CHECK-DAG: var normalFirst: Int?
// CHECK-DAG: var wrappedSecond: WrappedInt?
// CHECK-RECOVERY-DAG: var normalFirst: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedSecond:
public var normalFirst: Int?, wrappedSecond: WrappedInt?
// CHECK-DAG: var wrappedThird: WrappedInt?
// CHECK-DAG: var wrappedFourth: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedThird:
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFourth:
public var wrappedThird, wrappedFourth: WrappedInt?
// CHECK-DAG: func usesWrapped(_ wrapped: WrappedInt)
// CHECK-RECOVERY-NEGATIVE-NOT: func usesWrapped(
public func usesWrapped(_ wrapped: WrappedInt) {}
// CHECK-DAG: func usesUnwrapped(_ unwrapped: UnwrappedInt)
// CHECK-RECOVERY-DAG: func usesUnwrapped(_ unwrapped: Int32)
public func usesUnwrapped(_ unwrapped: UnwrappedInt) {}
// CHECK-DAG: func returnsWrapped() -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrapped(
public func returnsWrapped() -> WrappedInt { fatalError() }
// CHECK-DAG: func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrappedGeneric<
public func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt { fatalError() }
public protocol WrappedProto {}
public protocol UnwrappedProto {}
public typealias WrappedAlias = WrappedInt
public typealias UnwrappedAlias = UnwrappedInt
public typealias ConstrainedWrapped<T: HasAssoc> = T where T.Assoc == WrappedInt
public typealias ConstrainedUnwrapped<T: HasAssoc> = T where T.Assoc == UnwrappedInt
// CHECK-LABEL: extension Int32 : UnwrappedProto {
// CHECK-NEXT: func unwrappedMethod()
// CHECK-NEXT: prefix static func *** (x: UnwrappedInt)
// CHECK-NEXT: }
// CHECK-RECOVERY-LABEL: extension Int32 : UnwrappedProto {
// CHECK-RECOVERY-NEXT: func unwrappedMethod()
// CHECK-RECOVERY-NEXT: prefix static func *** (x: Int32)
// CHECK-RECOVERY-NEXT: }
// CHECK-RECOVERY-NEGATIVE-NOT: extension UnwrappedInt
extension UnwrappedInt: UnwrappedProto {
public func unwrappedMethod() {}
public static prefix func ***(x: UnwrappedInt) {}
}
// CHECK-LABEL: extension WrappedInt : WrappedProto {
// CHECK-NEXT: func wrappedMethod()
// CHECK-NEXT: prefix static func *** (x: WrappedInt)
// CHECK-NEXT: }
// CHECK-RECOVERY-NEGATIVE-NOT: extension WrappedInt
extension WrappedInt: WrappedProto {
public func wrappedMethod() {}
public static prefix func ***(x: WrappedInt) {}
}
#endif // TEST
| apache-2.0 | 51700b2b8c4bca57704bd821c967e7e0 | 42.359102 | 240 | 0.721574 | 3.938165 | false | false | false | false |
tapouillo/BMGlyphLabelSwift | bmGlyphLabelS/GameViewController.swift | 1 | 1417 | //
// GameViewController.swift
// bmGlyphLabelS
//
// Created by Stéphane QUERAUD on 20/02/2016.
// Copyright (c) 2016 Stéphane QUERAUD. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .aspectFill
skView.presentScene(scene)
}
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| mit | a04c1f50d59ef9687b34eb3a3e714009 | 25.698113 | 94 | 0.605654 | 5.421456 | false | false | false | false |
proxyco/RxBluetoothKit | Tests/FakePeripheral.swift | 1 | 4907 | // The MIT License (MIT)
//
// Copyright (c) 2016 Polidea
//
// 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 RxSwift
import CoreBluetooth
import RxTests
@testable
import RxBluetoothKit
class FakePeripheral: RxPeripheralType {
var name: String? = nil
var state: CBPeripheralState = CBPeripheralState.Connected
var rx_state: Observable<CBPeripheralState> = .never()
var services: [RxServiceType]? = nil
var identifier: NSUUID = NSUUID()
var RSSI: Int? = nil
var rx_didUpdateName: Observable<String?> = .never()
var rx_didModifyServices: Observable<[RxServiceType]> = .never()
var rx_didReadRSSI: Observable<(Int, NSError?)> = .never()
var rx_didDiscoverServices: Observable<([RxServiceType]?, NSError?)> = .never()
var rx_didDiscoverIncludedServicesForService: Observable<(RxServiceType, NSError?)> = .never()
var rx_didDiscoverCharacteristicsForService: Observable<(RxServiceType, NSError?)> = .never()
var rx_didUpdateValueForCharacteristic: Observable<(RxCharacteristicType, NSError?)> = .never()
var rx_didWriteValueForCharacteristic: Observable<(RxCharacteristicType, NSError?)> = .never()
var rx_didUpdateNotificationStateForCharacteristic: Observable<(RxCharacteristicType, NSError?)> = .never()
var rx_didDiscoverDescriptorsForCharacteristic: Observable<(RxCharacteristicType, NSError?)> = .never()
var rx_didUpdateValueForDescriptor: Observable<(RxDescriptorType, NSError?)> = .never()
var rx_didWriteValueForDescriptor: Observable<(RxDescriptorType, NSError?)> = .never()
var discoverServicesTO: TestableObserver<[CBUUID]?>?
func discoverServices(serviceUUIDs: [CBUUID]?) {
discoverServicesTO?.onNext(serviceUUIDs)
}
var discoverCharacteristicsTO: TestableObserver<([CBUUID]?, RxServiceType)>?
func discoverCharacteristics(characteristicUUIDs: [CBUUID]?, forService: RxServiceType) {
discoverCharacteristicsTO?.onNext((characteristicUUIDs, forService))
}
var discoverIncludedServicesTO: TestableObserver<([CBUUID]?, RxServiceType)>?
func discoverIncludedServices(includedServiceUUIDs: [CBUUID]?, forService service: RxServiceType) {
discoverIncludedServicesTO?.onNext((includedServiceUUIDs, service))
}
var readValueForCharacteristicTO: TestableObserver<RxCharacteristicType>?
func readValueForCharacteristic(characteristic: RxCharacteristicType) {
readValueForCharacteristicTO?.onNext(characteristic)
}
var writeValueForCharacteristicTypeTO: TestableObserver<(NSData, RxCharacteristicType, CBCharacteristicWriteType)>?
func writeValue(data: NSData, forCharacteristic characteristic: RxCharacteristicType, type: CBCharacteristicWriteType) {
writeValueForCharacteristicTypeTO?.onNext((data, characteristic, type))
}
var setNotifyValueForCharacteristicTO: TestableObserver<(Bool, RxCharacteristicType)>?
func setNotifyValue(enabled: Bool, forCharacteristic characteristic: RxCharacteristicType) {
setNotifyValueForCharacteristicTO?.onNext((enabled, characteristic))
}
var discoverDescriptorsForCharacteristicTO: TestableObserver<RxCharacteristicType>?
func discoverDescriptorsForCharacteristic(characteristic: RxCharacteristicType) {
discoverDescriptorsForCharacteristicTO?.onNext(characteristic)
}
var readValueForDescriptorTO: TestableObserver<RxDescriptorType>?
func readValueForDescriptor(descriptor: RxDescriptorType) {
readValueForDescriptorTO?.onNext(descriptor)
}
var writeValueForDescriptorTO: TestableObserver<(NSData, RxDescriptorType)>?
func writeValue(data: NSData, forDescriptor descriptor: RxDescriptorType) {
writeValueForDescriptorTO?.onNext((data, descriptor))
}
var readRSSITO: TestableObserver<Void>?
func readRSSI() {
readRSSITO?.onNext()
}
}
| mit | cb0610cd4584f54119bb0ea39017b0a2 | 46.640777 | 124 | 0.764826 | 5.464365 | false | true | false | false |
CPRTeam/CCIP-iOS | Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift | 3 | 3437 | // CryptoSwift
//
// Copyright (C) 2014-2018 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public class BlockDecryptor: Cryptor, Updatable {
private let blockSize: Int
private let padding: Padding
private var worker: CipherModeWorker
private var accumulated = Array<UInt8>()
init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws {
self.blockSize = blockSize
self.padding = padding
self.worker = worker
}
public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
self.accumulated += bytes
// If a worker (eg GCM) can combine ciphertext + tag
// we need to remove tag from the ciphertext.
if !isLast && self.accumulated.count < self.blockSize + self.worker.additionalBufferSize {
return []
}
let accumulatedWithoutSuffix: Array<UInt8>
if self.worker.additionalBufferSize > 0 {
// FIXME: how slow is that?
accumulatedWithoutSuffix = Array(self.accumulated.prefix(self.accumulated.count - self.worker.additionalBufferSize))
} else {
accumulatedWithoutSuffix = self.accumulated
}
var processedBytesCount = 0
var plaintext = Array<UInt8>(reserveCapacity: accumulatedWithoutSuffix.count)
// Processing in a block-size manner. It's good for block modes, but bad for stream modes.
for var chunk in accumulatedWithoutSuffix.batched(by: self.blockSize) {
if isLast || (accumulatedWithoutSuffix.count - processedBytesCount) >= blockSize {
let isLastChunk = processedBytesCount + chunk.count == accumulatedWithoutSuffix.count
if isLast, isLastChunk, var finalizingWorker = worker as? FinalizingDecryptModeWorker {
chunk = try finalizingWorker.willDecryptLast(bytes: chunk + accumulated.suffix(worker.additionalBufferSize)) // tag size
}
if !chunk.isEmpty {
plaintext += worker.decrypt(block: chunk)
}
if isLast, isLastChunk, var finalizingWorker = worker as? FinalizingDecryptModeWorker {
plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice))
}
processedBytesCount += chunk.count
}
}
accumulated.removeFirst(processedBytesCount) // super-slow
if isLast {
plaintext = self.padding.remove(from: plaintext, blockSize: self.blockSize)
}
return plaintext
}
public func seek(to position: Int) throws {
guard var worker = self.worker as? SeekableModeWorker else {
fatalError("Not supported")
}
try worker.seek(to: position)
self.worker = worker
accumulated = []
}
}
| gpl-3.0 | f4e1bce507907e36b1cda0ef022aac48 | 39.423529 | 217 | 0.717986 | 4.662144 | false | false | false | false |
wang-chuanhui/CHSDK | Source/FileSystem/Item.swift | 1 | 3791 | //
// Item.swift
// CHSDK
//
// Created by 王传辉 on 2017/8/4.
// Copyright © 2017年 王传辉. All rights reserved.
//
import Foundation
class Item {
let component: String
var superItem: Item?
var subItems: [Item] = [] {
didSet {
hiddenFalse = subItems.filter({ (item) -> Bool in
return (item.attribute[FileAttributeKey.extensionHidden] as? Bool) == false
})
}
}
var hiddenFalse: [Item] = []
static let root = Item(component: NSHomeDirectory(), superItem: nil)
init(component: String, superItem: Item?) {
self.component = component
self.superItem = superItem
}
func reloadSubItems() {
subItems.removeAll()
let sub = (try? FileManager.default.contentsOfDirectory(atPath: path)) ?? []
subItems.append(contentsOf: sub.map({Item(component: $0, superItem: self)}))
}
}
extension Item {
subscript(index: Int) -> Item {
return subItems[index]
}
var count: Int {
return subItems.count
}
var isDirectory: Bool {
var isD: ObjCBool = ObjCBool(false)
_ = FileManager.default.fileExists(atPath: path, isDirectory: &isD)
return isD.boolValue
}
var fileSize: UInt64 {
reloadSubItems()
let attribute = self.attribute
var size = (attribute[FileAttributeKey.size] as? UInt64) ?? 0
size = subItems.reduce(size, {$0 + $1.fileSize})
subItems.removeAll()
return size
}
func fileSize(completed: @escaping (Item, UInt64) -> ()) {
DispatchQueue.global().async {
let path = self.path
let manager = FileManager.default;
let sub = manager.subpaths(atPath: path) ?? []
let attribute = try? manager.attributesOfItem(atPath: path)
var size = (attribute?[FileAttributeKey.size] as? UInt64) ?? 0
size = sub.reduce(size, { (result, subPath) -> UInt64 in
let attribute = try? manager.attributesOfItem(atPath: path + "/" + subPath)
let size = (attribute?[FileAttributeKey.size] as? UInt64) ?? 0
return result + size
})
DispatchQueue.main.async {
completed(self, size)
}
}
}
var attribute: [FileAttributeKey: Any] {
do {
return try FileManager.default.attributesOfItem(atPath: path)
} catch {
return [:]
}
}
var isDeletable: Bool {
return FileManager.default.isDeletableFile(atPath: path)
}
}
extension Item: Equatable {
public static func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.isEqual(rhs)
}
}
extension Item {
func isEqual(_ item: Item) -> Bool {
let l = self as AnyObject
let r = item as AnyObject
return l.isEqual(r)
}
}
extension Item {
var lastPathComponent: String {
return components.last ?? ""
}
var title: String {
let path = self.path
if path == NSHomeDirectory() {
return "root"
}
return (path as NSString).lastPathComponent
}
var components: [String] {
guard let superItem = superItem else {
return (component as NSString).pathComponents
}
return superItem.components + [component]
}
var path: String {
return NSString.path(withComponents: components)
}
var subPaths: [String] {
return subItems.map({$0.path}) + subItems.reduce([], {$0 + $1.subPaths})
}
}
extension Item: CustomStringConvertible {
var description: String {
return subPaths.description
}
}
| mit | c867dc7d25c3aefb4a725b67b1f6a50c | 23.842105 | 91 | 0.562765 | 4.447585 | false | false | false | false |
wujianguo/GitHubKit | GitHubApp/Classes/Authorization/GitHubAccount.swift | 1 | 5525 | //
// GitHubAccount.swift
// GitHubKit
//
// Created by wujianguo on 16/7/26.
//
//
import Foundation
import UIKit
import SafariServices
import GitHubKit
import ObjectMapper
extension String {
var md5 : String{
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen);
CC_MD5(str!, strLen, result);
let hash = NSMutableString();
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i]);
}
result.destroy();
return String(format: hash as String)
}
}
class GitHubAccount {
static let sharedInstance = GitHubAccount()
class func config(clientID: String, scope: String) {
sharedInstance.clientID = clientID
sharedInstance.scope = scope
}
private var access_token: String?
private var token_type: String?
private var currentUserJsonFile: NSURL? {
if let dir = NSFileManager.defaultManager().URLsForDirectory(.DocumentationDirectory, inDomains: .UserDomainMask).first {
if !NSFileManager.defaultManager().fileExistsAtPath(dir.absoluteString) {
do {
try NSFileManager.defaultManager().createDirectoryAtURL(dir, withIntermediateDirectories: true, attributes: nil)
} catch {
}
}
return dir.URLByAppendingPathComponent("current_user.json")
}
return nil
}
private init() {
// todo: save to keychain, icloud
access_token = NSUserDefaults.standardUserDefaults().stringForKey("access_token")
token_type = NSUserDefaults.standardUserDefaults().stringForKey("token_type")
if let file = currentUserJsonFile {
if let data = NSData(contentsOfURL: file) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: [.AllowFragments])
GitHubKit.currentUser = Mapper<User>(context: nil).map(json)!
} catch {
}
}
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GitHubAccount.handleCurrentUserInfoNotification(_:)), name: GitHubCurrentUserInfoNotificationName, object: nil)
GitHubAuthorization.config(access_token, token_type: token_type) { (completion) in
self.authCompletion = completion
self.timestamp = NSDate(timeIntervalSinceNow: 0).timeIntervalSince1970
self.state = self.sign(self.clientID, t: self.timestamp)
let components = NSURLComponents(string: "https://github.com/login/oauth/authorize")!
let query = [
NSURLQueryItem(name: "client_id", value: self.clientID),
NSURLQueryItem(name: "scope", value: self.scope),
NSURLQueryItem(name: "state", value: self.state!),
]
components.queryItems = query
let url = components.URL!
dispatch_async(dispatch_get_main_queue()) {
self.authVC = SFSafariViewController(URL: url)
let topVC = UIApplication.sharedApplication().topViewController
topVC.presentViewController(self.authVC!, animated: true, completion: nil)
}
}
}
@objc func handleCurrentUserInfoNotification(notification: NSNotification) {
if let file = currentUserJsonFile, user = GitHubKit.currentUser {
do {
try user.toJSONString()?.writeToURL(file, atomically: true, encoding: NSUTF8StringEncoding)
} catch {
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: GitHubCurrentUserInfoNotificationName, object: nil)
}
private var timestamp: NSTimeInterval = 0
private var state: String?
private var authVC: SFSafariViewController?
private func sign(key: String, t: NSTimeInterval) -> String {
let origin = "\(key)\(timestamp)"
return "\(origin.md5),\(timestamp)"
}
private func getQueryStringParameter(url: String, param: String) -> String? {
if let url = NSURLComponents(string: url) {
if let query = url.queryItems {
return (query.filter { $0.name == param }).first?.value
}
}
return nil
}
private var clientID: String! = nil
private var scope: String! = nil
private var authCompletion: AuthorizationCompletion?
func openURL(url: NSURL) -> Bool {
guard url.scheme == "wjggithub" && url.host == "auth" else { return false }
access_token = getQueryStringParameter(url.absoluteString, param: "access_token")
token_type = getQueryStringParameter(url.absoluteString, param: "token_type")
NSUserDefaults.standardUserDefaults().setValue(access_token, forKey: "access_token")
NSUserDefaults.standardUserDefaults().setValue(token_type, forKey: "token_type")
authVC?.dismissViewControllerAnimated(true) {
self.authCompletion?(access_token: self.access_token!, token_type: self.token_type)
self.authVC = nil
self.authCompletion = nil
}
return true
}
class func openURL(url: NSURL) -> Bool {
return sharedInstance.openURL(url)
}
} | mit | e972f3529fc92511defb5cb469d5f135 | 33.322981 | 194 | 0.629683 | 5.013612 | false | false | false | false |
hironytic/Kiretan0 | Kiretan0/Resource/String/R+String.swift | 1 | 2705 | //
// R+String.swift
// Kiretan0
//
// Copyright (c) 2017 Hironori Ichimiya <[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 Foundation
public extension R {
public enum String: Swift.String {
case cancel = "Kiretan0.cancel"
case sufficient = "Kiretan0.sufficient"
case insufficient = "Kiretan0.insufficient"
case deselectAll = "Kiretan0.deselect_all"
case makeInsufficient = "Kiretan0.make_insufficient"
case makeSufficient = "Kiretan0.make_sufficient"
case addSufficientItem = "Kiretan0.add_sufficient_item"
case addInsufficientItem = "Kiretan0.add_insufficient_item"
case doAddItem = "Kiretan0.do_add_item"
case errorItemList = "Kiretan0.error_item_list"
case errorItem = "Kiretan0.error_item"
case settingTitle = "Kiretan0.setting_title"
case settingTeam = "Kiretan0.setting_team"
case settingTeamPreferences = "Kiretan0.setting_team_preferences"
case teamSelectionTitle = "Kiretan0.team_selection_title"
}
public enum StringFormat: Swift.String {
case foo = "Foo"
}
}
public extension R.String {
public func localized() -> Swift.String {
return NSLocalizedString(rawValue, comment: "")
}
}
public extension R.StringFormat {
public func localized(_ arguments: CVarArg...) -> Swift.String {
return localized(arguments: arguments)
}
public func localized(arguments: [CVarArg]) -> Swift.String {
let formatString = NSLocalizedString(rawValue, comment: "")
return Swift.String(format:formatString, arguments: arguments)
}
}
| mit | 232fddbf0c349de7a683bfb0face36a8 | 38.202899 | 80 | 0.708318 | 4.405537 | false | false | false | false |
jopamer/swift | test/SILGen/protocols.swift | 1 | 23197 |
// RUN: %target-swift-emit-silgen -module-name protocols -enable-sil-ownership %s | %FileCheck %s
//===----------------------------------------------------------------------===//
// Calling Existential Subscripts
//===----------------------------------------------------------------------===//
protocol SubscriptableGet {
subscript(a : Int) -> Int { get }
}
protocol SubscriptableGetSet {
subscript(a : Int) -> Int { get set }
}
var subscriptableGet : SubscriptableGet
var subscriptableGetSet : SubscriptableGetSet
func use_subscript_rvalue_get(_ i : Int) -> Int {
return subscriptableGet[i]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_rvalue_get
// CHECK: bb0(%0 : @trivial $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$S9protocols16subscriptableGetAA013SubscriptableC0_pvp : $*SubscriptableGet
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGet to $*[[OPENED:@opened(.*) SubscriptableGet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*SubscriptableGet
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGet.subscript!getter.1
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]])
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]]
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_get(_ i : Int) -> Int {
return subscriptableGetSet[i]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_get
// CHECK: bb0(%0 : @trivial $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$S9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!getter.1
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]])
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*SubscriptableGetSet
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_set(_ i : Int) {
subscriptableGetSet[i] = i
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_set
// CHECK: bb0(%0 : @trivial $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$S9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet
// CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!setter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, %0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Subscripts
//===----------------------------------------------------------------------===//
func use_subscript_archetype_rvalue_get<T : SubscriptableGet>(_ generic : T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_rvalue_get
// CHECK: bb0(%0 : @trivial $*T, %1 : @trivial $Int):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGet.subscript!getter.1
// CHECK-NEXT: apply [[METH]]<T>(%1, [[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK: } // end sil function '${{.*}}use_subscript_archetype_rvalue_get
func use_subscript_archetype_lvalue_get<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_get
// CHECK: bb0(%0 : @trivial $*T, %1 : @trivial $Int):
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T
// CHECK: [[GUARANTEEDSTACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr [[READ]] to [initialization] [[GUARANTEEDSTACK]] : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!getter.1
// CHECK-NEXT: [[APPLYRESULT:%[0-9]+]] = apply [[METH]]<T>(%1, [[GUARANTEEDSTACK]])
// CHECK-NEXT: destroy_addr [[GUARANTEEDSTACK]] : $*T
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: dealloc_stack [[GUARANTEEDSTACK]] : $*T
// CHECK: return [[APPLYRESULT]]
func use_subscript_archetype_lvalue_set<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) {
generic[idx] = idx
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_set
// CHECK: bb0(%0 : @trivial $*T, %1 : @trivial $Int):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!setter.1
// CHECK-NEXT: apply [[METH]]<T>(%1, %1, [[WRITE]])
//===----------------------------------------------------------------------===//
// Calling Existential Properties
//===----------------------------------------------------------------------===//
protocol PropertyWithGetter {
var a : Int { get }
}
protocol PropertyWithGetterSetter {
var b : Int { get set }
}
var propertyGet : PropertyWithGetter
var propertyGetSet : PropertyWithGetterSetter
func use_property_rvalue_get() -> Int {
return propertyGet.a
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_rvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$S9protocols11propertyGetAA18PropertyWithGetter_pvp : $*PropertyWithGetter
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetter to $*[[OPENED:@opened(.*) PropertyWithGetter]]
// CHECK: [[COPY:%.*]] = alloc_stack $[[OPENED]]
// CHECK-NEXT: copy_addr [[PROJ]] to [initialization] [[COPY]] : $*[[OPENED]]
// CHECK-NEXT: end_access [[READ]] : $*PropertyWithGetter
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetter.a!getter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[COPY]])
func use_property_lvalue_get() -> Int {
return propertyGetSet.b
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$S9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[STACK]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!getter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[STACK]])
func use_property_lvalue_set(_ x : Int) {
propertyGetSet.b = x
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_set
// CHECK: bb0(%0 : @trivial $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @$S9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter
// CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!setter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Properties
//===----------------------------------------------------------------------===//
func use_property_archetype_rvalue_get<T : PropertyWithGetter>(_ generic : T) -> Int {
return generic.a
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_rvalue_get
// CHECK: bb0(%0 : @trivial $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetter.a!getter.1
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]]
// CHECK-NEXT: dealloc_stack [[STACK]]
// CHECK: } // end sil function '{{.*}}use_property_archetype_rvalue_get
func use_property_archetype_lvalue_get<T : PropertyWithGetterSetter>(_ generic : T) -> Int {
return generic.b
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_get
// CHECK: bb0(%0 : @trivial $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]] : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!getter.1
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK: } // end sil function '${{.*}}use_property_archetype_lvalue_get
func use_property_archetype_lvalue_set<T : PropertyWithGetterSetter>(_ generic: inout T, v : Int) {
generic.b = v
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_set
// CHECK: bb0(%0 : @trivial $*T, %1 : @trivial $Int):
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!setter.1
// CHECK-NEXT: apply [[METH]]<T>(%1, [[WRITE]])
//===----------------------------------------------------------------------===//
// Calling Initializers
//===----------------------------------------------------------------------===//
protocol Initializable {
init(int: Int)
}
// CHECK-LABEL: sil hidden @$S9protocols27use_initializable_archetype{{[_0-9a-zA-Z]*}}F
func use_initializable_archetype<T: Initializable>(_ t: T, i: Int) {
// CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T
// CHECK: [[T_META:%[0-9]+]] = metatype $@thick T.Type
// CHECK: [[T_INIT:%[0-9]+]] = witness_method $T, #Initializable.init!allocator.1 : {{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[T_RESULT_ADDR:%[0-9]+]] = apply [[T_INIT]]<T>([[T_RESULT]], %1, [[T_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[T_RESULT]] : $*T
// CHECK: dealloc_stack [[T_RESULT]] : $*T
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
T(int: i)
}
// CHECK: sil hidden @$S9protocols29use_initializable_existential{{[_0-9a-zA-Z]*}}F
func use_initializable_existential(_ im: Initializable.Type, i: Int) {
// CHECK: bb0([[IM:%[0-9]+]] : @trivial $@thick Initializable.Type, [[I:%[0-9]+]] : @trivial $Int):
// CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[IM]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type
// CHECK: [[TEMP_VALUE:%[0-9]+]] = alloc_stack $Initializable
// CHECK: [[TEMP_ADDR:%[0-9]+]] = init_existential_addr [[TEMP_VALUE]] : $*Initializable, $@opened([[N]]) Initializable
// CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method $@opened([[N]]) Initializable, #Initializable.init!allocator.1 : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[TEMP_ADDR]], [[I]], [[ARCHETYPE_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[TEMP_VALUE]] : $*Initializable
// CHECK: dealloc_stack [[TEMP_VALUE]] : $*Initializable
im.init(int: i)
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
//===----------------------------------------------------------------------===//
// Protocol conformance and witness table generation
//===----------------------------------------------------------------------===//
class ClassWithGetter : PropertyWithGetter {
var a: Int {
get {
return 42
}
}
}
// Make sure we are generating a protocol witness that calls the class method on
// ClassWithGetter.
// CHECK-LABEL: sil private [transparent] [thunk] @$S9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW : $@convention(witness_method: PropertyWithGetter) (@in_guaranteed ClassWithGetter) -> Int {
// CHECK: bb0([[C:%.*]] : @trivial $*ClassWithGetter):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetter, #ClassWithGetter.a!getter.1 : (ClassWithGetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]] from %0
// CHECK-NEXT: return
class ClassWithGetterSetter : PropertyWithGetterSetter, PropertyWithGetter {
var a: Int {
get {
return 1
}
set {}
}
var b: Int {
get {
return 2
}
set {}
}
}
// CHECK-LABEL: sil private [transparent] [thunk] @$S9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW : $@convention(witness_method: PropertyWithGetterSetter) (@in_guaranteed ClassWithGetterSetter) -> Int {
// CHECK: bb0([[C:%.*]] : @trivial $*ClassWithGetterSetter):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetterSetter, #ClassWithGetterSetter.b!getter.1 : (ClassWithGetterSetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetterSetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]] from %0
// CHECK-NEXT: return
// Stored variables fulfilling property requirements
//
class ClassWithStoredProperty : PropertyWithGetter {
var a : Int = 0
// Make sure that accesses go through the generated accessors for classes.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden @$S9protocols23ClassWithStoredPropertyC011methodUsingE0SiyF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithStoredProperty):
// CHECK-NEXT: debug_value [[ARG]]
// CHECK-NOT: copy_value
// CHECK-NEXT: [[FUN:%.*]] = class_method [[ARG]] : $ClassWithStoredProperty, #ClassWithStoredProperty.a!getter.1 : (ClassWithStoredProperty) -> () -> Int, $@convention(method) (@guaranteed ClassWithStoredProperty) -> Int
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[ARG]])
// CHECK-NOT: destroy_value
// CHECK-NEXT: return [[RESULT]] : $Int
}
struct StructWithStoredProperty : PropertyWithGetter {
var a : Int
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden @$S9protocols24StructWithStoredPropertyV011methodUsingE0SiyF
// CHECK: bb0(%0 : @trivial $StructWithStoredProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredProperty, #StructWithStoredProperty.a
// CHECK-NEXT: return %2 : $Int
}
// Make sure that we generate direct function calls for out struct protocol
// witness since structs don't do virtual calls for methods.
//
// *NOTE* Even though at first glance the copy_addr looks like a leak
// here, StructWithStoredProperty is a trivial struct implying that no
// leak is occurring. See the test with StructWithStoredClassProperty
// that makes sure in such a case we don't leak. This is due to the
// thunking code being too dumb but it is harmless to program
// correctness.
//
// CHECK-LABEL: sil private [transparent] [thunk] @$S9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW : $@convention(witness_method: PropertyWithGetter) (@in_guaranteed StructWithStoredProperty) -> Int {
// CHECK: bb0([[C:%.*]] : @trivial $*StructWithStoredProperty):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [trivial] [[C]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @$S9protocols24StructWithStoredPropertyV1aSivg : $@convention(method) (StructWithStoredProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: return
class C {}
// Make sure that if the getter has a class property, we pass it in
// in_guaranteed and don't leak.
struct StructWithStoredClassProperty : PropertyWithGetter {
var a : Int
var c: C = C()
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden @$S9protocols29StructWithStoredClassPropertyV011methodUsingF0SiyF
// CHECK: bb0(%0 : @guaranteed $StructWithStoredClassProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredClassProperty, #StructWithStoredClassProperty.a
// CHECK-NEXT: return %2 : $Int
}
// CHECK-LABEL: sil private [transparent] [thunk] @$S9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW : $@convention(witness_method: PropertyWithGetter) (@in_guaranteed StructWithStoredClassProperty) -> Int {
// CHECK: bb0([[C:%.*]] : @trivial $*StructWithStoredClassProperty):
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow [[C]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @$S9protocols29StructWithStoredClassPropertyV1aSivg : $@convention(method) (@guaranteed StructWithStoredClassProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: end_borrow [[CCOPY_LOADED]] from %0
// CHECK-NEXT: return
// rdar://22676810
protocol ExistentialProperty {
var p: PropertyWithGetterSetter { get set }
}
func testExistentialPropertyRead<T: ExistentialProperty>(_ t: inout T) {
let b = t.p.b
}
// CHECK-LABEL: sil hidden @$S9protocols27testExistentialPropertyRead{{[_0-9a-zA-Z]*}}F
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T
// CHECK: [[P_TEMP:%.*]] = alloc_stack $PropertyWithGetterSetter
// CHECK: [[T_TEMP:%.*]] = alloc_stack $T
// CHECK: copy_addr [[READ]] to [initialization] [[T_TEMP]] : $*T
// CHECK: [[P_GETTER:%.*]] = witness_method $T, #ExistentialProperty.p!getter.1 :
// CHECK-NEXT: apply [[P_GETTER]]<T>([[P_TEMP]], [[T_TEMP]])
// CHECK-NEXT: destroy_addr [[T_TEMP]]
// CHECK-NEXT: [[OPEN:%.*]] = open_existential_addr immutable_access [[P_TEMP]] : $*PropertyWithGetterSetter to $*[[P_OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[T0:%.*]] = alloc_stack $[[P_OPENED]]
// CHECK-NEXT: copy_addr [[OPEN]] to [initialization] [[T0]]
// CHECK-NEXT: [[B_GETTER:%.*]] = witness_method $[[P_OPENED]], #PropertyWithGetterSetter.b!getter.1
// CHECK-NEXT: apply [[B_GETTER]]<[[P_OPENED]]>([[T0]])
// CHECK-NEXT: debug_value
// CHECK-NEXT: destroy_addr [[T0]]
// CHECK-NOT: witness_method
// CHECK: return
func modify(_ x: inout Int) {}
// Make sure we call the materializeForSet callback with the correct
// generic signature.
func modifyProperty<T : PropertyWithGetterSetter>(_ x: inout T) {
modify(&x.b)
}
// CHECK-LABEL: sil hidden @$S9protocols14modifyPropertyyyxzAA0C16WithGetterSetterRzlF
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T
// CHECK: [[WITNESS_FN:%.*]] = witness_method $T, #PropertyWithGetterSetter.b!materializeForSet.1
// CHECK: [[RESULT:%.*]] = apply [[WITNESS_FN]]<T>
// CHECK: [[TEMPORARY:%.*]] = tuple_extract [[RESULT]]
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[RESULT]]
// CHECK: [[TEMPORARY_ADDR_TMP:%.*]] = pointer_to_address [[TEMPORARY]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[TEMPORARY_ADDR:%.*]] = mark_dependence [[TEMPORARY_ADDR_TMP]] : $*Int on [[WRITE]] : $*T
// CHECK: [[TEMPORARY_ACCESS:%.*]] = begin_access [modify] [unsafe] [[TEMPORARY_ADDR]] : $*Int
// CHECK: [[MODIFY_FN:%.*]] = function_ref @$S9protocols6modifyyySizF
// CHECK: apply [[MODIFY_FN]]([[TEMPORARY_ACCESS]])
// CHECK: switch_enum [[CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
// CHECK: bb1([[CALLBACK_ADDR:%.*]] : @trivial $Builtin.RawPointer):
// CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]]
// CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[TEMPORARY:%.*]] = address_to_pointer [[TEMPORARY_ACCESS]] : $*Int to $Builtin.RawPointer
// CHECK: apply [[CALLBACK]]<T>
public struct Val {
public var x: Int = 0
}
public protocol Proto {
var val: Val { get nonmutating set}
}
public func test(_ p: Proto) {
p.val.x += 1
}
// CHECK-LABEL: sil @$S9protocols4testyyAA5Proto_pF : $@convention(thin) (@in_guaranteed Proto) -> ()
// CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access
// CHECK: [[MAT:%.*]] = witness_method $@opened("{{.*}}") Proto, #Proto.val!materializeForSet
// CHECK: [[BUF:%.*]] = apply [[MAT]]
// CHECK: [[WB:%.*]] = pointer_to_thin_function
// This use looks like it is mutating but really is not. We use to assert in the SIL verifier.
// CHECK: apply [[WB]]{{.*}}({{.*}}[[OPEN]]
// CHECK: return
// CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @$S9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetterSetter module protocols {
// CHECK-NEXT: method #PropertyWithGetterSetter.b!getter.1: {{.*}} : @$S9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW
// CHECK-NEXT: method #PropertyWithGetterSetter.b!setter.1: {{.*}} : @$S9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivsTW
// CHECK-NEXT: method #PropertyWithGetterSetter.b!materializeForSet.1: {{.*}} : @$S9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivmTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @$S9protocols21ClassWithGetterSetterCAA08PropertycD0A2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @$S9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredClassProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: {{.*}} : @$S9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW
// CHECK-NEXT: }
| apache-2.0 | 1e1c5db70131aeb23856896a003aed63 | 49.284165 | 272 | 0.642078 | 3.798296 | false | false | false | false |
Smartvoxx/ios | Step07/Start/SmartvoxxOnWrist Extension/UIColorExtension.swift | 2 | 2244 | //
// UIColorExtension.swift
// Smartvoxx
//
// Created by Sebastien Arbogast on 26/09/2015.
// Copyright © 2015 Epseelon. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.startIndex.advancedBy(1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
print("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
| gpl-2.0 | 2e8823ab7ff473d0cb425fa6ec59efbf | 40.537037 | 109 | 0.467677 | 4.093066 | false | false | false | false |
amdaza/Scoop-iOS-Client | ScoopClient/ScoopClient/ScoopsTableViewController.swift | 1 | 2911 | //
// ScoopsTableViewController.swift
// ScoopClient
//
// Created by Home on 8/11/16.
// Copyright © 2016 amdaza. All rights reserved.
//
import UIKit
class ScoopsTableViewController: UITableViewController {
var client: MSClient?
var model: [ScoopRecord]? = []
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
readAllItemsInTable()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - CRUD Scoops table
func readAllItemsInTable() {
let tableMS = client?.table(withName: "Scoops")
tableMS?.read { (results, error) in
if let _ = error {
print(error)
return
}
if !((self.model?.isEmpty)!) {
self.model?.removeAll()
}
if let items = results {
for item in items.items! {
self.model?.append(item as! [String: AnyObject])
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
if (model?.isEmpty)! {
return 0
}
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (model?.isEmpty)! {
return 0
}
return (model?.count)!
}
func tableView(withCellName cellId: String, _ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Create cell
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
// Configure the cell...
let item = model?[indexPath.row]
cell.textLabel?.text = item?["title"] as! String?
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Create a new variable to store the instance of PlayerTableViewController
if let destinationVC = segue.destination as? NewPostViewController{
destinationVC.client = self.client
}
}
}
| gpl-3.0 | 655a4a2536926d571a524a61fc16e978 | 25.697248 | 137 | 0.558419 | 5.418994 | false | false | false | false |
inacioferrarini/glasgow | Glasgow/Classes/Arrow/Transformer/ArrowArrayTransformer.swift | 1 | 2870 | // The MIT License (MIT)
//
// Copyright (c) 2017 Inácio Ferrarini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Arrow
/**
Uses `Arrow` to transform a given object of type AnyObject? into an array of target type, `Type`.
*/
open class ArrowArrayTransformer<Type: ArrowParsable>: Transformer, KeyPathTransformer {
/**
Default Initialization.
*/
public init() {}
/**
Transforms the input type AnyObject? and returns [`Type`] as output.
- parameter input: The object to be transformed.
- returns: `Type`
*/
public func transform(_ input: IType) -> OType {
return self.transform(input, keyPath: nil)
}
/**
Transforms the input type AnyObject? and returns [`Type`] as output.
- parameter input: The object to be transformed.
- parameter keyPath: If input type allows, use the given key path as the root object.
- returns: [`Type`]
*/
open func transform(_ input: AnyObject?, keyPath: String?) -> [Type]? {
guard let json = JSON(input) else { return nil }
if let keyPath = keyPath, keyPath.count > 0, let json = json[keyPath] {
return self.transformArray(json)
}
return self.transformArray(json)
}
/**
Transforms `json` into [`U`].
- parameter json: The `JSON` object to be transformed.
- returns: [`Type`]
*/
open func transformArray(_ json: JSON) -> [Type] {
var items = [Type]()
if let collection = json.collection {
for jsonEntry in collection {
var item = Type.init()
item.deserialize(jsonEntry)
items.append(item)
}
}
return items
}
}
| mit | d6e7e28b82156e53a989c9aa4865c481 | 32.360465 | 98 | 0.641338 | 4.525237 | false | false | false | false |
iXieYi/Weibo_DemoTest | Weibo_DemoTest/Weibo_DemoTest/Emoticon/UITextView+Emoticon.swift | 1 | 3017 | //
// UITextView+Emoticon.swift
// 表情键盘
//
// Created by 谢毅 on 17/1/4.
// Copyright © 2017年 xieyi. All rights reserved.
//
import UIKit
/*
代码复合: - 对重构完成的代码进行检查
1.修改注释:
2.确认是否需要进一步重构
3.再一次检查方法和返回值
*/
extension UITextView{
/// 表情图片字符串
///
/// - returns: 完整字符串内容
var emoticonText:String {
let attrText = attributedText
var strM = String()
//遍历属性文本
attrText.enumerateAttributesInRange(
NSRange(location: 0, length: attrText.length),//设置遍历范围
options: []) { (dict, range, _) -> Void in
//分段循环调试技巧
//如果字典中包含 NSTextAttachment 说明是图片
//否则是字符串,可以通过range 获得
//如何在attachment中包含该“哈哈”
if let attachment = dict["NSAttachment"] as? EmoticonAttchment{
print("图片\(attachment.emoticon)")
strM += attachment.emoticon.chs ?? ""
}else{
let str = (attrText.string as NSString).substringWithRange(range)
strM += str
}
}
return strM
}
//插入表情符号
func insertEmotion(em:Emoticon){
// text = em.chs
//1.空白表情
if em.isEmpty {
return
}
//2.删除按钮
if em.isRemoved{
deleteBackward()
return
}
//3.Emoji
if let emoji = em.emoji {
replaceRange(selectedTextRange!, withText: emoji)
return
}
//4.图片表情
insertImageEmotion(em)
//5.通知 代理 文本发生变化了 - textViewDidChange “?”代理如果什么都没有实现,更安全
delegate?.textViewDidChange?(self)
}
/// 插入图片表情
private func insertImageEmotion(em:Emoticon){
//1.图片属性文本
let imageText = EmoticonAttchment(emoticon: em).imageText(font!)
//2.插入到属性文本 ->装换成可变文本
let strM = NSMutableAttributedString(attributedString: attributedText)
//3.插入图片
strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
//4.替换属性文本(全部替换过)
//1>记录光标位置
let range = selectedRange
//2>替换文本
attributedText = strM
//3>恢复光标,length是表示之前选中的文本信息,在之后显示的长度,因为是替换掉的,所以设置为零
selectedRange = NSRange(location: range.location + 1, length: 0)
}
}
| mit | 94bf9234196b27d8558b01fe654b1594 | 23.712871 | 85 | 0.507612 | 4.425532 | false | false | false | false |
Raiden9000/Sonarus | PostsTable.swift | 1 | 3600 | //
// PostsTable.swift
// Sonarus
//
// Created by Christopher Arciniega on 8/28/17.
// Copyright © 2017 HQZenithLabs. All rights reserved.
//
import Foundation
class PostsTable:UITableViewController{
private var arrayOfPosts:[String] = []
private var user:String!
private var name:String!
private var profilePic:URL!
init(user: String, name:String) {
super.init(nibName: nil, bundle: nil)
self.user = user
self.name = name
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
tableView.separatorColor = UIColor.clear
tableView.alwaysBounceVertical = false
tableView.allowsMultipleSelectionDuringEditing = false
tableView.tableFooterView = UIView()//removes empty cells
tableView.dataSource = self
self.tableView.register(UserCell.self, forCellReuseIdentifier: "Posts")
//get session variable
if let sessionObj:AnyObject = UserDefaults.standard.value(forKey: "SpotifySession") as AnyObject?{
let sessionDataObj = sessionObj as! Data
let firstTimeSession = NSKeyedUnarchiver.unarchiveObject(with: sessionDataObj) as! SPTSession
session = firstTimeSession
}
//Get Firebase Profile Pic
let refQ = FIRDatabase.database().reference().child("Userbase/\(user!)/3Image/")
refQ.observeSingleEvent(of: .value, with: {(snapshot) in
let userImage = snapshot.value as! String
self.profilePic = URL(string: userImage)!
self.populatePosts()
})
}
private func populatePosts(){
//Generate key
let refQ = FIRDatabase.database().reference().child("Userbase/\(user!)/6Statuses/")
refQ.observeSingleEvent(of: .value, with: {(snapshot) in
for data in snapshot.children.allObjects as! [FIRDataSnapshot]{
guard let dataDict = data.value as? [String:Any] else {continue}
let status = dataDict["1status"] as? String
self.arrayOfPosts.insert(status!, at: 0)
}
self.tableView.reloadData()
})
}
public func addPostToTable(text:String){
arrayOfPosts.insert(text, at: 0)
tableView.reloadData()
}
//TableView setup
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfPosts.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(65)
}
override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//deque grabs cell that has already scrolled off of the screen, and resuses it. Saves mem, allows quicker scroll
let cell = tableView.dequeueReusableCell(withIdentifier: "Posts", for: indexPath) as? UserCell
cell?.hideFollowButton()
cell?.setUsername(userID: user!, displayName: name!)
let post = arrayOfPosts[indexPath.row]
cell?.setDisplayStatus(asStatus: post)
cell?.setProfilePic(imageURL: profilePic)
return cell!
}
}
| mit | 07e786810b9e06fd0e634838d6ac5636 | 34.633663 | 120 | 0.641845 | 4.930137 | false | false | false | false |
qiuncheng/study-for-swift | learn-rx-swift/learn-rx-swift/SampleTableViewController.swift | 1 | 1710 | //
// SampleTableViewController.swift
// learn-rx-swift
//
// Created by 程庆春 on 2017/1/4.
// Copyright © 2017年 Qiun Cheng. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
struct Data {
let name: String = ""
let subname: String = ""
}
class SampleTableViewController: UIViewController {
@IBOutlet weak var simpleTableView: UITableView!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let sss = Observable.just(
(0..<20).map {
"第\($0)行"
})
sss.bind(to: simpleTableView.rx.items(cellIdentifier: "cell", cellType: UITableViewCell.self)) { (row, element, cell) in
cell.textLabel?.text = element
}
.addDisposableTo(disposeBag)
simpleTableView.rx.modelSelected(String.self)
.subscribe(onNext: { [weak self] value in
self?.showAlertView(value: value)
})
.addDisposableTo(disposeBag)
}
func showAlertView(value: String) {
let alertView = UIAlertView(
title: "😃",
message: "你点击了\(value)",
delegate: nil,
cancelButtonTitle: "OK"
)
alertView.show()
}
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 | 2f7ce26a7f622a6f0a9addc5d5bb8e62 | 22.416667 | 124 | 0.667853 | 4.246851 | false | false | false | false |
itssofluffy/NanoMessage | Sources/NanoMessage/Core/NanoMessageError.swift | 1 | 6216 | /*
NanoMessageError.swift
Copyright (c) 2016, 2017 Stephen Whittle 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 CNanoMessage
import Foundation
/// Obtain the underlying libraries error message as a string.
///
/// - Parameters:
/// - code: Error code.
///
/// - Returns: The error string.
public func nanoMessageError(_ code: CInt) -> String {
return String(cString: nn_strerror(code))
}
private var _nanoMsgError = NanoMsgError()
/// A dictionary of nanomsg error codes and their POSIX codes as strings.
public var nanoMsgError: NanoMsgError {
if (_nanoMsgError.isEmpty) {
for symbol in symbolProperty.filter({ $0.namespace == .Error }) {
_nanoMsgError[symbol.value] = symbol.name
}
}
return _nanoMsgError
}
/// NanoMessage Error Domain.
public enum NanoMessageError: Error {
case NanoSocket(code: CInt)
case CloseFailed(code: CInt)
case Interrupted
case BindToEndPoint(code: CInt, url: URL, type: ConnectionType)
case ConnectToEndPoint(code: CInt, url: URL, type: ConnectionType)
case RemoveEndPoint(code: CInt, url: URL, endPointId: Int)
case BindToSocket(code: CInt, nanoSocketName: String)
case LoopBack(code: CInt)
case GetSocketOption(code: CInt, option: SocketOption)
case SetSocketOption(code: CInt, option: SocketOption)
case GetSocketStatistic(code: CInt, option: SocketStatistic)
case PollSocket(code: CInt)
case SocketIsADevice(socket: NanoSocket)
case NoEndPoint(socket: NanoSocket)
case SendMessage(code: CInt)
case MessageNotSent
case SendTimedOut(timeout: TimeInterval)
case ReceiveMessage(code: CInt)
case MessageNotAvailable
case ReceiveTimedOut(timeout: TimeInterval)
case DeadlineExpired(timeout: TimeInterval)
case FreeMessage(code: CInt)
case NoTopic
case TopicLength
case InvalidTopic
}
extension NanoMessageError: CustomStringConvertible {
public var description: String {
let errorString: (CInt) -> String = { code in
var errorMessage = nanoMessageError(code)
if let errorCode = nanoMsgError[code] {
errorMessage += " (#\(code) '\(errorCode)')"
} else {
errorMessage += " (#\(code))"
}
return errorMessage
}
switch self {
case .NanoSocket(let code):
return "nn_socket() failed: " + errorString(code)
case .CloseFailed(let code):
return "nn_close() failed: " + errorString(code)
case .Interrupted:
return "operation was interrupted"
case .BindToEndPoint(let code, let url, let type), .ConnectToEndPoint(let code, let url, let type):
return "createEndPoint(url: \(url.absoluteString), type: \(type)) failed: " + errorString(code)
case .RemoveEndPoint(let code, let url, let endPointId):
return "removeEndPoint(url: \(url.absoluteString)) endpoint.id: \(endPointId) failed: " + errorString(code)
case .BindToSocket(let code, let nanoSocketName):
return "bindToSocket(\(nanoSocketName)) failed: " + errorString(code)
case .LoopBack(let code):
return "loopBack() failed: " + errorString(code)
case .GetSocketOption(let code, let option):
return "getSocketOption(\(option)) failed: " + errorString(code)
case .SetSocketOption(let code, let option):
return "setSocketOption(\(option)) failed: " + errorString(code)
case .GetSocketStatistic(let code, let option):
return "getSocketStatistic(\(option)) failed: " + errorString(code)
case .PollSocket(let code):
return "pollSocket() failed: " + errorString(code)
case .SocketIsADevice(let socket):
return "NanoSocket \(socket.fileDescriptor) Is A Device"
case .NoEndPoint(let socket):
return "NanoSocket \(socket.fileDescriptor) Has No EndPoint(s)"
case .SendMessage(let code):
return "sendMessage() failed: " + errorString(code)
case .MessageNotSent:
return "message not sent"
case .ReceiveMessage(let code):
return "receiveMessage() failed: " + errorString(code)
case .MessageNotAvailable:
return "no message received"
case .SendTimedOut(let timeout), .ReceiveTimedOut(let timeout):
return "operation has timed out " + ((timeout < 0) ? "with an infinite timeout!" : "in \(timeout) second(s)")
case .DeadlineExpired(let timeout):
return "deadline of \(timeout) second(s) has been exceeded"
case .FreeMessage(let code):
return "nn_freemsg() failed: " + errorString(code)
case .NoTopic:
return "topic undefined"
case .TopicLength:
return "topic size > \(maximumTopicLength) bytes"
case .InvalidTopic:
return "topics of unequal length"
}
}
}
| mit | 17915b2e6d1c52f937398eb40c8d518e | 43.4 | 125 | 0.646879 | 4.652695 | false | false | false | false |
roambotics/swift | lib/ASTGen/Sources/ASTGen/Macros.swift | 1 | 6928 | import SwiftSyntax
@_spi(Testing) import _SwiftSyntaxMacros
extension SyntaxProtocol {
func token(at position: AbsolutePosition) -> TokenSyntax? {
// If the position isn't within this node at all, return early.
guard position >= self.position && position < self.endPosition else {
return nil
}
// If we are a token syntax, that's it!
if let token = Syntax(self).as(TokenSyntax.self) {
return token
}
// Otherwise, it must be one of our children.
return children(viewMode: .sourceAccurate).lazy.compactMap { child in
child.token(at: position)
}.first
}
}
/// Describes a macro that has been "exported" to the C++ part of the
/// compiler, with enough information to interface with the C++ layer.
struct ExportedMacro {
var macro: Macro.Type
}
/// Look up a macro with the given name.
///
/// Returns an unmanaged pointer to an ExportedMacro instance that describes
/// the specified macro. If there is no macro with the given name, produces
/// nil.
@_cdecl("swift_ASTGen_lookupMacro")
public func lookupMacro(
macroNamePtr: UnsafePointer<UInt8>
) -> UnsafeRawPointer? {
let macroSystem = MacroSystem.exampleSystem
// Look for a macro with this name.
let macroName = String(cString: macroNamePtr)
guard let macro = macroSystem.lookup(macroName) else { return nil }
// Allocate and initialize the exported macro.
let exportedPtr = UnsafeMutablePointer<ExportedMacro>.allocate(capacity: 1)
exportedPtr.initialize(to: .init(macro: macro))
return UnsafeRawPointer(exportedPtr)
}
/// Destroys the given macro.
@_cdecl("swift_ASTGen_destroyMacro")
public func destroyMacro(
macroPtr: UnsafeMutablePointer<UInt8>
) {
macroPtr.withMemoryRebound(to: ExportedMacro.self, capacity: 1) { macro in
macro.deinitialize(count: 1)
macro.deallocate()
}
}
/// Allocate a copy of the given string as a UTF-8 string.
private func allocateUTF8String(
_ string: String,
nullTerminated: Bool = false
) -> (UnsafePointer<UInt8>, Int) {
var string = string
return string.withUTF8 { utf8 in
let capacity = utf8.count + (nullTerminated ? 1 : 0)
let ptr = UnsafeMutablePointer<UInt8>.allocate(
capacity: capacity
)
if let baseAddress = utf8.baseAddress {
ptr.initialize(from: baseAddress, count: utf8.count)
}
if nullTerminated {
ptr[utf8.count] = 0
}
return (UnsafePointer<UInt8>(ptr), utf8.count)
}
}
/// Query the type signature of the given macro.
@_cdecl("swift_ASTGen_getMacroTypeSignature")
public func getMacroTypeSignature(
macroPtr: UnsafeMutablePointer<UInt8>,
evaluationContextPtr: UnsafeMutablePointer<UnsafePointer<UInt8>?>,
evaluationContextLengthPtr: UnsafeMutablePointer<Int>
) {
macroPtr.withMemoryRebound(to: ExportedMacro.self, capacity: 1) { macro in
(evaluationContextPtr.pointee, evaluationContextLengthPtr.pointee) =
allocateUTF8String(macro.pointee.evaluationContext, nullTerminated: true)
}
}
extension ExportedMacro {
var evaluationContext: String {
"""
struct __MacroEvaluationContext\(self.macro.genericSignature?.description ?? "") {
typealias SignatureType = \(self.macro.signature)
}
"""
}
}
/// Query the macro evaluation context of the given macro.
@_cdecl("swift_ASTGen_getMacroEvaluationContext")
public func getMacroEvaluationContext(
sourceFilePtr: UnsafePointer<UInt8>,
declContext: UnsafeMutableRawPointer,
context: UnsafeMutableRawPointer,
macroPtr: UnsafeMutablePointer<UInt8>,
contextPtr: UnsafeMutablePointer<UnsafeMutableRawPointer?>
) {
contextPtr.pointee = macroPtr.withMemoryRebound(to: ExportedMacro.self, capacity: 1) { macro in
return ASTGenVisitor(ctx: context, base: sourceFilePtr, declContext: declContext)
.visit(StructDeclSyntax(stringLiteral: macro.pointee.evaluationContext))
.rawValue
}
}
@_cdecl("swift_ASTGen_evaluateMacro")
@usableFromInline
func evaluateMacro(
sourceFilePtr: UnsafePointer<UInt8>,
sourceLocationPtr: UnsafePointer<UInt8>?,
expandedSourcePointer: UnsafeMutablePointer<UnsafePointer<UInt8>?>,
expandedSourceLength: UnsafeMutablePointer<Int>
) -> Int {
// We didn't expand anything so far.
expandedSourcePointer.pointee = nil
expandedSourceLength.pointee = 0
guard let sourceLocationPtr = sourceLocationPtr else {
print("NULL source location")
return -1
}
return sourceFilePtr.withMemoryRebound(
to: ExportedSourceFile.self, capacity: 1
) { (sourceFile: UnsafePointer<ExportedSourceFile>) -> Int in
// Find the offset.
let buffer = sourceFile.pointee.buffer
let offset = sourceLocationPtr - buffer.baseAddress!
if offset < 0 || offset >= buffer.count {
print("source location isn't inside this buffer")
return -1
}
let sf = sourceFile.pointee.syntax
guard let token = sf.token(at: AbsolutePosition(utf8Offset: offset)) else {
print("couldn't find token at offset \(offset)")
return -1
}
guard let parentSyntax = token.parent,
parentSyntax.is(MacroExpansionExprSyntax.self)
else {
print("not on a macro expansion node: \(token.recursiveDescription)")
return -1
}
let macroSystem = MacroSystem.exampleSystem
let converter = SourceLocationConverter(
file: sourceFile.pointee.fileName, tree: sf
)
let context = MacroEvaluationContext(
moduleName: sourceFile.pointee.moduleName,
sourceLocationConverter: converter
)
let evaluatedSyntax = parentSyntax.evaluateMacro(
with: macroSystem, context: context
) { error in
/* TODO: Report errors */
}
var evaluatedSyntaxStr = evaluatedSyntax.withoutTrivia().description
evaluatedSyntaxStr.withUTF8 { utf8 in
let evaluatedResultPtr = UnsafeMutablePointer<UInt8>.allocate(capacity: utf8.count + 1)
if let baseAddress = utf8.baseAddress {
evaluatedResultPtr.initialize(from: baseAddress, count: utf8.count)
}
evaluatedResultPtr[utf8.count] = 0
expandedSourcePointer.pointee = UnsafePointer(evaluatedResultPtr)
expandedSourceLength.pointee = utf8.count
}
return 0
}
}
/// Calls the given `allMacros: [Any.Type]` function pointer and produces a
/// newly allocated buffer containing metadata pointers.
@_cdecl("swift_ASTGen_getMacroTypes")
@usableFromInline
func getMacroTypes(
getterAddress: UnsafeRawPointer,
resultAddress: UnsafeMutablePointer<UnsafePointer<UnsafeRawPointer>?>,
count: UnsafeMutablePointer<Int>
) {
let getter = unsafeBitCast(
getterAddress, to: (@convention(thin) () -> [Any.Type]).self)
let metatypes = getter()
let address = UnsafeMutableBufferPointer<Any.Type>.allocate(
capacity: metatypes.count
)
_ = address.initialize(from: metatypes)
address.withMemoryRebound(to: UnsafeRawPointer.self) {
resultAddress.initialize(to: UnsafePointer($0.baseAddress))
}
count.initialize(to: address.count)
}
| apache-2.0 | fe9eb48defec86072c68f03d2941d7a8 | 31.223256 | 97 | 0.726328 | 4.357233 | false | false | false | false |
android/kotlin-multiplatform-samples | DiceRoller/iosApp/iosApp/SettingsViewModel.swift | 1 | 2917 | /*
* Copyright 2022 The Android Open Source Project
*
* 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
*
* https://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 shared
import Combine
import KMPNativeCoroutinesAsync
@MainActor
final class SettingsViewModel: ObservableObject {
private let repository = DiceSettingsRepository(dataStore: CreateDataStoreKt.createDataStore())
private var roller = DiceRoller()
@Published
var diceCount: Int = Int(DiceSettingsRepository.companion.DEFAULT_DICE_COUNT)
@Published
var sideCount: Int = Int(DiceSettingsRepository.companion.DEFAULT_SIDES_COUNT)
@Published
var uniqueRollsOnly: Bool = DiceSettingsRepository.companion.DEFAULT_UNIQUE_ROLLS_ONLY
@Published
var rollButtonLabel: String? = nil
@Published
private (set) var rollResultLabel: String? = nil
var isSettingsModified: Bool {
Int32(diceCount) != currentSettings?.diceCount ||
Int32(sideCount) != currentSettings?.sideCount ||
uniqueRollsOnly != currentSettings?.uniqueRollsOnly
}
private var currentSettings: DiceSettings? = nil
func startObservingSettings() async {
do {
let stream = asyncStream(for: repository.settingsNative)
for try await settings in stream {
self.diceCount = Int(settings.diceCount)
self.sideCount = Int(settings.sideCount)
self.uniqueRollsOnly = settings.uniqueRollsOnly
self.rollButtonLabel = String.localizedStringWithFormat(NSLocalizedString("game_roll_button", comment: ""), settings.diceCount, settings.sideCount)
self.currentSettings = settings
}
} catch {
print("Failed with error: \(error)")
}
}
func saveSettings() {
repository.saveSettings(diceCount: Int32(diceCount), sideCount: Int32(sideCount), uniqueRollsOnly: uniqueRollsOnly)
}
func rollDice() {
guard let settings = currentSettings else {
return
}
do {
let rolledNumbers: [KotlinInt] = try roller.rollDice(settings: settings)
rollResultLabel = String(
format: NSLocalizedString("game_result_success", comment: ""),
rolledNumbers.map(String.init).joined(separator: ", ")
)
} catch {
rollResultLabel = NSLocalizedString("game_result_error", comment: "")
}
}
}
| apache-2.0 | fa3f54e4207ceb5aed4bb69f6bd5d516 | 34.144578 | 163 | 0.672952 | 4.821488 | false | false | false | false |
kingslay/KSSwiftExtension | Core/Source/Extension/Then.swift | 1 | 1036 | //
// Then.swift
// Pods
//
// Created by king on 16/8/14.
//
//
import Foundation
public protocol Then {}
extension Then where Self: Any {
/// Makes it available to set properties with closures just after initializing.
///
/// let label = UILabel().then {
/// $0.textAlignment = .Center
/// $0.textColor = UIColor.blackColor()
/// $0.text = "Hello, World!"
/// }
public func then(@noescape block: inout Self -> Void) -> Self {
var copy = self
block(©)
return copy
}
}
extension Then where Self: AnyObject {
/// Makes it available to set properties with closures just after initializing.
///
/// let label = UILabel().then {
/// $0.textAlignment = .Center
/// $0.textColor = UIColor.blackColor()
/// $0.text = "Hello, World!"
/// }
public func then(@noescape block: Self -> Void) -> Self {
block(self)
return self
}
}
extension NSObject: Then {} | mit | 2bafed00640b3b0702d4489efe056e79 | 22.044444 | 83 | 0.546332 | 4.046875 | false | false | false | false |
caronae/caronae-ios | Caronae/User/WelcomeViewController.swift | 1 | 1164 | import UIKit
class WelcomeViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var welcomeImage: UIImageView!
convenience init() {
self.init(nibName: "WelcomeViewController", bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
let user = UserService.instance.user!
titleLabel.text = "Olá, " + user.firstName + "!"
navigationItem.titleView = UIImageView(image: UIImage(named: "NavigationBarLogo"))
// workaround to trigger the tintColor
// http://stackoverflow.com/a/30741478/2752598
let tintColor = welcomeImage.tintColor
welcomeImage.tintColor = nil
welcomeImage.tintColor = tintColor
}
@IBAction func continueTapped() {
let editProfileViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "EditProfileViewController") as! EditProfileViewController
editProfileViewController.completeProfileMode = true
navigationController?.setViewControllers([editProfileViewController], animated: true)
}
}
| gpl-3.0 | ee6a761bc8b056294fcfcf423d25aac0 | 36.516129 | 180 | 0.688736 | 5.460094 | false | false | false | false |
TimurBK/SwiftSampleProject | Pods/ProcedureKit/Sources/MutualExclusion.swift | 1 | 3208 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import Foundation
import Dispatch
/**
A generic condition for describing operations that
cannot be allowed to execute concurrently.
*/
public final class MutuallyExclusive<T>: Condition {
/// Public constructor
public init(category: String = "MutuallyExclusive<\(T.self)>") {
super.init()
name = "MutuallyExclusive<\(T.self)>"
mutuallyExclusiveCategory = category
}
/// Required public override, but there is no evaluation, so it just completes with `.Satisfied`.
public override func evaluate(procedure: Procedure, completion: @escaping (ConditionResult) -> Void) {
completion(.success(true))
}
}
final public class ExclusivityManager {
static let sharedInstance = ExclusivityManager()
fileprivate let queue = DispatchQueue(label: "run.kit.procedure.ProcedureKit.Exclusivity", qos: DispatchQoS.userInitiated) // serial dispatch queue
fileprivate var procedures: [String: [Procedure]] = [:]
private init() {
// A private initalizer prevents any other part of the app
// from creating an instance.
}
func add(procedure: Procedure, category: String) -> Operation? {
return queue.sync { _add(procedure: procedure, category: category) }
}
func remove(procedure: Procedure, category: String) {
queue.async { self._remove(procedure: procedure, category: category) }
}
fileprivate func _add(procedure: Procedure, category: String) -> Operation? {
procedure.log.verbose(message: ">>> \(category)")
procedure.addDidFinishBlockObserver { [unowned self] (procedure, errors) in
self.remove(procedure: procedure, category: category)
}
var proceduresWithThisCategory = procedures[category] ?? []
let previous = proceduresWithThisCategory.last
if let previous = previous {
procedure.add(dependencyOnPreviousMutuallyExclusiveProcedure: previous)
}
proceduresWithThisCategory.append(procedure)
procedures[category] = proceduresWithThisCategory
return previous
}
fileprivate func _remove(procedure: Procedure, category: String) {
procedure.log.verbose(message: "<<< \(category)")
if let proceduresWithThisCategory = procedures[category], let index = proceduresWithThisCategory.index(of: procedure) {
var mutableProceduresWithThisCategory = proceduresWithThisCategory
mutableProceduresWithThisCategory.remove(at: index)
procedures[category] = mutableProceduresWithThisCategory
}
}
}
public extension ExclusivityManager {
static func __tearDownForUnitTesting() {
sharedInstance.__tearDownForUnitTesting()
}
/// This should only be used as part of the unit testing
fileprivate func __tearDownForUnitTesting() {
queue.sync {
for (category, procedures) in procedures {
for procedure in procedures {
procedure.cancel()
_remove(procedure: procedure, category: category)
}
}
}
}
}
| mit | daf27f9d0a1682298eed7c0b0221be49 | 31.393939 | 151 | 0.668226 | 5.292079 | false | false | false | false |
thebrankoo/CryptoLab | CryptoLab/Message Auth/AuthExtensions.swift | 1 | 2611 | //
// AuthExtensions.swift
// CryptoLab
//
// Created by Branko Popovic on 3/13/17.
// Copyright © 2017 Branko Popovic. All rights reserved.
//
import Foundation
/**
CryptoLab Data extensions
*/
extension Data {
/**
Generates HMAC auth code form data
- parameter key: Auth code generation key
- parameter hasFunction: Auth code generation hash funcion
- returns: Generated HMAC auth code
*/
public func hmacAuthCode(withKey key: Data, hashFunction: AuthHashFunction) -> Data? {
let hmac = HMACAuth(key: key, hashFunction: hashFunction)
let authData = hmac.authenticationCode(forData: self)
return authData
}
/**
DSA signature of data
- parameter pubK: Public key
- parameter privK: Private key
- returns: Generated DSA signature of data
*/
public func dsaSign(publicKey pubK: Data, privateKey privK: Data) -> Data? {
let dsa = DSAAuth(publicKey: pubK, privateKey: privK)
let dsaSigned = dsa.sign(data: self)
return dsaSigned
}
/**
DSA public key verification of data with signature
- parameter signature: DSA generated signature
- parameter pubK: Public key
- returns: Bool that indicates if verification passed
*/
public func dsaVerify(withSignature signature: Data, publicKey pubK: Data) -> Bool {
let dsa = DSAAuth(publicKey: pubK)
let verify = dsa.verify(data: self, signature: signature)
return verify
}
}
/**
CryptoLab String extensions
*/
extension String {
/**
Generates HMAC auth code form string
- parameter key: Auth code generation key
- parameter hasFunction: Auth code generation hash funcion
- returns: Generated HMAC auth code
*/
public func hmacAuthCode(withKey key: Data, hashFunction: AuthHashFunction) -> Data? {
if let data = self.data(using: .utf8) {
return data.hmacAuthCode(withKey: key, hashFunction: hashFunction)
}
return nil
}
/**
DSA signature of string
- parameter pubK: Public key
- parameter privK: Private key
- returns: Generated DSA signature of string
*/
public func dsaSign(publicKey pubK: Data, privateKey privK: Data) -> Data? {
if let data = self.data(using: .utf8) {
return data.dsaSign(publicKey: pubK, privateKey: privK)
}
return nil
}
/**
DSA public key verification of string with signature
- parameter signature: DSA generated signature
- parameter pubK: Public key
- returns: Bool that indicates if verification passed
*/
public func dsaVerify(withSignature signature: Data, publicKey pubK: Data) -> Bool {
if let data = self.data(using: .utf8) {
return data.dsaVerify(withSignature: signature, publicKey: pubK)
}
return false
}
}
| mit | cf03229bc3fe2881c3eb2e0b14ad98d1 | 23.622642 | 87 | 0.721073 | 3.691655 | false | false | false | false |
alexdoloz/Gridy | Pod/Classes/Cell.swift | 1 | 665 | import Foundation
import CoreGraphics
/** Defines 2d cell with `Int` coordinates.*/
public struct Cell {
public var x = 0
public var y = 0
public var point: CGPoint {
return CGPoint(x: x, y: y)
}
public init(x: Int, y: Int) {
self.x = x
self.y = y
}
public init() {}
}
extension Cell: CustomStringConvertible {
public var description: String {
return "(\(x), \(y))"
}
}
extension Cell: Hashable {
public var hashValue: Int {
return x ^ y
}
}
// MARK: Operators
public func == (lhs: Cell, rhs: Cell) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
| mit | efa84695aac0323e0f7bceb2ee8ff131 | 14.465116 | 47 | 0.547368 | 3.653846 | false | false | false | false |
miracl/amcl | version3/swift/rom_c25519.swift | 1 | 2428 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
//
// rom.swift
//
// Created by Michael Scott on 12/06/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
public struct ROM{
#if D32
// Base Bits= 29
// Curve 25519 Modulus
static public let Modulus:[Chunk] = [0x1FFFFFED,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FFFFF]
static let R2modp:[Chunk] = [0x169000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let MConst:Chunk = 0x13
// Curve 25519
static let CURVE_Cof_I:Int = 8
static let CURVE_Cof:[Chunk] = [0x8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let CURVE_A:Int = 486662
static let CURVE_B_I:Int = 0
static let CURVE_B:[Chunk] = [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Order:[Chunk] = [0x1CF5D3ED,0x9318D2,0x1DE73596,0x1DF3BD45,0x14D,0x0,0x0,0x0,0x100000]
static public let CURVE_Gx:[Chunk] = [0x9,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Gy:[Chunk] = [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
#endif
#if D64
// Base Bits= 56
// Curve 25519 Modulus
static public let Modulus:[Chunk] = [0xFFFFFFFFFFFFED,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFF,0x7FFFFFFF]
static let R2modp:[Chunk] = [0xA4000000000000,0x5,0x0,0x0,0x0]
static let MConst:Chunk = 0x13
// Curve 25519
static let CURVE_Cof_I:Int = 8
static let CURVE_Cof:[Chunk] = [0x8,0x0,0x0,0x0,0x0]
static let CURVE_A:Int = 486662
static let CURVE_B_I:Int = 0
static let CURVE_B:[Chunk] = [0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Order:[Chunk] = [0x12631A5CF5D3ED,0xF9DEA2F79CD658,0x14DE,0x0,0x10000000]
static public let CURVE_Gx:[Chunk] = [0x9,0x0,0x0,0x0,0x0]
static public let CURVE_Gy:[Chunk] = [0x0,0x0,0x0,0x0,0x0]
#endif
}
| apache-2.0 | 28b17c1a0cb638b2b2fffb11af0d3dd4 | 32.722222 | 134 | 0.751647 | 2.475025 | false | false | false | false |
shvets/WebAPI | Sources/WebAPI/GoogleDocsAPI.swift | 1 | 10060 | import Foundation
import SwiftSoup
open class GoogleDocsAPI: HttpService {
// let SiteUrl = "http://cyro.se"
// let UserAgent = "Google Docs User Agent"
//
// func available() throws -> Elements {
// let document = try fetchDocument(SiteUrl, headers: getHeaders())
//
// return try document!.select("td.topic_content")
// }
//
// func getMovies(page: Int=1) throws -> ItemsList {
// return try getCategory(category: "movies", page: page)
// }
//
// func getSeries(page: Int=1) throws -> ItemsList {
// return try getCategory(category: "tvseries", page: page)
// }
//
// func getLatestEpisodes(page: Int=1) throws -> ItemsList {
// return try getCategory(category: "episodes", page: page)
// }
//
// func getLatest(page: Int=1) throws -> ItemsList {
// return try getCategory(category: "", page: page)
// }
//
// func getCategory(category: String="", page: Int=1) throws -> ItemsList {
// var data = [Any]()
// var paginationData: ItemsList = [:]
//
// var pagePath: String = ""
//
// if category != "" {
// pagePath = "/\(category)/index.php?" + "page=\(page)"
// }
// else {
// pagePath = "/index.php?show=latest-topics&" + "page=\(page)"
// }
//
// let document = try fetchDocument(SiteUrl + pagePath, headers: getHeaders())
//
// let items = try document!.select("td.topic_content")
//
// for item in items.array() {
// let href = try item.select("div a").attr("href")
//
// var path: String?
//
// if category != "" {
// path = "/\(category)/\(href)"
// }
// else {
// path = "/\(href)"
// }
//
// let name = try item.select("div a img").attr("alt")
// let urlPath = try item.select("div a img").attr("src")
// let thumb = SiteUrl + urlPath
//
// data.append(["path": path!, "thumb": thumb, "name": name])
// }
//
// if items.size() > 0 {
// paginationData = try extractPaginationData(pagePath, page: page)
// }
//
// return ["movies": data, "pagination": paginationData]
// }
//
// func getGenres(page: Int=1) throws -> ItemsList {
// var data = [Any]()
//
// let document = try fetchDocument(SiteUrl + "/movies/genre.php?showC=27", headers: getHeaders())
//
// let items = try document!.select("td.topic_content")
//
// for item in items.array() {
// let href = try item.select("div a").attr("href")
// let src = try item.select("div a img").attr("src")
//
// let path = "/movies/\(href)"
// let thumb = "\(SiteUrl)\(src)"
//
// let fileName = thumb.components(separatedBy: "/").last!
// let index1 = fileName.startIndex
//
// let name = fileName[index1 ..< fileName.find("-")!]
//
// data.append(["path": path, "thumb": thumb, "name": name])
// }
//
// return ["movies": data]
// }
//
// func getGenre(path: String, page: Int=1) throws -> ItemsList {
// var data = [Any]()
// var paginationData: ItemsList = [:]
//
// let response = httpRequest(SiteUrl + getCorrectedPath(path), headers: getHeaders())
//
// let newPath = "\(response!.response!.url!.path)?\(response!.response!.url!.query!)"
//
// let pagePath = newPath + "&page=\(page)"
//
// let document = try fetchDocument(SiteUrl + pagePath, headers: getHeaders())
//
// let items = try document!.select("td.topic_content")
//
// for item in items.array() {
// let href = try item.select("div a").attr("href")
//
// let path = "/movies/" + href
// let name = try item.select("div a img").attr("alt")
// let urlPath = try item.select("div a img").attr("src")
// let thumb = SiteUrl + urlPath
//
// data.append(["path": path, "thumb": thumb, "name": name])
// }
//
// if items.size() > 0 {
// paginationData = try extractPaginationData(pagePath, page: page)
// }
//
// return ["movies": data, "pagination": paginationData]
// }
//
// func getSerie(path: String, page: Int=1) throws -> ItemsList {
// var data = [Any]()
//
// let document = try fetchDocument(SiteUrl + path, headers: getHeaders())
//
// let items = try document!.select("div.titleline h2 a")
//
// for item in items.array() {
// let href = try item.attr("href")
//
// let path = "/forum/" + href
// let name = try item.text()
//
// data.append(["path": path, "name": name])
// }
//
// return ["movies": data]
// }
//
// func getPreviousSeasons(_ path: String) throws -> ItemsList {
// var data = [Any]()
//
// let document = try fetchDocument(SiteUrl + path, headers: getHeaders())
//
// let items = try document!.select("div.titleline h2 a")
//
// for item in items.array() {
// let href = try item.attr("href")
//
// let path = "/forum/" + href
// let name = try item.text()
//
// data.append(["path": path, "name": name])
// }
//
// return ["movies": data]
// }
//
//// func getSeasons(path: String) throws -> ItemsList {
//// let data = try self.getPreviousSeasons(path)
////
////// let currentSeason = try getSeason(path)
//////
////// let firstItemName = currentSeason[0]["name"]
////// let index1 = firstItemName.find("Season")
////// let index2 = firstItemName.find("Episode")
//////
////// let number = first_item_name[index1+6:index2].strip()
//////
////// data.append(["path": path, "name": "Season " + number])
////
//// return data
//// }
//
//// func getSeason(_ path: String) throws -> ItemsList {
//// var data = [Any]()
////
////// let document = try fetchDocument(SiteUrl + getCorrectedPath(path), headers: getHeaders())
//////
////// let items = try document!.select("div.inner h3 a")
//////
////// for item in items.array() {
////// let href = try item.attr("href")
//////
////// let path = "/forum/" + href
////// let name = try item.text()
//////
////// if name.find("Season Download") < 1 {
////// let newName = extractName(name)
//////
////// data.append(["path": path, "name": newName])
////// }
////// }
////
//// return ["movies": data]
//// }
//
// func updateUrls(data: [String: Any], url: String) -> [Any] {
// var urls = data["urls"] as! [Any]
//
// urls.append(url)
//
// return urls
// }
//
// func getMovie(_ id: String) throws -> [String: Any] {
// var data = [String: Any]()
//
// let response = httpRequest(SiteUrl + id, headers: getHeaders())
//
// let url = response!.response!.url!
//
// let document = try fetchDocument(url.absoluteString, headers: getHeaders())
//
// let name = try document!.select("title").text()
//
// data["name"] = extractName(name)
// data["thumb"] = SiteUrl + (try document!.select("img[id='nameimage']").attr("src"))
//
// data["urls"] = []
//
// let frameUrl1 = try document!.select("iframe").attr("src")
//
// if frameUrl1 != "" {
// let data1 = try fetchDocument(SiteUrl + frameUrl1, headers: getHeaders())
//
// let frameUrl2 = try data1!.select("iframe").attr("src")
//
// let data2 = try fetchDocument(SiteUrl + frameUrl2, headers: getHeaders())
//
// let url1 = try data2!.select("iframe").attr("src")
//
// data["urls"] = updateUrls(data: data, url: url1)
//
// let components = frameUrl2.components(separatedBy: ".")
//
// let frameUrl2WithoutExt = components[0...components.count-2].joined(separator: ".")
//
// if !frameUrl2WithoutExt.isEmpty {
// let secondUrlPart2 = frameUrl2WithoutExt + "2.php"
//
// do {
// let data3 = try fetchDocument(SiteUrl + secondUrlPart2, headers: getHeaders())
//
// let url2 = try data3!.select("iframe").attr("src")
//
// data["urls"] = updateUrls(data: data, url: url2)
// }
// catch {
// // suppress
// }
//
// do {
// let secondFrameUrlPart3 = frameUrl2WithoutExt + "3.php"
//
// let data4 = try fetchDocument(SiteUrl + secondFrameUrlPart3, headers: getHeaders())
//
// let url3 = try data4!.select("iframe").attr("src")
//
// if !url3.isEmpty {
// data["urls"] = updateUrls(data: data, url: url3)
// }
// }
// catch {
// // suppress
// }
// }
// }
//
//// if document.select("iframe[contains(@src,'ytid=')]/@src")) > 0 {
//// let el = SiteUrl + document!.xpath("//iframe[contains(@src,'ytid=')]/@src")[0]
////
//// //data["trailer_url"] = el.split("?",1)[0].replace("http://dayt.se/bits/pastube.php", "https://www.youtube.com/watch?v=") + el.split("=",1)[1]
//// }
//
// return data
// }
//
// func extractPaginationData(_ path: String, page: Int) throws -> ItemsList {
//// let document = try fetchDocument(SiteUrl + path, headers: getHeaders())
////
//// var pages = 1
////
//// let paginationRoot = try document?.select("div.mainpagination table tr")
////
//// if paginationRoot != nil {
//// let paginationBlock = paginationRoot!.get(0)
////
//// let items = try paginationBlock.select("td.table a")
////
//// pages = items.size()
//// }
////
//// return [
//// "page": page,
//// "pages": pages,
//// "has_previous": page > 1,
//// "has_next": page < pages
//// ]
//
// return [:]
// }
//
// func getCorrectedPath(_ path: String) -> String {
// let id = getMediaId(path)
//
// let index1 = path.startIndex
// let index21 = path.find("goto-")
//
// return path[index1 ..< index21!] + "view.php?id=\(id)"
// }
//
// func getMediaId(_ path: String) -> String {
// let index11 = path.find("/goto-")
//
// let index1 = path.index(index11!, offsetBy: 6)
//
// let idPart = String(path[index1 ..< path.endIndex])
//
// let index3 = idPart.startIndex
// let index41 = idPart.find("-")
//
// return String(idPart[index3 ..< index41!])
// }
//
// func extractName(_ name: String) -> String {
// //return name.rsplit(" Streaming", 1)[0].rsplit(" Download", 1)[0]
// return name
// }
//
// func getHeaders() -> [String: String] {
// return [
// "User-Agent": UserAgent
// ]
// }
}
| mit | e7ca95d154e36b1d645e06df666fc8cf | 28.075145 | 152 | 0.554076 | 3.290808 | false | false | false | false |
sersoft-gmbh/XMLWrangler | Sources/XMLWrangler/XMLElement+Lookup.swift | 1 | 16359 | // MARK: - Lookup
extension XMLElement {
// MARK: Single element
/// Looks up a single child element at a given path of element names.
/// - Parameter path: A collection of element names which represent the path to extract the element from.
/// - Returns: The element at the given path.
/// - Throws: `LookupError.missingChild` in case the path contains an inexistent element at some point.
public func element<Path: Collection>(at path: Path) throws -> XMLElement where Path.Element == Name {
guard !path.isEmpty else { return self }
guard let nextElement = content.findFirst(elementNamed: path[path.startIndex], recursive: false) else {
throw LookupError.missingChild(element: self, childName: path[path.startIndex])
}
return try nextElement.element(at: path.dropFirst())
}
/// Looks up a single child element at a given path of element names.
/// - Parameter path: A list of element names which represent the path to extract the element from.
/// - Returns: The element at the given path.
/// - Throws: `LookupError.missingChild` in case the path contains an inexistent element at some point.
@inlinable
public func element(at path: Name...) throws -> XMLElement {
try element(at: path)
}
// MARK: List of elements
/// Finds all element children with the given name inside the content the element on which this is called.
/// - Parameter elementName: The element name for which to look for.
/// - Returns: All elements found with the given name. Might be empty.
/// - Throws: Currently, no error is thrown. The method is annotated as `throws` for consistency and because it might throw in the future.
@inlinable
public func elements(named elementName: Name) throws -> [XMLElement] {
content.find(elementsNamed: elementName)
}
}
// MARK: - Attributes
extension XMLElement {
// MARK: Retrieval
/// Returns the value for a given attribute key if present.
/// - Parameter key: The key for which to get the attribute value.
/// - Returns: The attribute value for the given key.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key.
public func attribute(for key: Attributes.Key) throws -> Attributes.Content {
guard let attribute = attributes[key] else {
throw LookupError.missingAttribute(element: self, key: key)
}
return attribute
}
// MARK: Conversion
/// Returns the result of converting the value for a given attribute key.
/// - Parameters:
/// - key: The key for which to get the attribute value.
/// - converter: The converter to use for the conversion.
/// - Returns: The converted value.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key or any error thrown by `converter`.
/// - SeeAlso: `Element.attribute(for:)`
@inlinable
public func convertedAttribute<T>(for key: Attributes.Key, converter: (Attributes.Content) throws -> T) throws -> T {
try converter(attribute(for: key))
}
/// Returns the result of converting the value for a given attribute key.
/// - Parameters:
/// - key: The key for which to get the attribute value.
/// - converter: The converter to use for the conversion.
/// - Returns: The converted value.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key, `LookupError.cannotConvertAttribute` when `converter` returns nil or any error thrown by `converter`.
/// - SeeAlso: `XMLElement.attribute(for:)`
public func convertedAttribute<T>(for key: Attributes.Key, converter: (Attributes.Content) throws -> T?) throws -> T {
let content = try attribute(for: key)
return try _convert(content, using: converter,
failingWith: LookupError.cannotConvertAttribute(element: self, key: key, content: content, type: T.self))
}
/// Returns the result of initializing `Target` with the attribute for the given key if it exists.
/// - Parameters:
/// - convertible: The convertible type. Defaults to `Target.self`.
/// - key: The key for which to get the attribute content.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key or any error thrown by `Target.init(xmlAttributeContent:)`.
/// - Returns: An instance of the `Convertible` type initialized with the attribute content.
/// - SeeAlso: `XMLElement.attribute(for:)` and `ExpressibleByXMLAttributeContent`
@inlinable
public func convertedAttribute<Target>(for key: Attributes.Key) throws -> Target
where Target: ExpressibleByXMLAttributeContent
{
try convertedAttribute(for: key, converter: Target.init)
}
/// Returns the result of initializing `Target` with the attribute for the given key if it exists.
/// - Parameters:
/// - convertible: The convertible type. Defaults to `Target.self`.
/// - key: The key for which to get the attribute content.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key or any error thrown by `Target.init(xmlAttributeContent:)`.
/// - Returns: An instance of the `Convertible` type initialized with the attribute content.
/// - SeeAlso: `XMLElement.attribute(for:)` and `ExpressibleByXMLAttributeContent`
@inlinable
public func convertedAttribute<Target>(for key: Attributes.Key) throws -> Target
where Target: ExpressibleByXMLAttributeContent, Target: RawRepresentable, Target.RawValue: LosslessStringConvertible
{
try convertedAttribute(for: key, converter: Target.init(xmlAttributeContent:))
}
/// Returns the result of initializing `Target` with the attribute for the given key if it exists.
/// - Parameters:
/// - convertible: The convertible type. Defaults to `Target.self`.
/// - key: The key for which to get the attribute content.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key or any error thrown by `Target.init(xmlAttributeContent:)`.
/// - Returns: An instance of the `Convertible` type initialized with the attribute content.
/// - SeeAlso: `XMLElement.attribute(for:)` and `ExpressibleByXMLAttributeContent`
@inlinable
public func convertedAttribute<Target>(for key: Attributes.Key) throws -> Target
where Target: ExpressibleByXMLAttributeContent, Target: LosslessStringConvertible
{
try convertedAttribute(for: key, converter: Target.init(xmlAttributeContent:))
}
// Returns the result of initializing `Target` with the attribute for the given key if it exists.
/// - Parameters:
/// - convertible: The convertible type. Defaults to `Target.self`.
/// - key: The key for which to get the attribute content.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key or any error thrown by `Target.init(xmlAttributeContent:)`.
/// - Returns: An instance of the `Convertible` type initialized with the attribute content.
/// - SeeAlso: `XMLElement.attribute(for:)` and `ExpressibleByXMLAttributeContent`
@inlinable
public func convertedAttribute<Target>(for key: Attributes.Key) throws -> Target
where Target: ExpressibleByXMLAttributeContent, Target: RawRepresentable, Target: LosslessStringConvertible, Target.RawValue: LosslessStringConvertible
{
try convertedAttribute(for: key, converter: Target.init(xmlAttributeContent:))
}
/// Returns the result of initializing a RawRepresentable type with the value for a given attribute key
/// passed into the RawValue's LosslessStringConvertible-initializer.
/// - Parameter key: The key for which to get the attribute value.
/// - Returns: An instance of the RawRepresentable type initialized with the attribute value passed into the RawValue's LosslessStringConvertible-initializer.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key or `LookupError.cannotConvertAttribute` when the initializer of the RawRepresentable type or its RawValue returns nil.
/// - SeeAlso: `XMLElement.convertedAttribute(for:converter:)`, `RawRepresentable.init?(rawValue:)` and `LosslessStringConvertible.init?(_:)`
@inlinable
public func convertedAttribute<T: RawRepresentable>(for key: Attributes.Key) throws -> T
where T.RawValue: LosslessStringConvertible
{
try convertedAttribute(for: key, converter: { T(rawValueDescription: $0.rawValue) })
}
/// Returns the result of initializing a LosslessStringConvertible type with the value for a given attribute key.
/// - Parameter key: The key for which to get the attribute value.
/// - Returns: An instance of the LosslessStringConvertible type initialized with the attribute value.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key or `LookupError.cannotConvertAttribute` when the initializer of the LosslessStringConvertible type returns nil.
/// - SeeAlso: `XMLElement.convertedAttribute(for:converter:)` and `LosslessStringConvertible.init?(_:)`
@inlinable
public func convertedAttribute<T: LosslessStringConvertible>(for key: Attributes.Key) throws -> T {
try convertedAttribute(for: key, converter: { T($0.rawValue) })
}
/// Returns the result of initializing a RawRepresentable & LosslessStringConvertible type with the value for a given attribute key
/// passed into the RawValue's LosslessStringConvertible-initializer.
/// - Parameter key: The key for which to get the attribute value.
/// - Returns: An instance of the RawRepresentable & LosslessStringConvertible type initialized with the attribute value passed into the RawValue's LosslessStringConvertible-initializer.
/// - Throws: `LookupError.missingAttribute` in case no attribute exists for the given key or `LookupError.cannotConvertAttribute` when the initializer of the RawRepresentable type or its RawValue returns nil.
/// - SeeAlso: `XMLElement.convertedAttribute(for:converter:)`, `RawRepresentable.init?(rawValue:)` and `LosslessStringConvertible.init?(_:)`
/// - Note: This overload will prefer the RawRepresentable initializer.
@inlinable
public func convertedAttribute<T: RawRepresentable & LosslessStringConvertible>(for key: Attributes.Key) throws -> T
where T.RawValue: LosslessStringConvertible
{
try convertedAttribute(for: key, converter: { T(rawValueDescription: $0.rawValue) })
}
}
// MARK: - String Content
extension XMLElement {
// MARK: Retrieval
/// Returns the combined string content of the element.
/// - Returns: All `.string` contents joined together into one string.
/// - Throws: `LookupError.missingStringContent` if `content` contains no `.string` elements.
public func stringContent() throws -> String {
let stringContent = content.allStrings
guard !stringContent.isEmpty else { throw LookupError.missingStringContent(element: self) }
return stringContent.joined()
}
// MARK: Conversion
/// Returns the result of converting the combined string content.
/// - Parameter converter: The converter to use for the conversion.
/// - Returns: The converted content.
/// - Throws: `LookupError.missingStringContent` if `content` contains no `.string` elements or any error thrown by `converter`.
/// - SeeAlso: `XMLElement.stringContent()`
@inlinable
public func convertedStringContent<T>(converter: (String) throws -> T) throws -> T {
try converter(stringContent())
}
/// Returns the result of converting the combined string content.
/// - Parameter converter: The converter to use for the conversion.
/// - Returns: The converted content.
/// - Throws: `LookupError.missingStringContent` if `content` contains no `.string` elements, `LookupError.cannotConvertStringContent` if the `converter` returns nil or any error thrown by `converter`.
/// - SeeAlso: `XMLElement.stringContent()`
public func convertedStringContent<T>(converter: (String) throws -> T?) throws -> T {
let content = try stringContent()
return try _convert(content, using: converter,
failingWith: LookupError.cannotConvertStringContent(element: self, stringContent: content, type: T.self))
}
/// Returns the result of initializing a RawRepresentable type with the combined string content passed into the RawValue's LosslessStringConvertible-initializer.
/// - Returns: An instance of the RawRepresentable type initialized with the combined string content passed into the RawValue's LosslessStringConvertible-initializer.
/// - Throws: `LookupError.missingStringContent` if `content` contains no `.string` elements, `LookupError.cannotConvertStringContent` when the initializer of the RawRepresentable type or its RawValue returns nil.
/// - SeeAlso: `XMLElement.convertedStringContent(converter:)`, `RawRepresentable.init?(rawValue:)` and `LosslessStringConvertible.init?(_:)`
@inlinable
public func convertedStringContent<T: RawRepresentable>() throws -> T where T.RawValue: LosslessStringConvertible {
try convertedStringContent(converter: T.init)
}
/// Returns the result of initializing a LosslessStringConvertible type with the combined string content.
/// - Returns: An instance of the LosslessStringConvertible type initialized with the combined string content.
/// - Throws: `LookupError.missingStringContent` if `content` contains no `.string` elements, `LookupError.cannotConvertStringContent` when the initializer of the LosslessStringConvertible type returns nil.
/// - SeeAlso: `XMLElement.convertedStringContent(converter:)` and `LosslessStringConvertible.init?(_:)`
@inlinable
public func convertedStringContent<T: LosslessStringConvertible>() throws -> T {
try convertedStringContent(converter: T.init)
}
/// Returns the result of initializing a RawRepresentable & LosslessStringConvertible type with the combined string content passed into the RawValue's LosslessStringConvertible-initializer.
/// - Returns: An instance of the RawRepresentable & LosslessStringConvertible type initialized with the combined string content passed into the RawValue's LosslessStringConvertible-initializer.
/// - Throws: `LookupError.missingStringContent` if `content` contains no `.string` elements, `LookupError.cannotConvertStringContent` when the initializer of the RawRepresentable type or its RawValue returns nil.
/// - SeeAlso: `XMLElement.convertedStringContent(converter:)`, `RawRepresentable.init?(rawValue:)` and `LosslessStringConvertible.init?(_:)`
/// - Note: This overload will prefer the RawRepresentable initializer.
@inlinable
public func convertedStringContent<T: RawRepresentable & LosslessStringConvertible>() throws -> T
where T.RawValue: LosslessStringConvertible
{
try convertedStringContent(converter: T.init(rawValueDescription:))
}
}
// MARK: - Element Content
extension XMLElement {
/// Returns the result of converting the receiver to the given `ExpressibleByXMLElement` target.
/// - Parameter target: The target type to convert to. Defaults to `Target.self`.
/// - Throws: Any error thrown by `ExpressibleByXMLElement.init(xml:)` of `Target`.
/// - Returns: The result of calling `Target(xml:)`.
@inlinable
public func converted<Target: ExpressibleByXMLElement>(to target: Target.Type = Target.self) throws -> Target {
try target.init(xml: self)
}
}
extension Sequence where Element == XMLElement {
/// Convertes the contents of the sequence to the given target type that conforms to `ExpressibleByXMLElement`.
/// - Parameter target: The target type to convert the contents to. Defaults to `Target.self`.
/// - Throws: Any error thrown by `ExpressibleByXMLElement.init(xml:)` of `Target`.
/// - Returns: The list of converted elements.
@inlinable
public func converted<Target: ExpressibleByXMLElement>(to target: Target.Type = Target.self) throws -> Array<Target> {
try map(target.init)
}
}
| apache-2.0 | 18a5b21dbea3d2a34192e59d9d591d06 | 62.902344 | 217 | 0.721621 | 5.088336 | false | false | false | false |
telldus/telldus-live-mobile-v3 | ios/WidgetModule.swift | 1 | 12213 | //
// WidgetModule.swift
// TelldusLiveApp
//
// Created by Rimnesh Fernandez on 08/10/20.
// Copyright © 2020 Telldus Technologies AB. All rights reserved.
//
import Foundation
import Security
import Intents
import UIKit
import DeviceActionShortcut
import UIKit
import Intents
import IntentsUI
import CoreSpotlight
enum VoiceShortcutMutationStatus: String {
case cancelled = "cancelled"
case added = "added"
case updated = "updated"
case deleted = "deleted"
}
@objc(WidgetModule)
class WidgetModule: NSObject, INUIAddVoiceShortcutViewControllerDelegate, INUIEditVoiceShortcutViewControllerDelegate {
var presenterViewController: UIViewController?
var voiceShortcuts: Array<NSObject> = [] // Actually it's INVoiceShortcut, but that way we would have to break compatibility with simple NSUserActivity behaviour
var presentShortcutCallback: RCTResponseSenderBlock?
let sharedModule = SharedModule()
@objc(configureWidgetAuthData:)
func configureWidgetAuthData(authData: Dictionary<String, Any>) -> Void {
sharedModule.configureWidgetAuthData(authData: authData)
}
@discardableResult
func setSecureData(data: String) -> Bool {
return sharedModule.setSecureData(data: data)
}
// IMP: Do not update with partial data! Should have all keys set by 'configureWidgetAuthData'
@discardableResult
func updateSecureData(data: String) -> Int {
return sharedModule.updateSecureData(data: data)
}
func getSecureData() -> String? {
return sharedModule.getSecureData()
}
@objc(disableAllWidgets)
func disableAllWidgets() -> Void {
sharedModule.disableAllWidgets()
}
@objc(refreshAllWidgetsData)
func refreshAllWidgetsData() {
sharedModule.refreshAllWidgetsData()
}
@objc(refreshAllWidgets)
func refreshAllWidgets() {
sharedModule.refreshAllWidgets()
}
@objc(setUserDefault:value:)
func setUserDefault(key: NSString, value: NSString) {
sharedModule.setUserDefault(key: key, value: value);
}
@objc(getUserDefault:)
func getUserDefault(key: NSString) -> NSString {
return sharedModule.getUserDefault(key: key)
}
@objc(donate:)
func donate(jsonOptions: Dictionary<String, Any>) {
if #available(iOS 12.0, *) {
let intent = DeviceActionShortcutIntent()
let phrase = jsonOptions["phrase"] as! String
let deviceId = jsonOptions["deviceId"] as! String
let method = jsonOptions["method"] as! String
let dimValue = jsonOptions["dimValue"] as? NSNumber
let rgbValue = jsonOptions["rgbValue"] as? [String: NSNumber] ?? [:]
let thermostatValue = jsonOptions["thermostatValue"] as? [String: Any] ?? [:]
let r = rgbValue["r"]
let g = rgbValue["g"]
let b = rgbValue["b"]
let _rgbValue: RGBValue = RGBValue(
identifier: "rgbValue",
display: "rgb value",
pronunciationHint: "rgb value"
)
let mode = thermostatValue["mode"] as? String ?? ""
let temperature = thermostatValue["temperature"] as? NSNumber
let scale = thermostatValue["scale"] as? NSNumber ?? 0
let changeMode = thermostatValue["changeMode"] as? NSNumber ?? 0
let _thermostatValue: ThermostatValue = ThermostatValue(identifier: "_thermostatValue", display: "thermostat value")
if #available(iOS 13.0, *) {
_rgbValue.r = r
_rgbValue.g = g;
_rgbValue.b = b;
_thermostatValue.mode = mode;
_thermostatValue.temperature = temperature;
_thermostatValue.scale = scale;
_thermostatValue.changeMode = changeMode;
} else {
// Fallback on earlier versions
};
intent.suggestedInvocationPhrase = "phrase"
intent.phrase = phrase
intent.deviceId = deviceId
intent.method = method
intent.dimValue = dimValue
intent.rgbValue = _rgbValue
intent.thermostatValue = _thermostatValue
let interaction = INInteraction(intent: intent, response: nil)
interaction.donate { (error) in
if error != nil {
if let error = error as NSError? {
print("TEST Interaction donation failed: \(error.description)")
} else {
print("TEST Successfully donated interaction")
}
}
}
} else {
// Fallback on earlier versions
}
}
@objc(presentShortcut:callback:)
func presentShortcut(jsonOptions: Dictionary<String, Any>, callback: @escaping RCTResponseSenderBlock) {
if #available(iOS 12.0, *) {
self.presentShortcutCallback = callback
let intent = DeviceActionShortcutIntent()
let phrase = jsonOptions["phrase"] as! String
let deviceId = jsonOptions["deviceId"] as! String
let method = jsonOptions["method"] as! String
let dimValue = jsonOptions["dimValue"] as? NSNumber
let rgbValue = jsonOptions["rgbValue"] as? [String: NSNumber] ?? [:]
let thermostatValue = jsonOptions["thermostatValue"] as? [String: Any] ?? [:]
let identifier = jsonOptions["identifier"] as? String
let r = rgbValue["r"]
let g = rgbValue["g"]
let b = rgbValue["b"]
let _rgbValue: RGBValue = RGBValue(
identifier: "rgbValue",
display: "rgb value",
pronunciationHint: "rgb value"
)
let mode = thermostatValue["mode"] as? String ?? ""
let temperature = thermostatValue["temperature"] as? NSNumber
let scale = thermostatValue["scale"] as? NSNumber ?? 0
let changeMode = thermostatValue["changeMode"] as? NSNumber ?? 0
let _thermostatValue: ThermostatValue = ThermostatValue(
identifier: "thermostatValue",
display: "thermostat value",
pronunciationHint: "thermostat value"
)
if #available(iOS 13.0, *) {
_rgbValue.r = r
_rgbValue.g = g;
_rgbValue.b = b;
_thermostatValue.mode = mode;
_thermostatValue.temperature = temperature;
_thermostatValue.scale = scale;
_thermostatValue.changeMode = changeMode;
} else {
// Fallback on earlier versions
};
intent.phrase = phrase
intent.deviceId = deviceId
intent.method = method
intent.dimValue = dimValue
intent.rgbValue = _rgbValue
intent.thermostatValue = _thermostatValue
guard let shortcut = INShortcut(intent: intent) else {
return
}
var addedVoiceShortcut: INVoiceShortcut?
INVoiceShortcutCenter.shared.getAllVoiceShortcuts { (voiceShortcutsFromCenter, error) in
if let voiceShortcutsFromCenter = voiceShortcutsFromCenter {
for sc in voiceShortcutsFromCenter {
if identifier != nil, sc.identifier.uuidString == identifier {
addedVoiceShortcut = sc
}
}
}
DispatchQueue.main.async {
// The shortcut was not added yet, so present a form to add it
if (addedVoiceShortcut == nil) {
self.presenterViewController = INUIAddVoiceShortcutViewController(shortcut: shortcut)
self.presenterViewController!.modalPresentationStyle = .formSheet
(self.presenterViewController as! INUIAddVoiceShortcutViewController).delegate = self
} // The shortcut was already added, so we present a form to edit it
else {
self.presenterViewController = INUIEditVoiceShortcutViewController(voiceShortcut: addedVoiceShortcut!)
self.presenterViewController!.modalPresentationStyle = .formSheet
(self.presenterViewController as! INUIEditVoiceShortcutViewController).delegate = self
}
UIApplication.shared.keyWindow!.rootViewController!.present(self.presenterViewController!, animated: true, completion: nil)
}
}
} else {
// Fallback on earlier versions
}
}
@objc(getShortcuts:)
func getShortcuts(callback: @escaping RCTResponseSenderBlock) {
if #available(iOS 12.0, *) {
INVoiceShortcutCenter.shared.getAllVoiceShortcuts { (voiceShortcutsFromCenter, error) in
if let voiceShortcutsFromCenter = voiceShortcutsFromCenter {
var shortcuts: [[String: Any]] = []
for sc in voiceShortcutsFromCenter {
var userInfo: [String: Any] = [:]
if let intent = sc.shortcut.intent as? DeviceActionShortcutIntent {
userInfo = [
"phrase": intent.phrase,
"deviceId": intent.deviceId,
"method": intent.method,
"dimValue": intent.dimValue,
"rgbValue": intent.rgbValue,
"thermostatValue": intent.thermostatValue,
]
}
shortcuts.append([
"identifier": sc.identifier.uuidString,
"invocationPhrase": sc.invocationPhrase,
"userInfo": userInfo,
])
}
callback([["shortcuts":shortcuts]])
} else {
if let error = error as NSError? {
callback([["error":error]])
return
}
}
}
} else {
// Fallback on earlier versions
let shortcuts: [Any] = []
callback([["shortcuts":shortcuts]])
}
}
@available(iOS 12.0, *)
func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController, didFinishWith voiceShortcut: INVoiceShortcut?, error: Error?) {
// Shortcut was added
if (voiceShortcut != nil) {
voiceShortcuts.append(voiceShortcut!)
}
dismissPresenter(.added, withShortcut: voiceShortcut)
}
@available(iOS 12.0, *)
func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) {
// Adding shortcut cancelled
dismissPresenter(.cancelled, withShortcut: nil)
}
@available(iOS 12.0, *)
func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didUpdate voiceShortcut: INVoiceShortcut?, error: Error?) {
// Shortcut was updated
if (voiceShortcut != nil) {
// Update the array with the shortcut that was updated, just so we don't have to loop over the existing shortcuts again
let indexOfUpdatedShortcut = (voiceShortcuts as! Array<INVoiceShortcut>).firstIndex { (shortcut) -> Bool in
return shortcut.identifier == voiceShortcut!.identifier
}
if (indexOfUpdatedShortcut != nil) {
voiceShortcuts[indexOfUpdatedShortcut!] = voiceShortcut!
}
}
dismissPresenter(.updated, withShortcut: voiceShortcut)
}
@available(iOS 12.0, *)
func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didDeleteVoiceShortcutWithIdentifier deletedVoiceShortcutIdentifier: UUID) {
// Shortcut was deleted
// Keep a reference so we can notify JS about what the invocationPhrase was for this shortcut
var deletedShortcut: INVoiceShortcut? = nil
// Remove the deleted shortcut from the array
let indexOfDeletedShortcut = (voiceShortcuts as! Array<INVoiceShortcut>).firstIndex { (shortcut) -> Bool in
return shortcut.identifier == deletedVoiceShortcutIdentifier
}
if (indexOfDeletedShortcut != nil) {
deletedShortcut = voiceShortcuts[indexOfDeletedShortcut!] as? INVoiceShortcut
voiceShortcuts.remove(at: indexOfDeletedShortcut!)
}
dismissPresenter(.deleted, withShortcut: deletedShortcut)
}
@available(iOS 12.0, *)
func editVoiceShortcutViewControllerDidCancel(_ controller: INUIEditVoiceShortcutViewController) {
// Shortcut edit was cancelled
dismissPresenter(.cancelled, withShortcut: nil)
}
@available(iOS 12.0, *)
func dismissPresenter(_ status: VoiceShortcutMutationStatus, withShortcut voiceShortcut: INVoiceShortcut?) {
DispatchQueue.main.async {
self.presenterViewController?.dismiss(animated: true, completion: nil)
self.presenterViewController = nil
self.presentShortcutCallback?([
["status": status.rawValue, "phrase": voiceShortcut?.invocationPhrase]
])
self.presentShortcutCallback = nil
}
}
}
| gpl-3.0 | 069effad4c570c29c0bee8598703db3e | 34.707602 | 166 | 0.66058 | 5.137568 | false | false | false | false |
magicien/MMDSceneKit | Sample_swift/macOS/GameView.swift | 1 | 2078 | //
// GameView.swift
// MMDSceneKitSample_macOS
//
// Created by magicien on 12/10/15.
// Copyright (c) 2015 DarkHorse. All rights reserved.
//
import SceneKit
import MMDSceneKit_macOS
class GameView: SCNView {
override func mouseDown(with theEvent: NSEvent) {
super.mouseDown(with: theEvent)
return
let materials = mikuNode.materialArray!
for index in 0..<materials.count {
let material = materials[index]
}
return
/* Called when a mouse click occurs */
// get morpher
let geometryNode = scene!.rootNode.childNode(withName: "Geometry", recursively: true)
let morpher = geometryNode!.morpher
let childNodes = scene!.rootNode.childNodes
// check what nodes are clicked
let p = self.convert(theEvent.locationInWindow, from: nil)
let hitResults = self.hitTest(p, options: nil)
// check that we clicked on at least one object
if hitResults.count > 0 {
// retrieved the first clicked object
let result: AnyObject = hitResults[0]
// get its material
let material = result.node!.geometry!.firstMaterial!
// highlight it
SCNTransaction.begin()
//SCNTransaction.setAnimationDuration(0.5)
SCNTransaction.animationDuration = 0.5
// on completion - unhighlight
//SCNTransaction.setCompletionBlock() {
SCNTransaction.completionBlock = {
SCNTransaction.begin()
//SCNTransaction.setAnimationDuration(0.5)
SCNTransaction.animationDuration = 0.5
material.emission.contents = NSColor.black
SCNTransaction.commit()
}
material.emission.contents = NSColor.red
SCNTransaction.commit()
}
super.mouseDown(with: theEvent)
}
}
| mit | 3b42427b1ce63de4d03ed341280d110a | 29.558824 | 93 | 0.562079 | 5.571046 | false | false | false | false |
fespinoza/linked-ideas-osx | LinkedIdeas/UI/CanvasViewControllerExtensions/CanvasViewController+NSPasteboard.swift | 1 | 2980 | //
// CanvasViewController+NSPasteboard.swift
// LinkedIdeas
//
// Created by Felipe Espinoza on 23/05/2017.
// Copyright © 2017 Felipe Espinoza Dev. All rights reserved.
//
import Cocoa
import LinkedIdeas_Shared
extension CanvasViewController {
// MARK: - Pasteboard
fileprivate func writeToPasteboard(pasteboard: NSPasteboard) {
guard let elements = selectedElements() else {
return
}
pasteboard.clearContents()
pasteboard.writeObjects(elements.map { $0.attributedStringValue })
}
fileprivate func readFromPasteboard(pasteboard: NSPasteboard) {
let rawObjects = pasteboard.readObjects(
forClasses: [NSAttributedString.self], options: [:]
) as? [NSAttributedString]
guard let objects = rawObjects, objects.count != 0 else {
return
}
pasteConcepts(fromAttributedStrings: objects)
}
fileprivate func readFromPasteboardAsPlainText(pasteboard: NSPasteboard) {
let rawObjects = pasteboard.readObjects(forClasses: [NSString.self], options: [:]) as? [String]
guard let objects = rawObjects, objects.count != 0 else {
return
}
pasteConcepts(fromAttributedStrings: objects.map { NSAttributedString(string: $0) })
}
fileprivate func pasteConcepts(fromAttributedStrings attributedStrings: [NSAttributedString]) {
safeTransiton {
try stateManager.toCanvasWaiting()
}
var newConcepts = [Concept]()
for (index, string) in attributedStrings.enumerated() {
lastCopyIndex += 1
let copyReferenceIndex = index + lastCopyIndex + 1
if let concept = createConceptFromPasteboard(attributedString: string, index: copyReferenceIndex) {
newConcepts.append(concept)
}
}
guard newConcepts.count > 0 else {
return
}
if newConcepts.count > 1 {
safeTransiton {
try stateManager.toMultipleSelectedElements(elements: newConcepts)
}
} else {
safeTransiton {
try stateManager.toSelectedElement(element: newConcepts.first!)
}
}
}
fileprivate func createConceptFromPasteboard(attributedString: NSAttributedString, index: Int) -> Concept? {
let newConceptPadding: Int = 15
let newPoint = CGPoint(
x: CGFloat(200 + (newConceptPadding*index)),
y: CGFloat(200 + (newConceptPadding*index))
)
return saveConcept(text: attributedString, atPoint: newPoint)
}
// MARK: - Interface actions
@objc func cut(_ sender: Any?) {
writeToPasteboard(pasteboard: NSPasteboard.general)
if let elements = selectedElements() {
safeTransiton {
try stateManager.toCanvasWaiting(deletingElements: elements)
}
}
}
@objc func copy(_ sender: Any?) {
writeToPasteboard(pasteboard: NSPasteboard.general)
}
@objc func paste(_ sender: Any?) {
readFromPasteboard(pasteboard: NSPasteboard.general)
}
@objc func pasteAsPlainText(_ sender: Any?) {
readFromPasteboardAsPlainText(pasteboard: NSPasteboard.general)
}
}
| mit | af9946dbb04ff8f9a3ad691da32dbe6d | 27.103774 | 110 | 0.698221 | 4.597222 | false | false | false | false |
barbaramartina/swift-code-snippets | snippets/swift-ac-bloomFilter.swift | 1 | 1448 | ---
title: Swift Algorithm Club Bloom Filter
completion-scope: TopLevel
summary: Bloom filter implementation
---
public class BloomFilter<T> {
private var array: [Bool]
private var hashFunctions: [(T) -> Int]
public init(size: Int = 1024, hashFunctions: [(T) -> Int]) {
self.array = [Bool](repeating: false, count: size)
self.hashFunctions = hashFunctions
}
private func computeHashes(_ value: T) -> [Int] {
return hashFunctions.map() { hashFunc in abs(hashFunc(value) % array.count) }
}
public func insert(_ element: T) {
for hashValue in computeHashes(element) {
array[hashValue] = true
}
}
public func insert(_ values: [T]) {
for value in values {
insert(value)
}
}
public func query(_ value: T) -> Bool {
let hashValues = computeHashes(value)
// Map hashes to indices in the Bloom Filter
let results = hashValues.map() { hashValue in array[hashValue] }
// All values must be 'true' for the query to return true
// This does NOT imply that the value is in the Bloom filter,
// only that it may be. If the query returns false, however,
// you can be certain that the value was not added.
let exists = results.reduce(true, { $0 && $1 })
return exists
}
public func isEmpty() -> Bool {
// As soon as the reduction hits a 'true' value, the && condition will fail.
return array.reduce(true) { prev, next in prev && !next }
}
}
| gpl-3.0 | 045cb362de0d828cff5f1cf71d7cf95b | 27.96 | 81 | 0.649862 | 3.913514 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-security | Sample/BMSSecuritySample/BMSSecuritySample/ViewController.swift | 1 | 1329 | //
// ViewController.swift
// GoogleMCA
//
// Created by Ilan Klein on 15/02/2016.
// Copyright © 2016 ibm. All rights reserved.
//
import UIKit
import BMSCore
import BMSSecurity
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBOutlet weak var answerTextView: UILabel!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func logout(sender: AnyObject) {
MCAAuthorizationManager.sharedInstance.logout(nil)
}
@IBAction func login(sender: AnyObject) {
let callBack:BmsCompletionHandler = {(response: Response?, error: NSError?) in
var ans:String = "";
if error == nil {
ans="response:\(response?.responseText), no error"
} else {
ans="ERROR , error=\(error)"
}
dispatch_async(dispatch_get_main_queue(), {
self.answerTextView.text = ans
})
}
let request = Request(url: AppDelegate.customResourceURL, method: HttpMethod.GET)
request.sendWithCompletionHandler(callBack)
}
}
| apache-2.0 | a881c59fb900d1da139f8494c9ddefda | 27.869565 | 89 | 0.615211 | 4.882353 | false | false | false | false |
ReactKit/SwiftTask | SwiftTask/_StateMachine.swift | 1 | 8397 | //
// _StateMachine.swift
// SwiftTask
//
// Created by Yasuhiro Inami on 2015/01/21.
// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//
import Foundation
///
/// fast, naive event-handler-manager in replace of ReactKit/SwiftState (dynamic but slow),
/// introduced from SwiftTask 2.6.0
///
/// see also: https://github.com/ReactKit/SwiftTask/pull/22
///
internal class _StateMachine<Progress, Value, Error>
{
internal typealias ErrorInfo = Task<Progress, Value, Error>.ErrorInfo
internal typealias ProgressTupleHandler = Task<Progress, Value, Error>._ProgressTupleHandler
internal let weakified: Bool
internal let state: _Atomic<TaskState>
internal let progress: _Atomic<Progress?> = _Atomic(nil) // NOTE: always nil if `weakified = true`
internal let value: _Atomic<Value?> = _Atomic(nil)
internal let errorInfo: _Atomic<ErrorInfo?> = _Atomic(nil)
internal let configuration = TaskConfiguration()
/// wrapper closure for `_initClosure` to invoke only once when started `.Running`,
/// and will be set to `nil` afterward
internal var initResumeClosure: _Atomic<(() -> Void)?> = _Atomic(nil)
private lazy var _progressTupleHandlers = _Handlers<ProgressTupleHandler>()
private lazy var _completionHandlers = _Handlers<() -> Void>()
private var _lock = _RecursiveLock()
internal init(weakified: Bool, paused: Bool)
{
self.weakified = weakified
self.state = _Atomic(paused ? .Paused : .Running)
}
@discardableResult internal func addProgressTupleHandler(_ token: inout _HandlerToken?, _ progressTupleHandler: @escaping ProgressTupleHandler) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if self.state.rawValue == .Running || self.state.rawValue == .Paused {
token = self._progressTupleHandlers.append(progressTupleHandler)
return token != nil
}
else {
return false
}
}
@discardableResult internal func removeProgressTupleHandler(_ handlerToken: _HandlerToken?) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if let handlerToken = handlerToken {
let removedHandler = self._progressTupleHandlers.remove(handlerToken)
return removedHandler != nil
}
else {
return false
}
}
@discardableResult internal func addCompletionHandler(_ token: inout _HandlerToken?, _ completionHandler: @escaping () -> Void) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if self.state.rawValue == .Running || self.state.rawValue == .Paused {
token = self._completionHandlers.append(completionHandler)
return token != nil
}
else {
return false
}
}
@discardableResult internal func removeCompletionHandler(_ handlerToken: _HandlerToken?) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
if let handlerToken = handlerToken {
let removedHandler = self._completionHandlers.remove(handlerToken)
return removedHandler != nil
}
else {
return false
}
}
internal func handleProgress(_ progress: Progress)
{
self._lock.lock()
defer { self._lock.unlock() }
if self.state.rawValue == .Running {
let oldProgress = self.progress.rawValue
// NOTE: if `weakified = false`, don't store progressValue for less memory footprint
if !self.weakified {
self.progress.rawValue = progress
}
for handler in self._progressTupleHandlers {
handler((oldProgress: oldProgress, newProgress: progress))
}
}
}
internal func handleFulfill(_ value: Value)
{
self._lock.lock()
defer { self._lock.unlock() }
let newState = self.state.updateIf { $0 == .Running ? .Fulfilled : nil }
if let _ = newState {
self.value.rawValue = value
self._finish()
}
}
internal func handleRejectInfo(_ errorInfo: ErrorInfo)
{
self._lock.lock()
defer { self._lock.unlock() }
let toState = errorInfo.isCancelled ? TaskState.Cancelled : .Rejected
let newState = self.state.updateIf { $0 == .Running || $0 == .Paused ? toState : nil }
if let _ = newState {
self.errorInfo.rawValue = errorInfo
self._finish()
}
}
internal func handlePause() -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
let newState = self.state.updateIf { $0 == .Running ? .Paused : nil }
if let _ = newState {
self.configuration.pause?()
return true
}
else {
return false
}
}
internal func handleResume() -> Bool
{
self._lock.lock()
if let initResumeClosure = self.initResumeClosure.update({ _ in nil }) {
self.state.rawValue = .Running
self._lock.unlock()
//
// NOTE:
// Don't use `_lock` here so that dispatch_async'ed `handleProgress` inside `initResumeClosure()`
// will be safely called even when current thread goes into sleep.
//
initResumeClosure()
//
// Comment-Out:
// Don't call `configuration.resume()` when lazy starting.
// This prevents inapropriate starting of upstream in ReactKit.
//
//self.configuration.resume?()
return true
}
else {
let resumed = _handleResume()
self._lock.unlock()
return resumed
}
}
private func _handleResume() -> Bool
{
let newState = self.state.updateIf { $0 == .Paused ? .Running : nil }
if let _ = newState {
self.configuration.resume?()
return true
}
else {
return false
}
}
internal func handleCancel(_ error: Error? = nil) -> Bool
{
self._lock.lock()
defer { self._lock.unlock() }
let newState = self.state.updateIf { $0 == .Running || $0 == .Paused ? .Cancelled : nil }
if let _ = newState {
self.errorInfo.rawValue = ErrorInfo(error: error, isCancelled: true)
self._finish()
return true
}
else {
return false
}
}
private func _finish()
{
for handler in self._completionHandlers {
handler()
}
self._progressTupleHandlers.removeAll()
self._completionHandlers.removeAll()
self.configuration.finish()
self.initResumeClosure.rawValue = nil
self.progress.rawValue = nil
}
}
//--------------------------------------------------
// MARK: - Utility
//--------------------------------------------------
internal struct _HandlerToken
{
internal let key: Int
}
internal struct _Handlers<T>: Sequence
{
internal typealias KeyValue = (key: Int, value: T)
private var currentKey: Int = 0
private var elements = [KeyValue]()
internal mutating func append(_ value: T) -> _HandlerToken
{
self.currentKey = self.currentKey &+ 1
self.elements += [(key: self.currentKey, value: value)]
return _HandlerToken(key: self.currentKey)
}
internal mutating func remove(_ token: _HandlerToken) -> T?
{
for i in 0..<self.elements.count {
if self.elements[i].key == token.key {
return self.elements.remove(at: i).value
}
}
return nil
}
internal mutating func removeAll(keepCapacity: Bool = false)
{
self.elements.removeAll(keepingCapacity: keepCapacity)
}
internal func makeIterator() -> AnyIterator<T>
{
return AnyIterator(self.elements.map { $0.value }.makeIterator())
}
}
| mit | c33b8101d585c8a8133c43b55a93d86e | 28.769504 | 155 | 0.551757 | 5 | false | false | false | false |
haawa799/WaniKani-iOS | Pods/StrokeDrawingView/Pod/Classes/StrokeDrawingView.swift | 2 | 7736 | //
// StrokeDrawingView.swift
// StrokeDrawingView
//
// HAVE A NICE DAY!
// ₍ᐢ•ﻌ•ᐢ₎*・゚。
//
// Created by Andrew Kharchyshyn
// Copyright (c) 2015 StrokeDrawingView. 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
public protocol StrokeDrawingViewDataSource: class {
func sizeOfDrawing() -> CGSize
func numberOfStrokes() -> Int
func pathForIndex(index: Int) -> UIBezierPath
func animationDurationForStroke(index: Int) -> CFTimeInterval
func colorForStrokeAtIndex(index: Int) -> UIColor
func colorForUnderlineStrokes() -> UIColor?
}
public protocol StrokeDrawingViewDataDelegate: class {
func layersAreNowReadyForAnimation()
}
public class StrokeDrawingView: UIView {
private let defaultMiterLimit: CGFloat = 4
private var numberOfStrokes: Int { return dataSource?.numberOfStrokes() ?? 0 }
private var shouldDraw = false
private var strokeLayers = [CAShapeLayer]()
private var backgroundLayer = BackgroundLayer()
private var drawingSize = CGSizeZero
private var animations = [CABasicAnimation]()
private var timer: NSTimer?
deinit {
timer?.invalidate()
}
// MARK: - Public API
/// Custom drawing starts afte this property is set
public var dataSource: StrokeDrawingViewDataSource? {
didSet {
guard let dataSource = dataSource else {return}
drawingSize = dataSource.sizeOfDrawing()
shouldDraw = true
setNeedsDisplay()
}
}
public var delegate: StrokeDrawingViewDataDelegate?
/// Use this method to run looped animation
public func playForever(delayBeforeEach: CFTimeInterval = 0) {
guard let dataSource = dataSource else {return}
let numberOfStrokes = dataSource.numberOfStrokes()
var animationDuration: CFTimeInterval = 0
for i in 0..<numberOfStrokes {
animationDuration += dataSource.animationDurationForStroke(i)
}
playSingleAnimation()
timer = NSTimer.scheduledTimerWithTimeInterval(delayBeforeEach + animationDuration, target: self, selector: "playSingleAnimation", userInfo: nil, repeats: true)
}
/// Use this method to stop looped animation
public func stopForeverAnimation() {
timer?.invalidate()
pauseLayers()
}
public func clean() {
removeAnimationFromEachLayer()
resetLayers()
for layer in strokeLayers {
layer.removeFromSuperlayer()
}
strokeLayers = [CAShapeLayer]()
}
/// Use this method to run single animation cycle
public func playSingleAnimation() {
removeAnimationFromEachLayer()
setStrokesProgress(0)
resetLayers()
var counter = 0
var duration: CFTimeInterval = CACurrentMediaTime()
for strokeLayer in strokeLayers {
let delay = duration
let strokeAnimationDuration = dataSource?.animationDurationForStroke(counter) ?? 0
duration += strokeAnimationDuration
let anim = defaultAnimation(strokeAnimationDuration, delayTime: delay)
strokeLayer.addAnimation(anim, forKey: "strokeEndAnimation")
counter++
}
}
/// Use this method to reset strokes layers progress to 'progress'
/// Can be value from 0 t0 1
public func setStrokesProgress(progress: CGFloat) {
for strokeLayer in strokeLayers {
strokeLayer.strokeEnd = progress
}
}
}
// MARK:
extension StrokeDrawingView {
private func pauseLayers() {
for strokeLayer in strokeLayers {
strokeLayer.pause()
}
}
private func resetLayers() {
for strokeLayer in strokeLayers {
strokeLayer.reset()
}
}
private func removeAnimationFromEachLayer() {
for strokeLayer in strokeLayers {
strokeLayer.removeAllAnimations()
}
}
private func drawIfNeeded() {
if shouldDraw == true && numberOfStrokes > 0 {
layer.addSublayer(backgroundLayer)
for strokeIndex in 0..<numberOfStrokes {
let color = dataSource?.colorForStrokeAtIndex(strokeIndex) ?? UIColor.blackColor()
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = nil
shapeLayer.strokeColor = color.CGColor
shapeLayer.miterLimit = defaultMiterLimit
shapeLayer.lineCap = kCALineCapRound
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.strokeEnd = 0.0
layer.addSublayer(shapeLayer)
strokeLayers.append(shapeLayer)
}
shouldDraw = false
delegate?.layersAreNowReadyForAnimation()
}
}
private func defaultAnimation(duration: CFTimeInterval, delayTime: CFTimeInterval = 0, removeOnComletion: Bool = false) -> CABasicAnimation {
let baseAnim = CABasicAnimation(keyPath: "strokeEnd")
baseAnim.duration = duration
baseAnim.beginTime = delayTime
baseAnim.fromValue = 0
baseAnim.fillMode = kCAFillModeForwards
baseAnim.removedOnCompletion = removeOnComletion
baseAnim.toValue = 1
return baseAnim
}
public override func drawRect(rect: CGRect) {
drawIfNeeded()
}
public override func layoutSubviews() {
super.layoutSubviews()
guard let dataSource = dataSource where strokeLayers.count > 0 else {return}
let scale: CGFloat = bounds.height / drawingSize.height
var pathes = [UIBezierPath]()
for strokeIndex in 0..<numberOfStrokes {
let strokeLayer = strokeLayers[strokeIndex]
let path = dataSource.pathForIndex(strokeIndex)
let pathCopy = UIBezierPath(CGPath: path.CGPath)
pathCopy.lineWidth = path.lineWidth * scale
pathes.append(pathCopy)
pathCopy.applyTransform(CGAffineTransformMakeScale(scale, scale))
strokeLayer.lineWidth = path.lineWidth * scale
strokeLayer.path = pathCopy.CGPath
}
if let underlineColor = dataSource.colorForUnderlineStrokes() {
backgroundLayer.frame = bounds
backgroundLayer.strokeColor = underlineColor
backgroundLayer.strokes = pathes
backgroundLayer.setNeedsDisplay()
}
}
}
extension CALayer {
func pause() {
let pausedTime = convertTime(CACurrentMediaTime(), fromLayer: nil)
speed = 0.0
timeOffset = pausedTime
}
func reset() {
speed = 1.0
timeOffset = 0.0
}
func resume() {
let pausedTime = timeOffset
speed = 1.0
timeOffset = 0.0
beginTime = 0.0
let timeSincePause = convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime
beginTime = timeSincePause
}
}
public func performWithDelay(delay: Double, closure: () -> Void) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
| gpl-3.0 | 2c09b914b66c6ebdb2469e3b0fb1ad43 | 28.563218 | 164 | 0.698808 | 4.933504 | false | false | false | false |
Constructor-io/constructorio-client-swift | AutocompleteClient/FW/UI/DefaultSearchItemCell.swift | 1 | 1316 | //
// DefaultSearchItemCell.swift
// Constructor.io
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import UIKit
public class DefaultSearchItemCell: UITableViewCell, CIOAutocompleteCell {
@IBOutlet public weak var labelText: UILabel!
override public func awakeFromNib() {
super.awakeFromNib()
}
public func setup(result: CIOAutocompleteResult, searchTerm: String, highlighter: CIOHighlighter) {
if let group = result.group {
let groupString = NSMutableAttributedString()
groupString.append(highlighter.highlight(searchTerm: searchTerm, itemTitle: result.result.value))
let fontGroup = Constants.UI.Font.defaultFontNormal.withSize(11)
let groupAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: fontGroup,
NSAttributedString.Key.foregroundColor: Constants.UI.Color.defaultFontColorNormal]
groupString.append(NSAttributedString.build(string: "\nin \(group.displayName)", attributes: groupAttributes))
self.labelText.attributedText = groupString
} else {
self.labelText.attributedText = highlighter.highlight(searchTerm: searchTerm, itemTitle: result.result.value)
}
}
}
| mit | 5790c5624ae2c3b175a691f726a0ed04 | 35.527778 | 122 | 0.692776 | 4.943609 | false | false | false | false |
gregomni/swift | test/Constraints/tuple_arguments.swift | 2 | 65840 | // RUN: %target-typecheck-verify-swift -swift-version 5
// See test/Compatibility/tuple_arguments_4.swift for some
// Swift 4-specific tests.
func concrete(_ x: Int) {}
func concreteLabeled(x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
do {
concrete(3)
concrete((3))
concreteLabeled(x: 3)
concreteLabeled(x: (3))
concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}}
// expected-error@-1 {{cannot convert value of type '(x: Int)' to expected argument type 'Int'}}
concreteTwo(3, 4)
concreteTwo((3, 4)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
concreteTuple(3, 4) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
concreteTwo(d) // expected-error {{global function 'concreteTwo' expects 2 separate arguments}}
concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((a, b))
concreteTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
concreteTwo(d) // expected-error {{global function 'concreteTwo' expects 2 separate arguments}}
concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
concreteTuple((a, b))
concreteTuple(d)
}
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
do {
generic(3)
generic(3, 4) // expected-error {{extra argument in call}}
generic((3))
generic((3, 4))
genericLabeled(x: 3)
genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
genericLabeled(x: (3))
genericLabeled(x: (3, 4))
genericTwo(3, 4)
genericTwo((3, 4)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}}
genericTuple(3, 4) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}}
genericTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
generic(a)
generic(a, b) // expected-error {{extra argument in call}}
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}}
genericTwo(d) // expected-error {{global function 'genericTwo' expects 2 separate arguments}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
generic(a)
generic(a, b) // expected-error {{extra argument in call}}
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}}
genericTwo(d) // expected-error {{global function 'genericTwo' expects 2 separate arguments}}
genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}}
genericTuple((a, b))
genericTuple(d)
}
var function: (Int) -> ()
var functionTwo: (Int, Int) -> () // expected-note 5 {{'functionTwo' declared here}}
var functionTuple: ((Int, Int)) -> ()
do {
function(3)
function((3))
functionTwo(3, 4)
functionTwo((3, 4)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
functionTuple(3, 4) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
functionTwo(d) // expected-error {{var 'functionTwo' expects 2 separate arguments}}
functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((a, b))
functionTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
functionTwo(d) // expected-error {{var 'functionTwo' expects 2 separate arguments}}
functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
functionTuple((a, b))
functionTuple(d)
}
struct Concrete {}
extension Concrete {
func concrete(_ x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
}
do {
let s = Concrete()
s.concrete(3)
s.concrete((3))
s.concreteTwo(3, 4)
s.concreteTwo((3, 4)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.concreteTuple(3, 4) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.concreteTwo(d) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments}}
s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.concreteTwo(d) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments}}
s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
extension Concrete {
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
}
do {
let s = Concrete()
s.generic(3)
s.generic(3, 4) // expected-error {{extra argument in call}}
s.generic((3))
s.generic((3, 4))
s.genericLabeled(x: 3)
s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.genericLabeled(x: (3))
s.genericLabeled(x: (3, 4))
s.genericTwo(3, 4)
s.genericTwo((3, 4)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTuple(3, 4) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}}
s.genericTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.generic(a)
s.generic(a, b) // expected-error {{extra argument in call}}
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTwo(d) // expected-error {{instance method 'genericTwo' expects 2 separate arguments}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.generic(a)
s.generic(a, b) // expected-error {{extra argument in call}}
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTwo(d) // expected-error {{instance method 'genericTwo' expects 2 separate arguments}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
s.genericTuple(d)
}
extension Concrete {
mutating func mutatingConcrete(_ x: Int) {}
mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'mutatingConcreteTwo' declared here}}
mutating func mutatingConcreteTuple(_ x: (Int, Int)) {}
}
do {
var s = Concrete()
s.mutatingConcrete(3)
s.mutatingConcrete((3))
s.mutatingConcreteTwo(3, 4)
s.mutatingConcreteTwo((3, 4)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}}
s.mutatingConcreteTuple(3, 4) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}}
s.mutatingConcreteTwo(d) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments}}
s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}}
s.mutatingConcreteTwo(d) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments}}
s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
extension Concrete {
mutating func mutatingGeneric<T>(_ x: T) {}
mutating func mutatingGenericLabeled<T>(x: T) {}
mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {}
}
do {
var s = Concrete()
s.mutatingGeneric(3)
s.mutatingGeneric(3, 4) // expected-error {{extra argument in call}}
s.mutatingGeneric((3))
s.mutatingGeneric((3, 4))
s.mutatingGenericLabeled(x: 3)
s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.mutatingGenericLabeled(x: (3))
s.mutatingGenericLabeled(x: (3, 4))
s.mutatingGenericTwo(3, 4)
s.mutatingGenericTwo((3, 4)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.mutatingGenericTuple(3, 4) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b) // expected-error {{extra argument in call}}
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.mutatingGenericTwo(d) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b) // expected-error {{extra argument in call}}
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.mutatingGenericTwo(d) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
extension Concrete {
var function: (Int) -> () { return concrete }
var functionTwo: (Int, Int) -> () { return concreteTwo } // expected-note 5 {{'functionTwo' declared here}}
var functionTuple: ((Int, Int)) -> () { return concreteTuple }
}
do {
let s = Concrete()
s.function(3)
s.function((3))
s.functionTwo(3, 4)
s.functionTwo((3, 4)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.functionTuple(3, 4) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.functionTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.functionTwo(d) // expected-error {{property 'functionTwo' expects 2 separate arguments}}
s.functionTuple(a, b) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.functionTuple((a, b))
s.functionTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}}
s.functionTwo(d) // expected-error {{property 'functionTwo' expects 2 separate arguments}}
s.functionTuple(a, b) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}}
s.functionTuple((a, b))
s.functionTuple(d)
}
struct InitTwo {
init(_ x: Int, _ y: Int) {} // expected-note 5 {{'init(_:_:)' declared here}}
}
struct InitTuple {
init(_ x: (Int, Int)) {}
}
struct InitLabeledTuple {
init(x: (Int, Int)) {}
}
do {
_ = InitTwo(3, 4)
_ = InitTwo((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
_ = InitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((3, 4))
_ = InitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = InitLabeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
_ = InitTwo(c) // expected-error {{initializer expects 2 separate arguments}}
_ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}}
_ = InitTwo(c) // expected-error {{initializer expects 2 separate arguments}}
_ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
struct SubscriptTwo {
subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}}
}
struct SubscriptTuple {
subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } }
}
struct SubscriptLabeledTuple {
subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } }
}
do {
let s1 = SubscriptTwo()
_ = s1[3, 4]
_ = s1[(3, 4)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
let s2 = SubscriptTuple()
_ = s2[3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(3, 4)]
}
do {
let a = 3
let b = 4
let d = (a, b)
let s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
_ = s1[d] // expected-error {{subscript expects 2 separate arguments}}
let s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(a, b)]
_ = s2[d]
let s3 = SubscriptLabeledTuple()
_ = s3[x: 3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}}
_ = s3[x: (3, 4)]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
_ = s1[d] // expected-error {{subscript expects 2 separate arguments}}
var s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}}
_ = s2[(a, b)]
_ = s2[d]
}
enum Enum {
case two(Int, Int) // expected-note 6 {{'two' declared here}}
case tuple((Int, Int))
case labeledTuple(x: (Int, Int))
}
do {
_ = Enum.two(3, 4)
_ = Enum.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
_ = Enum.two(3 > 4 ? 3 : 4) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((3, 4))
_ = Enum.labeledTuple(x: 3, 4) // expected-error {{enum case 'labeledTuple' expects a single parameter of type '(Int, Int)'}}
_ = Enum.labeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
_ = Enum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
_ = Enum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
struct Generic<T> {}
extension Generic {
func generic(_ x: T) {}
func genericLabeled(x: T) {}
func genericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'genericTwo' declared here}}
func genericTuple(_ x: (T, T)) {}
}
do {
let s = Generic<Double>()
s.generic(3.0)
s.generic((3.0))
s.genericLabeled(x: 3.0)
s.genericLabeled(x: (3.0))
s.genericTwo(3.0, 4.0)
s.genericTwo((3.0, 4.0)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{25-26=}}
s.genericTuple(3.0, 4.0) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{26-26=)}}
s.genericTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(3.0, 4.0) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{24-24=)}}
sTwo.generic((3.0, 4.0))
sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'genericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.genericLabeled(x: (3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}}
sTwo.generic((a, b))
sTwo.generic(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}}
s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}}
s.genericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}}
sTwo.generic((a, b))
sTwo.generic(d)
}
extension Generic {
mutating func mutatingGeneric(_ x: T) {}
mutating func mutatingGenericLabeled(x: T) {}
mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple(_ x: (T, T)) {}
}
do {
var s = Generic<Double>()
s.mutatingGeneric(3.0)
s.mutatingGeneric((3.0))
s.mutatingGenericLabeled(x: 3.0)
s.mutatingGenericLabeled(x: (3.0))
s.mutatingGenericTwo(3.0, 4.0)
s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {24-25=}} {{33-34=}}
s.mutatingGenericTuple(3.0, 4.0) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}}
s.mutatingGenericTuple((3.0, 4.0))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}}
sTwo.mutatingGeneric((3.0, 4.0))
sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'mutatingGenericLabeled' expects a single parameter of type '(Double, Double)'}}
sTwo.mutatingGenericLabeled(x: (3.0, 4.0))
}
do {
var s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {24-25=}} {{29-30=}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
extension Generic {
var genericFunction: (T) -> () { return generic }
var genericFunctionTwo: (T, T) -> () { return genericTwo } // expected-note 3 {{'genericFunctionTwo' declared here}}
var genericFunctionTuple: ((T, T)) -> () { return genericTuple }
}
do {
let s = Generic<Double>()
s.genericFunction(3.0)
s.genericFunction((3.0))
s.genericFunctionTwo(3.0, 4.0)
s.genericFunctionTwo((3.0, 4.0)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{33-34=}}
s.genericFunctionTuple(3.0, 4.0) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}}
s.genericFunctionTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(3.0, 4.0) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}}
sTwo.genericFunction((3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.genericFunctionTuple(a, b) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.genericFunctionTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.genericFunction((a, b))
sTwo.genericFunction(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}}
s.genericFunctionTuple(a, b) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}}
s.genericFunctionTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}}
sTwo.genericFunction((a, b))
sTwo.genericFunction(d)
}
struct GenericInit<T> {
init(_ x: T) {}
}
struct GenericInitLabeled<T> {
init(x: T) {}
}
struct GenericInitTwo<T> {
init(_ x: T, _ y: T) {} // expected-note 10 {{'init(_:_:)' declared here}}
}
struct GenericInitTuple<T> {
init(_ x: (T, T)) {}
}
struct GenericInitLabeledTuple<T> {
init(x: (T, T)) {}
}
do {
_ = GenericInit(3, 4) // expected-error {{extra argument in call}}
_ = GenericInit((3, 4))
_ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled(x: (3, 4))
_ = GenericInitTwo(3, 4)
_ = GenericInitTwo((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}}
_ = GenericInitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((3, 4))
_ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}}
_ = GenericInitLabeledTuple(x: (3, 4))
}
do {
_ = GenericInit<(Int, Int)>(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInit<(Int, Int)>((3, 4))
_ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInitLabeled<(Int, Int)>(x: (3, 4))
_ = GenericInitTwo<Int>(3, 4)
_ = GenericInitTwo<Int>((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}}
_ = GenericInitTuple<Int>(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((3, 4))
_ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInitLabeledTuple<Int>(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}}
_ = GenericInitTwo(c) // expected-error {{initializer expects 2 separate arguments}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit<(Int, Int)>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}}
_ = GenericInitTwo<Int>(c) // expected-error {{initializer expects 2 separate arguments}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}}
_ = GenericInitTwo(c) // expected-error {{initializer expects 2 separate arguments}}
_ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit<(Int, Int)>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}}
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}}
_ = GenericInitTwo<Int>(c) // expected-error {{initializer expects 2 separate arguments}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
struct GenericSubscript<T> {
subscript(_ x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptLabeled<T> {
subscript(x x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTwo<T> {
subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}}
}
struct GenericSubscriptLabeledTuple<T> {
subscript(x x: (T, T)) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTuple<T> {
subscript(_ x: (T, T)) -> Int { get { return 0 } set { } }
}
do {
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{18-18=)}}
_ = s1[(3.0, 4.0)]
let s1a = GenericSubscriptLabeled<(Double, Double)>()
_ = s1a [x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{14-14=(}} {{23-23=)}}
_ = s1a [x: (3.0, 4.0)]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[3.0, 4.0]
_ = s2[(3.0, 4.0)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{19-20=}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{18-18=)}}
_ = s3[(3.0, 4.0)]
let s3a = GenericSubscriptLabeledTuple<Double>()
_ = s3a[x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{13-13=(}} {{22-22=)}}
_ = s3a[x: (3.0, 4.0)]
}
do {
let a = 3.0
let b = 4.0
let d = (a, b)
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}}
_ = s1[(a, b)]
_ = s1[d]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
_ = s2[d] // expected-error {{subscript expects 2 separate arguments}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}}
_ = s3[(a, b)]
_ = s3[d]
}
do {
// TODO: Restore regressed diagnostics rdar://problem/31724211
var a = 3.0 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4.0 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}}
_ = s1[(a, b)]
_ = s1[d]
var s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}}
_ = s2[d] // expected-error {{subscript expects 2 separate arguments}}
var s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}}
_ = s3[(a, b)]
_ = s3[d]
}
enum GenericEnum<T> {
case one(T)
case labeled(x: T)
case two(T, T) // expected-note 10 {{'two' declared here}}
case tuple((T, T))
}
do {
_ = GenericEnum.one(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.one((3, 4))
_ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled(x: (3, 4))
_ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum.two(3, 4)
_ = GenericEnum.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}}
_ = GenericEnum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((3, 4))
}
do {
_ = GenericEnum<(Int, Int)>.one(3, 4) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((3, 4))
_ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled(x: (3, 4))
_ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}}
_ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum<Int>.two(3, 4)
_ = GenericEnum<Int>.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}}
_ = GenericEnum<Int>.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum.one(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}}
_ = GenericEnum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}}
_ = GenericEnum<Int>.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericEnum.one(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}}
_ = GenericEnum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}}
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}}
_ = GenericEnum<Int>.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
protocol Protocol {
associatedtype Element
}
extension Protocol {
func requirement(_ x: Element) {}
func requirementLabeled(x: Element) {}
func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 3 {{'requirementTwo' declared here}}
func requirementTuple(_ x: (Element, Element)) {}
}
struct GenericConforms<T> : Protocol {
typealias Element = T
}
do {
let s = GenericConforms<Double>()
s.requirement(3.0)
s.requirement((3.0))
s.requirementLabeled(x: 3.0)
s.requirementLabeled(x: (3.0))
s.requirementTwo(3.0, 4.0)
s.requirementTwo((3.0, 4.0)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{29-30=}}
s.requirementTuple(3.0, 4.0) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{30-30=)}}
s.requirementTuple((3.0, 4.0))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(3.0, 4.0) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{28-28=)}}
sTwo.requirement((3.0, 4.0))
sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{instance method 'requirementLabeled' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{29-29=(}} {{38-38=)}}
sTwo.requirementLabeled(x: (3.0, 4.0))
}
do {
let s = GenericConforms<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{25-26=}}
s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{26-26=)}}
s.requirementTuple((a, b))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{24-24=)}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
do {
var s = GenericConforms<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{25-26=}}
s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{26-26=)}}
s.requirementTuple((a, b))
var sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{24-24=)}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
extension Protocol {
func takesClosure(_ fn: (Element) -> ()) {}
func takesClosureTwo(_ fn: (Element, Element) -> ()) {}
func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {}
}
do {
let s = GenericConforms<Double>()
s.takesClosure({ _ = $0 })
s.takesClosure({ x in })
s.takesClosure({ (x: Double) in })
s.takesClosureTwo({ _ = $0 }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ x in }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ (x: (Double, Double)) in }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}}
s.takesClosureTwo({ _ = $0; _ = $1 })
s.takesClosureTwo({ (x, y) in })
s.takesClosureTwo({ (x: Double, y:Double) in })
s.takesClosureTuple({ _ = $0 })
s.takesClosureTuple({ x in })
s.takesClosureTuple({ (x: (Double, Double)) in })
s.takesClosureTuple({ _ = $0; _ = $1 })
s.takesClosureTuple({ (x, y) in })
s.takesClosureTuple({ (x: Double, y:Double) in })
let sTwo = GenericConforms<(Double, Double)>()
sTwo.takesClosure({ _ = $0 })
sTwo.takesClosure({ x in })
sTwo.takesClosure({ (x: (Double, Double)) in })
sTwo.takesClosure({ _ = $0; _ = $1 })
sTwo.takesClosure({ (x, y) in })
sTwo.takesClosure({ (x: Double, y: Double) in })
}
do {
let _: ((Int, Int)) -> () = { _ = $0 }
let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) }
let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) }
let _: ((Int, Int)) -> () = { _ = ($0, $1) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}}
let _: ((Int, Int)) -> () = { t, u in _ = (t, u) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{41-41=let (t, u) = arg; }}
let _: ((Int, Int)) -> () = { x, y in }
// expected-error@-1 {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{40-40= let (x, y) = arg; }}
let _: (Int, Int) -> () = { _ = $0 } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { _ = ($0.0, $0.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { t in _ = (t.0, t.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
let _: (Int, Int) -> () = { _ = ($0, $1) }
let _: (Int, Int) -> () = { t, u in _ = (t, u) }
}
// rdar://problem/28952837 - argument labels ignored when calling function
// with single 'Any' parameter
func takesAny(_: Any) {}
enum HasAnyCase {
case any(_: Any)
}
do {
let fn: (Any) -> () = { _ in }
fn(123)
fn(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
takesAny(123)
takesAny(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
_ = HasAnyCase.any(123)
_ = HasAnyCase.any(data: 123) // expected-error {{extraneous argument label 'data:' in call}}
}
// rdar://problem/29739905 - protocol extension methods on Array had
// ParenType sugar stripped off the element type
func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()],
f2: [(Bool, Bool) -> ()],
c: Bool) {
let p = (c, c)
f1.forEach { block in
block(p)
block((c, c))
block(c, c) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}} {{11-11=(}} {{15-15=)}}
}
f2.forEach { block in
// expected-note@-1 {{'block' declared here}}
block(p) // expected-error {{parameter 'block' expects 2 separate arguments}}
}
f2.forEach { block in
// expected-note@-1 {{'block' declared here}}
block((c, c)) // expected-error {{parameter 'block' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{11-12=}} {{16-17=}}
block(c, c)
}
f2.forEach { block in
block(c, c)
}
f2.forEach { (block: ((Bool, Bool)) -> ()) in
// expected-error@-1 {{cannot convert value of type '(((Bool, Bool)) -> ()) -> Void' to expected argument type '(@escaping (Bool, Bool) -> ()) throws -> Void'}}
block(p)
block((c, c))
block(c, c) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}}
}
f2.forEach { (block: (Bool, Bool) -> ()) in
// expected-note@-1 {{'block' declared here}}
block(p) // expected-error {{parameter 'block' expects 2 separate arguments}}
}
f2.forEach { (block: (Bool, Bool) -> ()) in
// expected-note@-1 {{'block' declared here}}
block((c, c)) // expected-error {{parameter 'block' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{11-12=}} {{16-17=}}
block(c, c)
}
f2.forEach { (block: (Bool, Bool) -> ()) in
block(c, c)
}
}
// expected-error@+1 {{cannot create a single-element tuple with an element label}}
func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) {
// TODO: Error could be improved.
// expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}}
completion((didAdjust: true))
}
// SR-4378
final public class MutableProperty<Value> {
public init(_ initialValue: Value) {}
}
enum DataSourcePage<T> {
case notLoaded
}
let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: .notLoaded,
totalCount: 0
))
let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: DataSourcePage.notLoaded,
totalCount: 0
))
let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
data: DataSourcePage<Int>.notLoaded,
totalCount: 0
))
// SR-4745
let sr4745 = [1, 2]
let _ = sr4745.enumerated().map { (count, element) in "\(count): \(element)" }
// SR-4738
let sr4738 = (1, (2, 3))
[sr4738].map { (x, (y, z)) -> Int in x + y + z } // expected-note 2 {{'x' declared here}}
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{20-26=arg1}} {{38-38=let (y, z) = arg1; }}
// expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{20-20=_: }}
// expected-error@-3 {{cannot find 'y' in scope; did you mean 'x'?}}
// expected-error@-4 {{cannot find 'z' in scope; did you mean 'x'?}}
// rdar://problem/31892961
let r31892961_1 = [1: 1, 2: 2]
r31892961_1.forEach { (k, v) in print(k + v) }
let r31892961_2 = [1, 2, 3]
let _: [Int] = r31892961_2.enumerated().map { ((index, val)) in
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{48-60=arg0}} {{3-3=\n let (index, val) = arg0\n }}
// expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{48-48=_: }}
val + 1
// expected-error@-1 {{cannot find 'val' in scope}}
}
let r31892961_3 = (x: 1, y: 42)
_ = [r31892961_3].map { (x: Int, y: Int) in x + y }
_ = [r31892961_3].map { (x, y: Int) in x + y }
let r31892961_4 = (1, 2)
_ = [r31892961_4].map { x, y in x + y }
let r31892961_5 = (x: 1, (y: 2, (w: 3, z: 4)))
[r31892961_5].map { (x: Int, (y: Int, (w: Int, z: Int))) in x + y } // expected-note {{'x' declared here}}
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-56=arg1}} {{61-61=let (y, (w, z)) = arg1; }}
// expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{30-30=_: }}
// expected-error@-3{{cannot find 'y' in scope; did you mean 'x'?}}
let r31892961_6 = (x: 1, (y: 2, z: 4))
[r31892961_6].map { (x: Int, (y: Int, z: Int)) in x + y } // expected-note {{'x' declared here}}
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-46=arg1}} {{51-51=let (y, z) = arg1; }}
// expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{30-30=_: }}
// expected-error@-3{{cannot find 'y' in scope; did you mean 'x'?}}
// rdar://problem/32214649 -- these regressed in Swift 4 mode
// with SE-0110 because of a problem in associated type inference
func r32214649_1<X,Y>(_ a: [X], _ f: (X)->Y) -> [Y] {
return a.map(f)
}
func r32214649_2<X>(_ a: [X], _ f: (X) -> Bool) -> [X] {
return a.filter(f)
}
func r32214649_3<X>(_ a: [X]) -> [X] {
return a.filter { _ in return true }
}
// rdar://problem/32301091 - [SE-0110] causes errors when passing a closure with a single underscore to a block accepting multiple parameters
func rdar32301091_1(_ :((Int, Int) -> ())!) {}
rdar32301091_1 { _ in }
// expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }}
func rdar32301091_2(_ :(Int, Int) -> ()) {}
rdar32301091_2 { _ in }
// expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }}
rdar32301091_2 { x in }
// expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,<#arg#> }}
func rdar32875953() {
let myDictionary = ["hi":1]
myDictionary.forEach {
print("\($0) -> \($1)")
}
myDictionary.forEach { key, value in
print("\(key) -> \(value)")
}
myDictionary.forEach { (key, value) in
print("\(key) -> \(value)")
}
let array1 = [1]
let array2 = [2]
_ = zip(array1, array2).map(+)
}
struct SR_5199 {}
extension Sequence where Iterator.Element == (key: String, value: String?) {
func f() -> [SR_5199] {
return self.map { (key, value) in
SR_5199() // Ok
}
}
}
func rdar33043106(_ records: [(Int)], _ other: [((Int))]) -> [Int] {
let x: [Int] = records.map { _ in
let i = 1
return i
}
let y: [Int] = other.map { _ in
let i = 1
return i
}
return x + y
}
func itsFalse(_: Int) -> Bool? {
return false
}
func rdar33159366(s: AnySequence<Int>) {
_ = s.compactMap(itsFalse)
let a = Array(s)
_ = a.compactMap(itsFalse)
}
func sr5429<T>(t: T) {
_ = AnySequence([t]).first(where: { (t: T) in true })
}
extension Concrete {
typealias T = (Int, Int)
typealias F = (T) -> ()
func opt1(_ fn: (((Int, Int)) -> ())?) {}
func opt2(_ fn: (((Int, Int)) -> ())??) {}
func opt3(_ fn: (((Int, Int)) -> ())???) {}
func optAliasT(_ fn: ((T) -> ())?) {}
func optAliasF(_ fn: F?) {}
}
extension Generic {
typealias F = (T) -> ()
func opt1(_ fn: (((Int, Int)) -> ())?) {}
func opt2(_ fn: (((Int, Int)) -> ())??) {}
func opt3(_ fn: (((Int, Int)) -> ())???) {}
func optAliasT(_ fn: ((T) -> ())?) {}
func optAliasF(_ fn: F?) {}
}
func rdar33239714() {
Concrete().opt1 { x, y in }
Concrete().opt1 { (x, y) in }
Concrete().opt2 { x, y in }
Concrete().opt2 { (x, y) in }
Concrete().opt3 { x, y in }
Concrete().opt3 { (x, y) in }
Concrete().optAliasT { x, y in }
Concrete().optAliasT { (x, y) in }
Concrete().optAliasF { x, y in }
Concrete().optAliasF { (x, y) in }
Generic<(Int, Int)>().opt1 { x, y in }
Generic<(Int, Int)>().opt1 { (x, y) in }
Generic<(Int, Int)>().opt2 { x, y in }
Generic<(Int, Int)>().opt2 { (x, y) in }
Generic<(Int, Int)>().opt3 { x, y in }
Generic<(Int, Int)>().opt3 { (x, y) in }
Generic<(Int, Int)>().optAliasT { x, y in }
Generic<(Int, Int)>().optAliasT { (x, y) in }
Generic<(Int, Int)>().optAliasF { x, y in }
Generic<(Int, Int)>().optAliasF { (x, y) in }
}
// rdar://problem/35198459 - source-compat-suite failure: Moya (toType->hasUnresolvedType() && "Should have handled this above"
do {
func foo(_: (() -> Void)?) {}
func bar() -> ((()) -> Void)? { return nil }
foo(bar()) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}}
}
// https://bugs.swift.org/browse/SR-6509
public extension Optional {
func apply<Result>(_ transform: ((Wrapped) -> Result)?) -> Result? {
return self.flatMap { value in
transform.map { $0(value) }
}
}
func apply<Value, Result>(_ value: Value?) -> Result?
where Wrapped == (Value) -> Result {
return value.apply(self)
}
}
// https://bugs.swift.org/browse/SR-6837
// FIXME: Can't overlaod local functions so these must be top-level
func takePairOverload(_ pair: (Int, Int?)) {}
func takePairOverload(_: () -> ()) {}
do {
func takeFn(fn: (_ i: Int, _ j: Int?) -> ()) {}
func takePair(_ pair: (Int, Int?)) {}
takeFn(fn: takePair) // expected-error {{cannot convert value of type '((Int, Int?)) -> ()' to expected argument type '(Int, Int?) -> ()'}}
takeFn(fn: takePairOverload) // expected-error {{cannot convert value of type '((Int, Int?)) -> ()' to expected argument type '(Int, Int?) -> ()'}}
takeFn(fn: { (pair: (Int, Int?)) in } ) // Disallow for -swift-version 4 and later
// expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}}
takeFn { (pair: (Int, Int?)) in } // Disallow for -swift-version 4 and later
// expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// https://bugs.swift.org/browse/SR-6796
do {
func f(a: (() -> Void)? = nil) {}
func log<T>() -> ((T) -> Void)? { return nil }
f(a: log() as ((()) -> Void)?) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}}
func logNoOptional<T>() -> (T) -> Void { }
f(a: logNoOptional() as ((()) -> Void)) // expected-error {{cannot convert value of type '(()) -> Void' to expected argument type '() -> Void'}}
func g() {}
g(()) // expected-error {{argument passed to call that takes no arguments}}
func h(_: ()) {} // expected-note {{'h' declared here}}
h() // expected-error {{missing argument for parameter #1 in call}}
}
// https://bugs.swift.org/browse/SR-7191
class Mappable<T> {
init(_: T) { }
func map<U>(_ body: (T) -> U) -> U { fatalError() }
}
let x = Mappable(())
// expected-note@-1 4{{'x' declared here}}
x.map { (_: Void) in return () }
x.map { (_: ()) in () }
// https://bugs.swift.org/browse/SR-9470
do {
func f(_: Int...) {}
let _ = [(1, 2, 3)].map(f) // expected-error {{no exact matches in call to instance method 'map'}}
// expected-note@-1 {{found candidate with type '(((Int, Int, Int)) throws -> _) throws -> Array<_>'}}
}
// rdar://problem/48443263 - cannot convert value of type '() -> Void' to expected argument type '(_) -> Void'
protocol P_48443263 {
associatedtype V
}
func rdar48443263() {
func foo<T : P_48443263>(_: T, _: (T.V) -> Void) {}
struct S1 : P_48443263 {
typealias V = Void
}
struct S2: P_48443263 {
typealias V = Int
}
func bar(_ s1: S1, _ s2: S2, _ fn: () -> Void) {
foo(s1, fn) // Ok because s.V is Void
foo(s2, fn) // expected-error {{cannot convert value of type '() -> Void' to expected argument type '(S2.V) -> Void' (aka '(Int) -> ()')}}
}
}
func autoclosureSplat() {
func takeFn<T>(_: (T) -> ()) {}
takeFn { (fn: @autoclosure () -> Int) in }
// This type checks because we find a solution T:= @escaping () -> Int and
// wrap the closure in a function conversion.
takeFn { (fn: @autoclosure () -> Int, x: Int) in }
// expected-error@-1 {{contextual closure type '(() -> Int) -> ()' expects 1 argument, but 2 were used in closure body}}
// expected-error@-2 {{converting non-escaping value to 'T' may allow it to escape}}
takeFn { (fn: @autoclosure @escaping () -> Int) in }
// FIXME: It looks like matchFunctionTypes() does not check @autoclosure at all.
// Perhaps this is intentional, but we should document it eventually. In the
// interim, this test serves as "documentation"; if it fails, please investigate why
// instead of changing the test.
takeFn { (fn: @autoclosure @escaping () -> Int, x: Int) in }
// expected-error@-1 {{contextual closure type '(@escaping () -> Int) -> ()' expects 1 argument, but 2 were used in closure body}}
}
func noescapeSplat() {
func takesFn<T>(_ fn: (T) -> ()) -> T {}
func takesEscaping(_: @escaping () -> Int) {}
do {
let t = takesFn { (fn: () -> Int) in }
takesEscaping(t)
// This type checks because we find a solution T:= (@escaping () -> Int).
}
do {
let t = takesFn { (fn: () -> Int, x: Int) in }
// expected-error@-1 {{converting non-escaping value to 'T' may allow it to escape}}
takesEscaping(t.0)
}
}
func variadicSplat() {
func takesFnWithVarg(fn: (Int, Int...) -> Void) {}
takesFnWithVarg { x in // expected-error {{contextual closure type '(Int, Int...) -> Void' expects 2 arguments, but 1 was used in closure body}}
_ = x.1.count
}
takesFnWithVarg { x, y in
_ = y.count
}
}
| apache-2.0 | 5d7e654cdc1ee9c8d5d11694894f0357 | 35.679666 | 253 | 0.633809 | 3.414052 | false | false | false | false |
BareFeetWare/BFWControls | BFWControls/Modules/Transition/Controller/SegueHandlerType.swift | 1 | 3044 | //
// SegueHandlerType.swift
//
// Created by Tom Brodhurst-Hill on 7/12/16.
// Copyright © 2016 BareFeetWare.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
/*
Inspired by:
https://www.bignerdranch.com/blog/using-swift-enumerations-makes-segues-safer/
https://developer.apple.com/library/content/samplecode/Lister/Listings/Lister_SegueHandlerTypeType_swift.html
https://www.natashatherobot.com/protocol-oriented-segue-identifiers-swift/
but changed to allow (ie not crash) blank segue identifiers with no code handling.
Example usage:
class RootViewController: UITableViewController, SegueHandlerType {
enum SegueIdentifier: String {
case account, products, recentProducts, contacts, login
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
guard let segueIdentifier = segueIdentifier(forIdentifier: identifier)
else { return true }
let should: Bool
switch segueIdentifier {
case .account:
should = isLoggedIn
if !should {
performSegue(.login, sender: sender)
}
default:
should = true
}
return should
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let segueIdentifier = segueIdentifier(forIdentifier: segue.identifier)
else { return }
switch segueIdentifier {
case .account:
if let accountViewController = segue.destination as? AccountViewController {
accountViewController.account = account
}
case .products, .recentProducts:
if let productsViewController = segue.destination as? ProductsViewController {
productsViewController.products = ??
}
case .contacts:
if let contactsViewController = segue.destination as? ContactsViewController {
contactsViewController.contacts = [String]()
}
case .login:
break
}
}
}
*/
import UIKit
public protocol SegueHandlerType {
associatedtype SegueIdentifier: RawRepresentable
}
public extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String {
func performSegue(_ segueIdentifier: SegueIdentifier, sender: Any?) {
performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender)
}
/// To perform the segue after already queued UI actions. For instance, use in an unwind segue to perform a forward segue after viewDidAppear has finished.
func performOnMainQueueSegue(_ segueIdentifier: SegueIdentifier, sender: Any?) {
DispatchQueue.main.async { [weak self] in
self?.performSegue(segueIdentifier, sender: sender)
}
}
func segueIdentifier(forIdentifier identifier: String?) -> SegueIdentifier? {
return identifier.flatMap { SegueIdentifier(rawValue: $0) }
}
}
| mit | 98b79df635addaf9cd3585f7f4bd0d87 | 32.811111 | 159 | 0.665462 | 5.329247 | false | false | false | false |
BareFeetWare/BFWControls | BFWControls/Modules/NibReplaceable/View/NibReplaceable.swift | 1 | 5487 | //
// NibReplaceable.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 4/5/18.
// Copyright © 2018 BareFeetWare. All rights reserved.
//
/*
// Implement in conforming class:
// For runtime:
open override func awakeAfter(using coder: NSCoder) -> Any? {
guard let nibView = replacedByNibView()
else { return self }
nibView.removePlaceholders()
return nibView
}
// For Interface Builder, IBDesignable:
@objc public extension NibView {
@objc func replacedByNibViewForInit() -> Self? {
return replacedByNibView()
}
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
return [(NibView *)self replacedByNibViewForInit];
}
*/
// Storage required since a protocol extension can not store variables.
fileprivate class Storage {
/// Prevents recursive call by loadNibNamed to itself. Safe as a static var since it is always called on the main thread, ie synchronously.
static var loadingStack: [AnyClass] = []
static var sizeForKeyDictionary = [String: CGSize]()
}
public protocol NibReplaceable where Self: UIView {
/// Override to give different nib for each cell style
var nibName: String? { get }
/// Labels and buttons which should remove enclosing [] from text at runtime, if not replaced with another value.
var placeholderViews: [UIView] { get }
}
public extension NibReplaceable {
// MARK: - Protocol variable defaults that can be overridden
/// Override to give different nib for each cell style or for a particular instance
var nibName: String? {
return nil
}
var placeholderViews: [UIView] {
return []
}
// MARK: - Static variables
static var isLoadingFromNib: Bool {
get {
return Storage.loadingStack.last == self
}
set {
// TODO: Move stack logic to a type, eg UniqueStack.
if newValue {
guard !Storage.loadingStack.contains(where: { $0 == self })
else {
fatalError("loadingStack tried to append \(self) but laodingStack already contains \(self)")
}
Storage.loadingStack.append(self)
} else {
guard Storage.loadingStack.last == self
else {
fatalError("loadingStack tried to remove \(self) but last item is \(Storage.loadingStack.last.map { String(describing: $0) } ?? "nil" )")
}
Storage.loadingStack.removeLast()
}
}
}
static var bundle: Bundle? {
return Bundle(for: self)
}
static var classNameComponents: [String] {
let fullClassName = NSStringFromClass(self) // Note: String(describing: self) does not include the moduleName prefix.
return fullClassName.components(separatedBy: ".")
}
static var moduleName: String? {
let components = classNameComponents
return components.count > 1
? components.first!
: nil
}
static var nibName: String {
// Remove the <ProjectName>. prefix that Swift adds:
return classNameComponents.last!
}
static var sizeFromNib: CGSize? {
let size: CGSize?
let key = NSStringFromClass(self)
if let reuseSize = Storage.sizeForKeyDictionary[key] {
size = reuseSize
} else {
size = nibView()?.frame.size
Storage.sizeForKeyDictionary[key] = size
}
return size
}
// MARK: - Static functions
static func nibView(fromNibNamed nibName: String? = nil, in bundle: Bundle? = nil) -> Self? {
guard !isLoadingFromNib
else { return nil }
isLoadingFromNib = true
defer {
isLoadingFromNib = false
}
let bundle = bundle ?? self.bundle!
let nibName = nibName ?? self.nibName
guard let nibViews = bundle.loadNibNamed(nibName, owner: nil, options: nil),
let nibView = nibViews.first(where: { type(of: $0) == self } ) as? Self
else {
fatalError("\(#function) Could not find an instance of class \(self) in \(nibName) xib")
}
return nibView
}
// MARK: - Instance functions
func replacedByNibView(fromNibNamed nibName: String? = nil, in bundle: Bundle? = nil) -> Self? {
let nibView = type(of: self).nibView(fromNibNamed: nibName, in: bundle)
nibView?.copyProperties(from: self)
nibView?.copyConstraints(from: self)
return nibView
}
func isPlaceholderString(_ string: String?) -> Bool {
return string != nil && string!.isPlaceholder
}
/// Replace placeholders (eg [Text]) with blank text.
internal func removePlaceholders() {
for view in placeholderViews {
if let label = view as? UILabel,
let text = label.text,
text.isPlaceholder
{
label.text = nil
} else if let button = view as? UIButton {
if button.title(for: .normal)?.isPlaceholder ?? false {
button.setTitle(nil, for: .normal)
}
}
}
}
}
private extension String {
var isPlaceholder: Bool {
return hasPrefix("[") && hasSuffix("]")
}
}
| mit | e737b43fd7a388ddd056b2af57f10c28 | 29.142857 | 161 | 0.586584 | 4.83348 | false | false | false | false |
mozilla/focus | Blockzilla/OpenUtils.swift | 4 | 5255 | /* 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 Telemetry
import OnePasswordExtension
class OpenUtils: NSObject {
private let app = UIApplication.shared
private let selectedURL: URL
private let browserFillIdentifier = "org.appextension.fill-browser-action"
private let webViewController: WebViewController
init(url: URL, webViewController: WebViewController) {
self.selectedURL = url
self.webViewController = webViewController
}
func buildShareViewController() -> UIActivityViewController {
var activityItems: [Any] = [selectedURL]
let printInfo = UIPrintInfo(dictionary: nil)
printInfo.jobName = selectedURL.absoluteString
printInfo.outputType = .general
activityItems.append(printInfo)
let renderer = UIPrintPageRenderer()
renderer.addPrintFormatter(webViewController.printFormatter, startingAtPageAt: 0)
activityItems.append(renderer)
if let title = webViewController.pageTitle {
activityItems.append(TitleActivityItemProvider(title: title))
}
let shareController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
// This needs to be ready by the time the share menu has been displayed and
// activityViewController(activityViewController:, activityType:) is called,
// which is after the user taps the button. So a million cycles away.
findLoginExtensionItem()
shareController.popoverPresentationController?.permittedArrowDirections = .up
shareController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in
if !completed {
return
}
// Bug 1392418 - When copying a url using the share extension there are 2 urls in the pasteboard.
// Make sure the pasteboard only has one url.
if let url = UIPasteboard.general.urls?.first {
UIPasteboard.general.urls = [url]
}
if self.isPasswordManagerActivityType(activityType.map { $0.rawValue }) {
Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.show, object: TelemetryEventObject.autofill)
if let logins = returnedItems {
self.fillPasswords(returnedItems: logins as [AnyObject])
Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.click, object: TelemetryEventObject.autofill)
}
}
}
return shareController
}
}
extension OpenUtils: UIActivityItemSource {
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return selectedURL
}
// IMPORTANT: This method needs Swift compiler optimization DISABLED to prevent a nasty
// crash from happening in release builds. It seems as though the check for `nil` may
// get removed by the optimizer which leads to a crash when that happens.
@_semantics("optimize.sil.never") func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
// activityType actually is nil sometimes (in the simulator at least)
if activityType != nil && isPasswordManagerActivityType(activityType?.rawValue) {
return webViewController.onePasswordExtensionItem
} else {
return selectedURL
}
}
func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivity.ActivityType?) -> String {
if let type = activityType, isPasswordManagerActivityType(type.rawValue) {
return browserFillIdentifier
}
return activityType == nil ? browserFillIdentifier : kUTTypeURL as String
}
}
private extension OpenUtils {
func isPasswordManagerActivityType(_ activityType: String?) -> Bool {
// A 'password' substring covers the most cases, such as pwsafe and 1Password.
// com.agilebits.onepassword-ios.extension
// com.app77.ios.pwsafe2.find-login-action-password-actionExtension
// If your extension's bundle identifier does not contain "password", simply submit a pull request by adding your bundle identifier.
guard let activityType = activityType else { return false }
return (activityType.range(of: "password") != nil)
|| (activityType == "com.lastpass.ilastpass.LastPassExt")
|| (activityType == "in.sinew.Walletx.WalletxExt")
|| (activityType == "com.8bit.bitwarden.find-login-action-extension")
}
func findLoginExtensionItem() {
// Add 1Password to share sheet
webViewController.createPasswordManagerExtensionItem()
}
func fillPasswords(returnedItems: [AnyObject]) {
webViewController.fillPasswords(returnedItems: returnedItems)
}
}
| mpl-2.0 | c0ac6c80c15a25de47355f889b370ede | 45.096491 | 187 | 0.701047 | 5.572641 | false | false | false | false |
gottesmm/swift | test/SILGen/objc_generic_class.swift | 2 | 1900 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
// Although we don't ever expose initializers and methods of generic classes
// to ObjC yet, a generic subclass of an ObjC class must still use ObjC
// deallocation.
// CHECK-NOT: sil hidden @_T0So7GenericCfd
// CHECK-NOT: sil hidden @_T0So8NSObjectCfd
class Generic<T>: NSObject {
var x: Int = 10
// CHECK-LABEL: sil hidden @_T018objc_generic_class7GenericCfD : $@convention(method) <T> (@owned Generic<T>) -> () {
// CHECK: bb0({{%.*}} : $Generic<T>):
// CHECK-LABEL: sil hidden [thunk] @_T018objc_generic_class7GenericCfDTo : $@convention(objc_method) <T> (Generic<T>) -> () {
// CHECK: bb0([[SELF:%.*]] : $Generic<T>):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[NATIVE:%.*]] = function_ref @_T018objc_generic_class7GenericCfD
// CHECK: apply [[NATIVE]]<T>([[SELF_COPY]])
deinit {
// Don't blow up when 'self' is referenced inside an @objc deinit method
// of a generic class. <rdar://problem/16325525>
self.x = 0
}
}
// CHECK-NOT: sil hidden @_T018objc_generic_class7GenericCfd
// CHECK-NOT: sil hidden @_T0So8NSObjectCfd
// CHECK-LABEL: sil hidden @_T018objc_generic_class11SubGeneric1CfD : $@convention(method) <U, V> (@owned SubGeneric1<U, V>) -> () {
// CHECK: bb0([[SELF:%.*]] : $SubGeneric1<U, V>):
// CHECK: [[SUPER_DEALLOC:%.*]] = super_method [[SELF]] : $SubGeneric1<U, V>, #Generic.deinit!deallocator.foreign : <T> (Generic<T>) -> () -> () , $@convention(objc_method) <τ_0_0> (Generic<τ_0_0>) -> ()
// CHECK: [[SUPER:%.*]] = upcast [[SELF:%.*]] : $SubGeneric1<U, V> to $Generic<Int>
// CHECK: apply [[SUPER_DEALLOC]]<Int>([[SUPER]])
class SubGeneric1<U, V>: Generic<Int> {
}
| apache-2.0 | 65c72f3356e67ab0554725982eaaa182 | 45.292683 | 211 | 0.621707 | 3.25 | false | false | false | false |
gongzhang/swift-event-dispatch | EventDispatch.playground/Contents.swift | 1 | 1339 | import UIKit
// some useful custom operators (optional)
infix operator <- { associativity none precedence 100 }
infix operator += { associativity right precedence 90 }
infix operator -= { associativity right precedence 90 }
infix operator +-= { associativity right precedence 90 }
// PUBLISHER SIDE:
// An example datatype - Book
struct Book {
// properties:
var title: String {
// trigger the event when title changes
didSet { onTitleChange <- (oldValue, title) }
}
var price: Double {
didSet {
// trigger the event when price changes
onPriceChange <- (oldValue, price)
// trigger the event when price is going down
if price < oldValue {
onSale <- ()
}
}
}
// published events:
let onTitleChange = EventDispatch<String>()
let onPriceChange = EventDispatch<Double>()
let onSale = EventDispatch<Void>()
}
// SUBSCRIBER SIDE:
// Usage of events
var book1 = Book(title: "Pride and Prejudice", price: 30.0)
// we want to be notified when the book is on sale...
book1.onSale += {
print("the book is on sale")
}
book1.price = 35.0
book1.price = 40.0
book1.price = 35.0 // on sale
book1.price = 40.0
book1.price = 35.0 // on sale
book1.price = 30.0 // on sale
| mit | 6d0d4c773587062d7d44c13d570e0b68 | 22.910714 | 59 | 0.615385 | 3.973294 | false | false | false | false |
SwiftKit/Torch | Source/Predicate/Operators/OptionalPropertyOperators.swift | 1 | 3051 | //
// OptionalPropertyOperators.swift
// Torch
//
// Created by Tadeáš Kříž on 24/07/16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Foundation
// MARK: - NSObjectConvertible
public extension Property where T: PropertyOptionalType, T.Wrapped: NSObjectConvertible {
public func equalTo(value: T) -> SingleValuePredicate<PARENT> {
return SingleValuePredicate(keyPath: torchName, operatorString: "==", value: value.value?.toNSObject() ?? NSNull())
}
public func notEqualTo(value: T) -> SingleValuePredicate<PARENT> {
return SingleValuePredicate(keyPath: torchName, operatorString: "!=", value: value.value?.toNSObject() ?? NSNull())
}
}
public func == <P, T: NSObjectConvertible>(lhs: Property<P, T?>, rhs: T?) -> SingleValuePredicate<P> {
return lhs.equalTo(rhs)
}
public func != <P, T: NSObjectConvertible>(lhs: Property<P, T?>, rhs: T?) -> SingleValuePredicate<P> {
return lhs.notEqualTo(rhs)
}
// MARK: NSNumberConvertible
public extension Property where T: PropertyOptionalType, T.Wrapped: NSNumberConvertible {
public func lessThan(value: T) -> SingleValuePredicate<PARENT> {
return SingleValuePredicate(keyPath: torchName, operatorString: "<", value: value.value?.toNSNumber() ?? NSNull())
}
public func lessThanOrEqualTo(value: T) -> SingleValuePredicate<PARENT> {
return SingleValuePredicate(keyPath: torchName, operatorString: "<=", value: value.value?.toNSNumber() ?? NSNull())
}
public func greaterThanOrEqualTo(value: T) -> SingleValuePredicate<PARENT> {
return SingleValuePredicate(keyPath: torchName, operatorString: ">=", value: value.value?.toNSNumber() ?? NSNull())
}
public func greaterThan(value: T) -> SingleValuePredicate<PARENT> {
return SingleValuePredicate(keyPath: torchName, operatorString: ">", value: value.value?.toNSNumber() ?? NSNull())
}
}
public func < <P, T: NSNumberConvertible>(lhs: Property<P, T?>, rhs: T?) -> SingleValuePredicate<P> {
return lhs.lessThan(rhs)
}
public func <= <P, T: NSNumberConvertible>(lhs: Property<P, T?>, rhs: T?) -> SingleValuePredicate<P> {
return lhs.lessThanOrEqualTo(rhs)
}
public func >= <P, T: NSNumberConvertible>(lhs: Property<P, T?>, rhs: T?) -> SingleValuePredicate<P> {
return lhs.greaterThanOrEqualTo(rhs)
}
public func > <P, T: NSNumberConvertible>(lhs: Property<P, T?>, rhs: T?) -> SingleValuePredicate<P> {
return lhs.greaterThan(rhs)
}
// MARK: - TorchEntity
public extension Property where T: PropertyOptionalType, T.Wrapped: TorchEntity {
subscript(predicate: SingleValuePredicate<T.Wrapped>) -> SingleValuePredicate<PARENT> {
return matches(predicate)
}
public func matches(predicate: SingleValuePredicate<T.Wrapped>) -> SingleValuePredicate<PARENT> {
return SingleValuePredicate(keyPath: joinKeyPaths(torchName, predicate.keyPath),
operatorString: predicate.operatorString,
value: predicate.value)
}
}
| mit | 4b579337933618679d2911f8f5f8ebb1 | 38.038462 | 123 | 0.690969 | 4.419448 | false | false | false | false |
KaushalElsewhere/AllHandsOn | IGListDemo/IGListDemo/FeedItem.swift | 1 | 833 | //
// FeedItem.swift
// IGListDemo
//
// Created by Kaushal Elsewhere on 17/03/2017.
// Copyright © 2017 Kaushal Elsewhere. All rights reserved.
//
import Foundation
import ObjectMapper
import IGListKit
final class FeedItem: Mappable {
var id: String?
var title: String?
required init?(_ map: Map) {
}
// Mappable
func mapping(map: Map) {
id <- map["id"]
title <- map["title"]
}
}
extension FeedItem: IGListDiffable {
@objc func diffIdentifier() -> NSObjectProtocol {
return id as! NSObjectProtocol
}
@objc func isEqualToDiffableObject(object: IGListDiffable?) -> Bool {
guard self !== object else { return true }
guard let object = object as? FeedItem else { return false }
return id == object.id
}
} | mit | 33cbbb16ea4b97dfad9c9d8057b60551 | 20.921053 | 73 | 0.609375 | 4.310881 | false | false | false | false |
cruisediary/GitHub | GitHub/Scenes/ListIssues/ListIssuesConfigurator.swift | 1 | 1093 | //
// ListIssuesPresenter.swift
// GitHub
//
// Created by CruzDiary on 27/01/2017.
// Copyright © 2017 cruz. All rights reserved.
//
import UIKit
extension ListIssuesPresenter: ListIssuesViewControllerOutput, ListIssuesRouterDataSource, ListIssuesRouterDataDestination {
}
extension ListIssuesViewController: ListIssuesPresenterOutput {
}
final class ListIssuesConfigurator {
// MARK: Object lifecycle
class var sharedInstance: ListIssuesConfigurator {
struct Static {
static let instance: ListIssuesConfigurator = ListIssuesConfigurator()
}
return Static.instance
}
private init() {}
// MARK: Configuration
func configure(_ viewController: ListIssuesViewController) {
let presenter = ListIssuesPresenter()
presenter.output = viewController
let router = ListIssuesRouter(viewController: viewController, dataSource: presenter, dataDestination: presenter)
viewController.output = presenter
viewController.router = router
}
}
| mit | 181ef3d2063f69f748d5211c188d6692 | 25 | 124 | 0.690476 | 5.571429 | false | true | false | false |
Kijjakarn/Crease-Pattern-Analyzer | CreasePatternAnalyzer/Controllers/PointViewController.swift | 1 | 12418 | //
// PointViewController.swift
// CreasePatternAnalyzer
//
// Created by Kijjakarn Praditukrit on 11/19/16.
// Copyright © 2016-2017 Kijjakarn Praditukrit. All rights reserved.
//
import Cocoa
let numberFormat = "%.5f"
@objc
protocol PointViewControllerDelegate: class {
func emptyInstructions()
func updateDiagram()
}
class PointViewController: NSViewController, NSTableViewDelegate {
@objc dynamic weak var delegate: PointViewControllerDelegate!
var x: Double = 0 {
willSet {
xString = String(format: numberFormat, newValue)
}
}
var y: Double = 0 {
willSet {
yString = String(format: numberFormat, newValue)
}
}
// Variables for enabling/disabling the findPoint button
@objc dynamic var isXValid = false
@objc dynamic var isYValid = false
@objc dynamic var foundPoints = [PointReference]()
@objc dynamic var xString = ""
@objc dynamic var yString = ""
var xInput: NSTextField!
var yInput: NSTextField!
var errorMessage: NSTextField!
var arrayController: NSArrayController!
override func loadView() {
view = NSView()
}
@objc func updateX(_ sender: NSTextField) {
let parsedX = Parser.parsedString(from: sender.stringValue)
if parsedX.success {
validate(x: parsedX.value)
delegate.updateDiagram()
}
else {
isXValid = false
xString = ""
errorMessage.stringValue = parsedX.string
}
}
@objc func updateY(_ sender: NSTextField) {
let parsedY = Parser.parsedString(from: sender.stringValue)
if parsedY.success {
validate(y: parsedY.value)
delegate.updateDiagram()
}
else {
isYValid = false
yString = ""
errorMessage.stringValue = parsedY.string
}
}
func validate(x: Double) {
if main.paper.encloses(x: x) {
self.x = x
isXValid = true
errorMessage.stringValue = ""
}
else {
isXValid = false
xString = ""
errorMessage.stringValue = "The x-coordinate is out of bounds"
}
}
func validate(y: Double) {
if main.paper.encloses(y: y) {
self.y = y
isYValid = true
errorMessage.stringValue = ""
}
else {
isYValid = false
yString = ""
errorMessage.stringValue = "The y-coordinate is out of bounds"
}
}
@objc func findPoint() {
foundPoints = matchedPoints(for: PointVector(x, y))
}
override func viewDidLoad() {
super.viewDidLoad()
setUpView()
}
func setUpView() {
let xText = NSTextField()
let xColon = NSTextField()
xInput = NSTextField()
let xEquals = NSTextField()
let xOutput = NSTextField()
setUp(textField: xText)
setUp(textField: xColon)
setUp(textField: xEquals)
xText.stringValue = "x"
xColon.stringValue = ":"
xInput.placeholderString = "x-coordinate"
xInput.action = #selector(PointViewController.updateX)
xInput.target = self
xOutput.alignment = .right
xOutput.bind(
NSBindingName(rawValue: "value"),
to: self,
withKeyPath: "xString",
options: nil
)
let xStack = NSStackView(
views: [xText, xColon, xInput, xEquals, xOutput]
)
xStack.orientation = .horizontal
xStack.translatesAutoresizingMaskIntoConstraints = false
xInput.translatesAutoresizingMaskIntoConstraints = false
xInput.widthAnchor.constraint(equalToConstant: 100).isActive = true
let yText = NSTextField()
let yColon = NSTextField()
yInput = NSTextField()
let yEquals = NSTextField()
let yOutput = NSTextField()
setUp(textField: yText)
setUp(textField: yColon)
setUp(textField: yEquals)
yText.stringValue = "y"
yColon.stringValue = ":"
yInput.placeholderString = "y-coordinate"
yInput.action = #selector(PointViewController.updateY)
yInput.target = self
yOutput.alignment = .right
yOutput.bind(
NSBindingName(rawValue: "value"),
to: self,
withKeyPath: "yString",
options: nil
)
let yStack = NSStackView(
views: [yText, yColon, yInput, yEquals, yOutput]
)
yStack.orientation = .horizontal
yStack.translatesAutoresizingMaskIntoConstraints = false
yInput.translatesAutoresizingMaskIntoConstraints = false
yInput.widthAnchor.constraint(equalToConstant: 100).isActive = true
errorMessage = NSTextField()
setUp(textField: errorMessage)
let findPointButton = NSButton(
title: "Find Point",
target: self,
action: #selector(PointViewController.findPoint)
)
findPointButton.bind(
NSBindingName(rawValue: "enabled"),
to: self,
withKeyPath: "isXValid",
options: nil
)
findPointButton.bind(
NSBindingName(rawValue: "enabled2"),
to: self,
withKeyPath: "isYValid",
options: nil
)
findPointButton.bind(
NSBindingName(rawValue: "enabled3"),
to: self,
withKeyPath: "delegate.hasFinishedInitialization",
options: nil
)
let foundPointsText = NSTextField()
foundPointsText.stringValue = "Found Points"
setUp(textField: foundPointsText)
let foundPointsScrollView = NSScrollView()
let foundPointsTableView = NSTableView()
foundPointsTableView.delegate = self
arrayController = NSArrayController()
let pointsColumn = NSTableColumn(
identifier: NSUserInterfaceItemIdentifier(rawValue: "Point")
)
let ranksColumn = NSTableColumn(
identifier: NSUserInterfaceItemIdentifier(rawValue: "Rank")
)
let errorsColumn = NSTableColumn(
identifier: NSUserInterfaceItemIdentifier(rawValue: "Error")
)
pointsColumn.title = "Point"
ranksColumn.title = "Rank"
errorsColumn.title = "Error"
ranksColumn.width = 50
pointsColumn.headerCell.alignment = .center
ranksColumn.headerCell.alignment = .center
errorsColumn.headerCell.alignment = .center
pointsColumn.bind(
NSBindingName(rawValue: "value"),
to: arrayController,
withKeyPath: "arrangedObjects.pointString",
options: nil
)
ranksColumn.sortDescriptorPrototype = NSSortDescriptor(
key: "rank",
ascending: true,
selector: #selector(NSNumber.compare(_:))
)
errorsColumn.sortDescriptorPrototype = NSSortDescriptor(
key: "distanceError",
ascending: false,
selector: #selector(NSNumber.compare(_:))
)
ranksColumn.bind(
NSBindingName(rawValue: "value"),
to: arrayController,
withKeyPath: "arrangedObjects.rank",
options: nil
)
errorsColumn.bind(
NSBindingName(rawValue: "value"),
to: arrayController,
withKeyPath: "arrangedObjects.distanceError",
options: nil
)
foundPointsTableView.addTableColumn(pointsColumn)
foundPointsTableView.addTableColumn(ranksColumn)
foundPointsTableView.addTableColumn(errorsColumn)
foundPointsTableView.bind(
NSBindingName(rawValue: "content"),
to: arrayController,
withKeyPath: "arrangedObjects",
options: nil
)
foundPointsTableView.bind(
NSBindingName(rawValue: "selectionIndexes"),
to: arrayController,
withKeyPath: "selectionIndexes",
options: nil
)
foundPointsTableView.bind(
NSBindingName(rawValue: "sortDescriptors"),
to: arrayController,
withKeyPath: "sortDescriptors",
options: nil
)
arrayController.bind(
NSBindingName(rawValue: "contentArray"),
to: self,
withKeyPath: "foundPoints",
options: nil
)
arrayController.bind(
NSBindingName(rawValue: "sortDescriptors"),
to: NSUserDefaultsController.shared,
withKeyPath: "values.sortDescriptors",
options: [
.valueTransformerName:
NSValueTransformerName.unarchiveFromDataTransformerName
]
)
arrayController.addObserver(
self,
forKeyPath: #keyPath(NSArrayController.selectionIndex),
context: nil
)
foundPointsScrollView.documentView = foundPointsTableView
let stackView = NSStackView(
views: [
xStack,
yStack,
errorMessage,
findPointButton,
foundPointsText,
foundPointsScrollView,
]
)
stackView.orientation = .vertical
stackView.alignment = .left
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.leftAnchor
.constraint(equalTo: view.leftAnchor, constant: 20),
stackView.rightAnchor
.constraint(equalTo: view.rightAnchor, constant: -20),
stackView.topAnchor
.constraint(equalTo: view.topAnchor, constant: 20),
])
findPointButton.translatesAutoresizingMaskIntoConstraints = false
findPointButton.rightAnchor
.constraint(equalTo: stackView.rightAnchor)
.isActive = true
findPointButton.setContentHuggingPriority(
NSLayoutConstraint.Priority(rawValue: 261),
for: .horizontal
)
foundPointsScrollView.translatesAutoresizingMaskIntoConstraints = false
foundPointsScrollView.heightAnchor
.constraint(equalToConstant: 200)
.isActive = true
}
func setUp(textField: NSTextField) {
textField.font = NSFont.systemFont(ofSize: 13)
textField.isSelectable = false
textField.drawsBackground = false
textField.isBordered = false
}
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
if keyPath == "selectionIndex" {
clearInstructions()
let index = arrayController.selectionIndex
let solutions = arrayController.arrangedObjects as! [PointReference]
if 0 <= index && index < solutions.count {
_ = makeInstructions(for: solutions[index])
// The point alrady exists on the paper
// (it is one of the corners)
if main.diagrams.count == 0 {
main.diagrams.append(Diagram())
main.instructions.append("")
}
else {
coalesceInstructions()
}
NotificationCenter.default.post(
name: NSNotification.Name("FindPoint"),
object: self
)
}
else {
delegate.emptyInstructions()
}
}
}
// MARK: NSTableViewDelegate
func tableView(_ tableView: NSTableView,
willDisplayCell cell: Any,
for tableColumn: NSTableColumn?,
row: Int) {
if tableColumn?.identifier == NSUserInterfaceItemIdentifier("Rank") {
if let cell = cell as? NSCell {
cell.alignment = .center
}
}
}
}
| gpl-3.0 | db7cea2eb3269f576d7d50789eebc05f | 31.590551 | 80 | 0.568817 | 5.662107 | false | false | false | false |
dndydon/DSSFMovies | DSSFMovies/AppDelegate.swift | 1 | 5999 | //
// AppDelegate.swift
// DSSFMovies
//
// Created by Don Sleeter on 7/23/16.
// Copyright © 2016 Don Sleeter. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let controller = masterNavigationController.topViewController as! MasterViewController
controller.managedObjectContext = self.persistentContainer.viewContext
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "DSSFMovies")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | fca18ccbfb60389c6b158cb9d704476b | 52.553571 | 285 | 0.708069 | 6.158111 | false | false | false | false |
chengxianghe/MissGe | MissGe/Pods/ESTabBarController-swift/Sources/ESTabBarController.swift | 1 | 6172 | //
// ESTabBarController.swift
//
// Created by Vincent Li on 2017/2/8.
// Copyright (c) 2013-2018 ESTabBarController (https://github.com/eggswift/ESTabBarController)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/// 是否需要自定义点击事件回调类型
public typealias ESTabBarControllerShouldHijackHandler = ((_ tabBarController: UITabBarController, _ viewController: UIViewController, _ index: Int) -> (Bool))
/// 自定义点击事件回调类型
public typealias ESTabBarControllerDidHijackHandler = ((_ tabBarController: UITabBarController, _ viewController: UIViewController, _ index: Int) -> (Void))
open class ESTabBarController: UITabBarController, ESTabBarDelegate {
/// 打印异常
public static func printError(_ description: String) {
#if DEBUG
print("ERROR: ESTabBarController catch an error '\(description)' \n")
#endif
}
/// 当前tabBarController是否存在"More"tab
public static func isShowingMore(_ tabBarController: UITabBarController?) -> Bool {
return tabBarController?.moreNavigationController.parent != nil
}
/// Ignore next selection or not.
fileprivate var ignoreNextSelection = false
/// Should hijack select action or not.
open var shouldHijackHandler: ESTabBarControllerShouldHijackHandler?
/// Hijack select action.
open var didHijackHandler: ESTabBarControllerDidHijackHandler?
/// Observer tabBarController's selectedViewController. change its selection when it will-set.
open override var selectedViewController: UIViewController? {
willSet {
guard let newValue = newValue else {
// if newValue == nil ...
return
}
guard !ignoreNextSelection else {
ignoreNextSelection = false
return
}
guard let tabBar = self.tabBar as? ESTabBar, let items = tabBar.items, let index = viewControllers?.index(of: newValue) else {
return
}
let value = (ESTabBarController.isShowingMore(self) && index > items.count - 1) ? items.count - 1 : index
tabBar.select(itemAtIndex: value, animated: false)
}
}
/// Observer tabBarController's selectedIndex. change its selection when it will-set.
open override var selectedIndex: Int {
willSet {
guard !ignoreNextSelection else {
ignoreNextSelection = false
return
}
guard let tabBar = self.tabBar as? ESTabBar, let items = tabBar.items else {
return
}
let value = (ESTabBarController.isShowingMore(self) && newValue > items.count - 1) ? items.count - 1 : newValue
tabBar.select(itemAtIndex: value, animated: false)
}
}
/// Customize set tabBar use KVC.
open override func viewDidLoad() {
super.viewDidLoad()
let tabBar = { () -> ESTabBar in
let tabBar = ESTabBar()
tabBar.delegate = self
tabBar.customDelegate = self
tabBar.tabBarController = self
return tabBar
}()
self.setValue(tabBar, forKey: "tabBar")
}
// MARK: - UITabBar delegate
open override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
guard let idx = tabBar.items?.index(of: item) else {
return;
}
if idx == tabBar.items!.count - 1, ESTabBarController.isShowingMore(self) {
ignoreNextSelection = true
selectedViewController = moreNavigationController
return;
}
if let vc = viewControllers?[idx] {
ignoreNextSelection = true
selectedIndex = idx
delegate?.tabBarController?(self, didSelect: vc)
}
}
open override func tabBar(_ tabBar: UITabBar, willBeginCustomizing items: [UITabBarItem]) {
if let tabBar = tabBar as? ESTabBar {
tabBar.updateLayout()
}
}
open override func tabBar(_ tabBar: UITabBar, didEndCustomizing items: [UITabBarItem], changed: Bool) {
if let tabBar = tabBar as? ESTabBar {
tabBar.updateLayout()
}
}
// MARK: - ESTabBar delegate
internal func tabBar(_ tabBar: UITabBar, shouldSelect item: UITabBarItem) -> Bool {
if let idx = tabBar.items?.index(of: item), let vc = viewControllers?[idx] {
return delegate?.tabBarController?(self, shouldSelect: vc) ?? true
}
return true
}
internal func tabBar(_ tabBar: UITabBar, shouldHijack item: UITabBarItem) -> Bool {
if let idx = tabBar.items?.index(of: item), let vc = viewControllers?[idx] {
return shouldHijackHandler?(self, vc, idx) ?? false
}
return false
}
internal func tabBar(_ tabBar: UITabBar, didHijack item: UITabBarItem) {
if let idx = tabBar.items?.index(of: item), let vc = viewControllers?[idx] {
didHijackHandler?(self, vc, idx)
}
}
}
| mit | 92423ba99f9d4fcc16970b8221d0da4a | 39.131579 | 159 | 0.642623 | 5.058043 | false | false | false | false |
iOS-mamu/SS | P/Library/Eureka/Source/Rows/SliderRow.swift | 1 | 5322 | // SliderRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// The cell of the SliderRow
open class SliderCell: Cell<Float>, CellType {
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open var titleLabel: UILabel! {
textLabel?.translatesAutoresizingMaskIntoConstraints = false
textLabel?.setContentHuggingPriority(500, for: .horizontal)
return textLabel
}
open var valueLabel: UILabel! {
detailTextLabel?.translatesAutoresizingMaskIntoConstraints = false
detailTextLabel?.setContentHuggingPriority(500, for: .horizontal)
return detailTextLabel
}
lazy open var slider: UISlider = {
let result = UISlider()
result.translatesAutoresizingMaskIntoConstraints = false
result.setContentHuggingPriority(500, for: .horizontal)
return result
}()
open var formatter: NumberFormatter?
open override func setup() {
super.setup()
selectionStyle = .none
slider.minimumValue = sliderRow.minimumValue
slider.maximumValue = sliderRow.maximumValue
slider.addTarget(self, action: #selector(SliderCell.valueChanged), for: .valueChanged)
if shouldShowTitle() {
contentView.addSubview(titleLabel)
contentView.addSubview(valueLabel!)
}
contentView.addSubview(slider)
let views = ["titleLabel" : titleLabel, "valueLabel" : valueLabel, "slider" : slider] as [String : Any]
let metrics = ["hPadding" : 16.0, "vPadding" : 12.0, "spacing" : 12.0]
if shouldShowTitle() {
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-hPadding-[titleLabel]-[valueLabel]-hPadding-|", options: NSLayoutFormatOptions.alignAllLastBaseline, metrics: metrics, views: views))
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPadding-[titleLabel]-spacing-[slider]-vPadding-|", options: NSLayoutFormatOptions.alignAllLeft, metrics: metrics, views: views))
} else {
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPadding-[slider]-vPadding-|", options: NSLayoutFormatOptions.alignAllLeft, metrics: metrics, views: views))
}
contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-hPadding-[slider]-hPadding-|", options: NSLayoutFormatOptions.alignAllLastBaseline, metrics: metrics, views: views))
}
open override func update() {
super.update()
if !shouldShowTitle() {
textLabel?.text = nil
detailTextLabel?.text = nil
}
slider.value = row.value ?? 0.0
}
func valueChanged() {
let roundedValue: Float
let steps = Float(sliderRow.steps)
if steps > 0 {
let stepValue = round((slider.value - slider.minimumValue) / (slider.maximumValue - slider.minimumValue) * steps)
let stepAmount = (slider.maximumValue - slider.minimumValue) / steps
roundedValue = stepValue * stepAmount + self.slider.minimumValue
}
else {
roundedValue = slider.value
}
row.value = roundedValue
if shouldShowTitle() {
valueLabel.text = "\(row.value!)"
}
}
fileprivate func shouldShowTitle() -> Bool {
return row.title?.isEmpty == false
}
fileprivate var sliderRow: SliderRow {
return row as! SliderRow
}
}
/// A row that displays a UISlider. If there is a title set then the title and value will appear above the UISlider.
public final class SliderRow: Row<Float, SliderCell>, RowType {
public var minimumValue: Float = 0.0
public var maximumValue: Float = 10.0
public var steps: UInt = 20
required public init(tag: String?) {
super.init(tag: tag)
}
}
| mit | a4c76dea5d71e9f36dbbbc804c9e7157 | 40.578125 | 226 | 0.677565 | 5.092823 | false | false | false | false |
Aghassi/Notify | Notify/Handlers/SpotifyNotificationHandler.swift | 1 | 2179 | //
// NotificationHandler.swift
// Type: Object and Delegate of NSUserNotificationCenter
//
// Notify
//
// Created by David Aghassi on 9/19/15.
// Copyright © 2015 David Aghassi. All rights reserved.
//
import Foundation
import Cocoa
import Alamofire
import SwiftyJSON
class SpotifyNotificationHandler: NSObject, NotificationHandler {
var track = Song()
let client: Client = .Spotify
/**
Called when the application changes its playback state
@param notification, an NSNotification passed in when state changes
**/
func spotifyStateChanged(notification: NSNotification) {
self.stateChanged(notification)
}
/**********************
* Getters and Setters *
**********************/
func setCurrentTrack(info: NSDictionary) {
// Reset to no data
track = Song()
// Set the current track
track.name = info["Name"] as! String
track.artist = info["Artist"] as! String
track.album = info["Album"] as! String
// We receive values like spotify:track:0QXPKOlwGXrEUId6H1Eyxa. We just need the last section
let fullId = info["Track ID"] as! String
track.trackID = fullId.componentsSeparatedByString(":")[2]
// Get the album art for the track
let spotifyApiUrl = "https://api.spotify.com/v1/tracks/\(track.trackID)"
Alamofire.request(.GET, spotifyApiUrl, parameters: nil)
.responseJSON { (req, res, result) in
if (result.isFailure) {
NSLog("Error: \(result.error)")
}
else {
var json = JSON(result.value!)
// Get the album art. Size doesn't matter.
var image = json["album"]["images"][0]
let albumArtworkUrl: NSURL = NSURL(string: image["url"].stringValue)!
let albumArtwork = NSImage(contentsOfURL: albumArtworkUrl)
self.track.image = albumArtwork!
// Send the notification
self.sendNotification()
}
}
}
} | mit | 28a6b29d3550791dea470970f149e75f | 32.015152 | 101 | 0.568411 | 4.961276 | false | false | false | false |
nextcloud/ios | iOSClient/Main/Section Header Footer/NCSectionHeaderFooter.swift | 1 | 13920 | //
// NCSectionHeaderFooter.swift
// Nextcloud
//
// Created by Marino Faggiana on 09/10/2018.
// Copyright © 2018 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import MarkdownKit
class NCSectionHeaderMenu: UICollectionReusableView, UIGestureRecognizerDelegate {
@IBOutlet weak var buttonSwitch: UIButton!
@IBOutlet weak var buttonOrder: UIButton!
@IBOutlet weak var buttonMore: UIButton!
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
@IBOutlet weak var viewButtonsCommand: UIView!
@IBOutlet weak var viewButtonsView: UIView!
@IBOutlet weak var viewSeparator: UIView!
@IBOutlet weak var viewRichWorkspace: UIView!
@IBOutlet weak var viewSection: UIView!
@IBOutlet weak var viewButtonsCommandHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var viewButtonsViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var viewSeparatorHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var viewRichWorkspaceHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var viewSectionHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var textViewRichWorkspace: UITextView!
@IBOutlet weak var labelSection: UILabel!
weak var delegate: NCSectionHeaderMenuDelegate?
private var markdownParser = MarkdownParser()
private var richWorkspaceText: String?
private var textViewColor: UIColor?
private let gradient: CAGradientLayer = CAGradientLayer()
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = .clear
buttonSwitch.setImage(UIImage(named: "switchList")!.image(color: NCBrandColor.shared.systemGray1, size: 25), for: .normal)
buttonOrder.setTitle("", for: .normal)
buttonOrder.setTitleColor(.systemBlue, for: .normal)
buttonMore.setImage(UIImage(named: "more")!.image(color: NCBrandColor.shared.systemGray1, size: 25), for: .normal)
button1.setImage(nil, for: .normal)
button1.isHidden = true
button1.backgroundColor = .clear
button1.setTitleColor(.systemBlue, for: .normal)
button1.layer.borderColor = NCBrandColor.shared.systemGray1.cgColor
button1.layer.borderWidth = 0.4
button1.layer.cornerRadius = 3
button2.setImage(nil, for: .normal)
button2.isHidden = true
button2.backgroundColor = .clear
button2.setTitleColor(.systemBlue, for: .normal)
button2.layer.borderColor = NCBrandColor.shared.systemGray1.cgColor
button2.layer.borderWidth = 0.4
button2.layer.cornerRadius = 3
button3.setImage(nil, for: .normal)
button3.isHidden = true
button3.backgroundColor = .clear
button3.setTitleColor(.systemBlue, for: .normal)
button3.layer.borderColor = NCBrandColor.shared.systemGray1.cgColor
button3.layer.borderWidth = 0.4
button3.layer.cornerRadius = 3
// Gradient
gradient.startPoint = CGPoint(x: 0, y: 0.50)
gradient.endPoint = CGPoint(x: 0, y: 1)
viewRichWorkspace.layer.addSublayer(gradient)
let tap = UITapGestureRecognizer(target: self, action: #selector(touchUpInsideViewRichWorkspace(_:)))
tap.delegate = self
viewRichWorkspace?.addGestureRecognizer(tap)
viewSeparatorHeightConstraint.constant = 0.5
viewSeparator.backgroundColor = .separator
markdownParser = MarkdownParser(font: UIFont.systemFont(ofSize: 15), color: .label)
markdownParser.header.font = UIFont.systemFont(ofSize: 25)
if let richWorkspaceText = richWorkspaceText {
textViewRichWorkspace.attributedText = markdownParser.parse(richWorkspaceText)
}
textViewColor = .label
labelSection.text = ""
viewSectionHeightConstraint.constant = 0
}
override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
gradient.frame = viewRichWorkspace.bounds
setInterfaceColor()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
setInterfaceColor()
}
//MARK: - Command
func setStatusButtonsCommand(enable: Bool) {
button1.isEnabled = enable
button2.isEnabled = enable
button3.isEnabled = enable
}
func setButtonsCommand(heigt :CGFloat, imageButton1: UIImage? = nil, titleButton1: String? = nil, imageButton2: UIImage? = nil, titleButton2: String? = nil, imageButton3: UIImage? = nil, titleButton3: String? = nil) {
viewButtonsCommandHeightConstraint.constant = heigt
if heigt == 0 {
viewButtonsView.isHidden = true
button1.isHidden = true
button2.isHidden = true
button3.isHidden = true
} else {
viewButtonsView.isHidden = false
if var image = imageButton1, let title = titleButton1 {
image = image.image(color: NCBrandColor.shared.systemGray1, size: 25)
button1.setImage(image, for: .normal)
button1.isHidden = false
button1.setTitle(title.firstUppercased, for: .normal)
}
if var image = imageButton2, let title = titleButton2 {
image = image.image(color: NCBrandColor.shared.systemGray1, size: 25)
button2.setImage(image, for: .normal)
button2.isHidden = false
button2.setTitle(title.firstUppercased, for: .normal)
}
if var image = imageButton3, let title = titleButton3 {
image = image.image(color: NCBrandColor.shared.systemGray1, size: 25)
button3.setImage(image, for: .normal)
button3.isHidden = false
button3.setTitle(title.firstUppercased, for: .normal)
}
}
}
//MARK: - View
func setStatusButtonsView(enable: Bool) {
buttonSwitch.isEnabled = enable
buttonOrder.isEnabled = enable
buttonMore.isEnabled = enable
}
func buttonMoreIsHidden(_ isHidden: Bool) {
buttonMore.isHidden = isHidden
}
func setImageSwitchList() {
buttonSwitch.setImage(UIImage(named: "switchList")!.image(color: NCBrandColor.shared.systemGray1, size: 50), for: .normal)
}
func setImageSwitchGrid() {
buttonSwitch.setImage(UIImage(named: "switchGrid")!.image(color: NCBrandColor.shared.systemGray1, size: 50), for: .normal)
}
func setButtonsView(heigt :CGFloat) {
viewButtonsViewHeightConstraint.constant = heigt
if heigt == 0 {
viewButtonsView.isHidden = true
} else {
viewButtonsView.isHidden = false
}
}
func setSortedTitle(_ title: String) {
let title = NSLocalizedString(title, comment: "")
//let size = title.size(withAttributes: [.font: buttonOrder.titleLabel?.font as Any])
buttonOrder.setTitle(title, for: .normal)
}
//MARK: - RichWorkspace
func setRichWorkspaceHeight(_ size: CGFloat) {
viewRichWorkspaceHeightConstraint.constant = size
if size == 0 {
viewRichWorkspace.isHidden = true
} else {
viewRichWorkspace.isHidden = false
}
}
func setInterfaceColor() {
if traitCollection.userInterfaceStyle == .dark {
gradient.colors = [UIColor(white: 0, alpha: 0).cgColor, UIColor.black.cgColor]
} else {
gradient.colors = [UIColor(white: 1, alpha: 0).cgColor, UIColor.white.cgColor]
}
}
func setRichWorkspaceText(_ text: String?) {
guard let text = text else { return }
if text != self.richWorkspaceText {
textViewRichWorkspace.attributedText = markdownParser.parse(text)
self.richWorkspaceText = text
}
}
//MARK: - Section
func setSectionHeight(_ size:CGFloat) {
viewSectionHeightConstraint.constant = size
if size == 0 {
viewSection.isHidden = true
} else {
viewSection.isHidden = false
}
}
// MARK: - Action
@IBAction func touchUpInsideSwitch(_ sender: Any) {
delegate?.tapButtonSwitch(sender)
}
@IBAction func touchUpInsideOrder(_ sender: Any) {
delegate?.tapButtonOrder(sender)
}
@IBAction func touchUpInsideMore(_ sender: Any) {
delegate?.tapButtonMore(sender)
}
@IBAction func touchUpInsideButton1(_ sender: Any) {
delegate?.tapButton1(sender)
}
@IBAction func touchUpInsideButton2(_ sender: Any) {
delegate?.tapButton2(sender)
}
@IBAction func touchUpInsideButton3(_ sender: Any) {
delegate?.tapButton3(sender)
}
@objc func touchUpInsideViewRichWorkspace(_ sender: Any) {
delegate?.tapRichWorkspace(sender)
}
}
protocol NCSectionHeaderMenuDelegate: AnyObject {
func tapButtonSwitch(_ sender: Any)
func tapButtonOrder(_ sender: Any)
func tapButtonMore(_ sender: Any)
func tapButton1(_ sender: Any)
func tapButton2(_ sender: Any)
func tapButton3(_ sender: Any)
func tapRichWorkspace(_ sender: Any)
}
// optional func
extension NCSectionHeaderMenuDelegate {
func tapButtonSwitch(_ sender: Any) {}
func tapButtonOrder(_ sender: Any) {}
func tapButtonMore(_ sender: Any) {}
func tapButton1(_ sender: Any) {}
func tapButton2(_ sender: Any) {}
func tapButton3(_ sender: Any) {}
func tapRichWorkspace(_ sender: Any) {}
}
class NCSectionHeader: UICollectionReusableView {
@IBOutlet weak var labelSection: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.clear
self.labelSection.text = ""
}
}
class NCSectionFooter: UICollectionReusableView, NCSectionFooterDelegate {
@IBOutlet weak var buttonSection: UIButton!
@IBOutlet weak var activityIndicatorSection: UIActivityIndicatorView!
@IBOutlet weak var labelSection: UILabel!
@IBOutlet weak var separator: UIView!
@IBOutlet weak var separatorHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var buttonSectionHeightConstraint: NSLayoutConstraint!
weak var delegate: NCSectionFooterDelegate?
var metadataForSection: NCMetadataForSection?
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.clear
labelSection.textColor = NCBrandColor.shared.gray
labelSection.text = ""
separator.backgroundColor = .separator
separatorHeightConstraint.constant = 0.5
buttonIsHidden(true)
activityIndicatorSection.isHidden = true
activityIndicatorSection.color = .label
}
func setTitleLabel(directories: Int, files: Int, size: Int64) {
var foldersText = ""
var filesText = ""
if directories > 1 {
foldersText = "\(directories) " + NSLocalizedString("_folders_", comment: "")
} else if directories == 1 {
foldersText = "1 " + NSLocalizedString("_folder_", comment: "")
}
if files > 1 {
filesText = "\(files) " + NSLocalizedString("_files_", comment: "") + " " + CCUtility.transformedSize(size)
} else if files == 1 {
filesText = "1 " + NSLocalizedString("_file_", comment: "") + " " + CCUtility.transformedSize(size)
}
if foldersText == "" {
labelSection.text = filesText
} else if filesText == "" {
labelSection.text = foldersText
} else {
labelSection.text = foldersText + ", " + filesText
}
}
func setTitleLabel(_ text: String) {
labelSection.text = text
}
func setButtonText(_ text: String) {
buttonSection.setTitle(text, for: .normal)
}
func separatorIsHidden(_ isHidden: Bool) {
separator.isHidden = isHidden
}
func buttonIsHidden(_ isHidden: Bool) {
buttonSection.isHidden = isHidden
if isHidden {
buttonSectionHeightConstraint.constant = 0
} else {
buttonSectionHeightConstraint.constant = NCGlobal.shared.heightFooterButton
}
}
func showActivityIndicatorSection() {
buttonSection.isHidden = true
buttonSectionHeightConstraint.constant = NCGlobal.shared.heightFooterButton
activityIndicatorSection.isHidden = false
activityIndicatorSection.startAnimating()
}
func hideActivityIndicatorSection() {
activityIndicatorSection.stopAnimating()
activityIndicatorSection.isHidden = true
}
// MARK: - Action
@IBAction func touchUpInsideButton(_ sender: Any) {
delegate?.tapButtonSection(sender, metadataForSection: metadataForSection)
}
}
protocol NCSectionFooterDelegate: AnyObject {
func tapButtonSection(_ sender: Any, metadataForSection: NCMetadataForSection?)
}
// optional func
extension NCSectionFooterDelegate {
func tapButtonSection(_ sender: Any, metadataForSection: NCMetadataForSection?) {}
}
| gpl-3.0 | 515ed962044bd803127730415278d1cc | 31.750588 | 221 | 0.664272 | 4.937567 | false | false | false | false |
JChauncyChandler/MizzouClasses | IT/4001/Fall_2017/Example_1/SwiftLanguageBasics/Swift Language Basics/main.swift | 1 | 1522 | //
// main.swift
// Swift Language Basics
//
// Created by Jackson Chandler on 9/8/17.
// Copyright © 2017 Jackson Chandler. All rights reserved.
//
import Foundation
let sample1: UInt8 = 0x3A
var sample2: UInt8 = 58
var heartRate: Int = 85
var deposits: Double = 135002796
let acceleration: Float = 9.800
var mass: Float = 14.6
var distance: Double = 129.763001
var lost: Bool = true
var expensive: Bool = true
var choice: Int = 2
let integral: Character = "\u{222B}"
let greeting: String = "Hello"
var name: String = "Karen"
if ( sample1 == sample2){
print("The samples are equal")
}
else{
print("The samples are not equal.")
}
if(heartRate >= 40 && heartRate <= 80){
print("Heart rate is normal.")
}else{
print("Heart rate is not normal.")
}
if(deposits >= 100000000){
print("You are exceedingly wealthy")
}else{
print("Sorry you are so poor.")
}
var force = mass * acceleration
print("force =", force)
print(distance, " is the distance.")
if(lost == true && expensive == true){
print("I am really sorry! I will get the manager.")
}
if(lost == true && expensive == false){
print("Here is coupon for 10% off.")
}
switch choice{
case 1:
print("You choose 1.")
case 2:
print("You choose 2.")
case 3:
print("You choose 3.")
default:
print("You made an unkown choice")
}
print(integral, "is an integral.")
var i: Int = 5
for i in 5...10{
print("i =", i)
}
var age: Int = 0
while age < 6{
print("age =", age)
age += 1
}
print(greeting, name)
| mit | c408d36897d4941a0fd3b697449cb1ca | 16.894118 | 59 | 0.639711 | 3.16875 | false | false | false | false |
akuraru/PureViewIcon | PureViewIcon/Views/PVICheckCircle.swift | 1 | 2027 | //
// PVICheckCircle.swift
//
// Created by akuraru on 2017/02/11.
//
import UIKit
import SnapKit
extension PVIView {
func mekeCheckCircleConstraints() {
base.snp.updateConstraints { (make) in
make.width.equalToSuperview()
make.height.equalToSuperview()
make.center.equalToSuperview()
}
base.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_4))
before.setup(width: 2)
main.setup(width: 2)
after.setup(width: 2)
// before
before.top.alpha = 1
before.left.alpha = 0
before.right.alpha = 0
before.bottom.alpha = 1
before.view.snp.makeConstraints { (make) in
make.centerX.equalToSuperview().multipliedBy(19 / 17.0)
make.centerY.equalToSuperview().multipliedBy(18 / 17.0)
make.width.equalToSuperview().multipliedBy(14 / 34.0)
make.height.equalToSuperview().multipliedBy(2 / 34.0)
}
before.view.transform = resetTransform()
// main
main.top.alpha = 0
main.left.alpha = 0
main.right.alpha = 0
main.bottom.alpha = 0
main.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.equalToSuperview().multipliedBy(30 / 34.0)
make.height.equalToSuperview().multipliedBy(30 / 34.0)
}
main.view.transform = resetTransform()
// after
after.top.alpha = 0
after.left.alpha = 1
after.right.alpha = 1
after.bottom.alpha = 0
after.view.snp.makeConstraints { (make) in
make.centerX.equalToSuperview().multipliedBy(12 / 17.0)
make.centerY.equalToSuperview().multipliedBy(15 / 17.0)
make.width.equalToSuperview().multipliedBy(2 / 34.0)
make.height.equalToSuperview().multipliedBy(8 / 34.0)
}
after.view.transform = resetTransform()
}
}
| mit | 47e9da46dc546872999a70d2f4fe1030 | 30.671875 | 75 | 0.579181 | 4.340471 | false | false | false | false |
radazzouz/firefox-ios | Client/Extensions/NSURLExtensionsMailTo.swift | 1 | 1915 | /* 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
/**
* Data structure containing metadata associated with a mailto: link. For additional details,
* see RFC 2368 https://tools.ietf.org/html/rfc2368
*/
public struct MailToMetadata {
public let to: String
public let headers: [String: String]
}
public extension URL {
/**
Extracts the metadata associated with a mailto: URL according to RFC 2368
https://tools.ietf.org/html/rfc2368
*/
func mailToMetadata() -> MailToMetadata? {
guard scheme == "mailto" else {
return nil
}
let urlString = absoluteString
// Extract 'to' value
let toStart = urlString.characters.index(urlString.startIndex, offsetBy: "mailto:".characters.count)
let toEnd = urlString.characters.index(of: "?") ?? urlString.endIndex
let to = urlString.substring(with: toStart..<toEnd)
guard toEnd != urlString.endIndex else {
return MailToMetadata(to: to, headers: [String: String]())
}
// Extract headers
let headersString = ""//urlString.substring(with: <#T##String.CharacterView corresponding to `toEnd`##String.CharacterView#>.index(toEnd, offsetBy: 1)..<urlString.endIndex)
var headers = [String: String]()
let headerComponents = headersString.components(separatedBy: "&")
headerComponents.forEach { headerPair in
let components = headerPair.components(separatedBy: "=")
guard components.count == 2 else {
return
}
let (hname, hvalue) = (components[0], components[1])
headers[hname] = hvalue
}
return MailToMetadata(to: to, headers: headers)
}
}
| mpl-2.0 | f7f930f61ebb9825934238b6897f7a7a | 33.818182 | 180 | 0.639687 | 4.402299 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | 04-App Architecture/Swift 2/Breadcrumbs/Breadcrumbs-5/Breadcrumbs/BCOptionsTableViewController.swift | 1 | 3939 | //
// BCOptionsTableViewController.swift
// Breadcrumbs
//
// Created by Nicholas Outram on 22/01/2016.
// Copyright © 2016 Plymouth University. All rights reserved.
//
import UIKit
class BCOptionsTableViewController: UITableViewController {
// MARK: - Outlets
@IBOutlet weak var backgroundUpdateSwitch: UISwitch!
@IBOutlet weak var headingUPSwitch: UISwitch!
@IBOutlet weak var headingUPLabel: UILabel!
@IBOutlet weak var showTrafficSwitch: UISwitch!
@IBOutlet weak var distanceSlider: UISlider!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var gpsPrecisionLabel: UILabel!
@IBOutlet weak var gpsPrecisionSlider: UISlider!
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - Actions
@IBAction func doBackgroundUpdateSwitch(sender: AnyObject) {
print("\(__FUNCTION__)")
}
@IBAction func doHeadingUpSwitch(sender: AnyObject) {
print("\(__FUNCTION__)")
}
@IBAction func doShowTrafficSwitch(sender: AnyObject) {
print("\(__FUNCTION__)")
}
@IBAction func doDistanceSliderChanged(sender: AnyObject) {
print("\(__FUNCTION__)")
}
@IBAction func doGPSPrecisionSliderChanged(sender: AnyObject) {
print("\(__FUNCTION__)")
}
}
| mit | ec3c60e7387520cda9f3e82d98feab38 | 32.092437 | 157 | 0.676993 | 5.416781 | false | false | false | false |
srn214/Floral | Floral/Floral/Classes/Module/Community(研究院)/View/LDRecommendReusableView.swift | 1 | 1949 | //
// LDRecommendReusableView.swift
// Floral
//
// Created by LDD on 2019/7/20.
// Copyright © 2019 文刂Rn. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class LDRecommendReusableView: CollectionReusableView {
fileprivate let titleLabel = Label().then {
$0.font = UIFont.autoFontBoldSize(16)
}
fileprivate let moreButton = Button().then {
$0.setTitleColor(UIColor.gray, for: .normal)
$0.titleLabel?.font = UIFont.autoFontSize(15)
$0.setImage(UIImage(named: "p_back_right"), for: .normal)
}
fileprivate var typeId: String = ""
/// (typeId, title)
var moreBtnTap: ((String, String?) -> ())?
override func setupUI() {
super.setupUI()
addSubview(titleLabel)
addSubview(moreButton)
moreButton.rx.tap
.subscribe(onNext: { [weak self] (_) in
guard let self = self else { return }
if let _block = self.moreBtnTap {
_block(self.typeId, self.titleLabel.text ?? "")
}
}).disposed(by: rx.disposeBag)
}
override func setupConstraints() {
super.setupConstraints()
titleLabel.snp.makeConstraints { (make) in
make.bottom.equalToSuperview().offset(-k_Margin_Fifteen)
make.left.equalToSuperview()
}
moreButton.snp.makeConstraints { (make) in
make.centerY.equalTo(titleLabel)
make.right.equalToSuperview()
}
}
func setData(title: String, total: Int, isMore: Bool, typeId: String) {
titleLabel.text = title
moreButton.isHidden = !isMore
moreButton.setTitle("查看更多( \(total) )", for: .normal)
moreButton.setImage(position: .right, spacing: 5)
self.typeId = typeId
}
}
| mit | 95eb78db94402d636c31510f1fd36885 | 26.267606 | 75 | 0.560434 | 4.576832 | false | false | false | false |
tkremenek/swift | benchmark/single-source/CharacterLiteralsLarge.swift | 34 | 1598 | //===--- CharacterLiteralsLarge.swift -------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test tests the performance of Characters initialized from literals
// which don't fit into the small (63-bit) representation and need to allocate
// and retain a StringBuffer.
import TestsUtils
public let CharacterLiteralsLarge = BenchmarkInfo(
name: "CharacterLiteralsLarge",
runFunction: run_CharacterLiteralsLarge,
tags: [.validation, .api, .String])
@inline(never)
func makeCharacter_UTF8Length9() -> Character {
return "a\u{0300}\u{0301}\u{0302}\u{0303}"
}
@inline(never)
func makeCharacter_UTF8Length10() -> Character {
return "\u{00a9}\u{0300}\u{0301}\u{0302}\u{0303}"
}
@inline(never)
func makeCharacter_UTF8Length11() -> Character {
return "a\u{0300}\u{0301}\u{0302}\u{0303}\u{0304}"
}
@inline(never)
func makeCharacter_UTF8Length12() -> Character {
return "\u{00a9}\u{0300}\u{0301}\u{0302}\u{0303}\u{0304}"
}
public func run_CharacterLiteralsLarge(_ N: Int) {
for _ in 0...10000 * N {
_ = makeCharacter_UTF8Length9()
_ = makeCharacter_UTF8Length10()
_ = makeCharacter_UTF8Length11()
_ = makeCharacter_UTF8Length12()
}
}
| apache-2.0 | d2fa39514d7fcf9212f8477fa75b8620 | 30.96 | 80 | 0.658949 | 3.76 | false | true | false | false |
ohwutup/ReactiveCocoa | ReactiveCocoaTests/AppKit/NSPopUpButtonSpec.swift | 1 | 2548 | import Quick
import Nimble
import ReactiveCocoa
import ReactiveSwift
import Result
import AppKit
final class NSPopUpButtonSpec: QuickSpec {
override func spec() {
describe("NSPopUpButton") {
var button: NSPopUpButton!
var window: NSWindow!
weak var _button: NSButton?
let testTitles = (0..<100).map { $0.description }
beforeEach {
window = NSWindow()
button = NSPopUpButton(frame: .zero)
_button = button
button.addItems(withTitles: testTitles )
window.contentView?.addSubview(button)
}
afterEach {
autoreleasepool {
button.removeFromSuperview()
button = nil
}
expect(_button).to(beNil())
}
it("should emit selected index changes") {
var values = [Int]()
button.reactive.selectedIndexes.observeValues { values.append($0) }
button.menu?.performActionForItem(at: 1)
button.menu?.performActionForItem(at: 99)
expect(values) == [1, 99]
}
it("should emit selected title changes") {
var values = [String]()
button.reactive.selectedTitles.observeValues { values.append($0) }
button.menu?.performActionForItem(at: 1)
button.menu?.performActionForItem(at: 99)
expect(values) == ["1", "99"]
}
it("should accept changes from its bindings to its index values") {
let (signal, observer) = Signal<Int?, NoError>.pipe()
button.reactive.selectedIndex <~ SignalProducer(signal)
observer.send(value: 1)
expect(button.indexOfSelectedItem) == 1
observer.send(value: 99)
expect(button.indexOfSelectedItem) == 99
observer.send(value: nil)
expect(button.indexOfSelectedItem) == -1
expect(button.selectedItem?.title).to(beNil())
}
it("should accept changes from its bindings to its title values") {
let (signal, observer) = Signal<String?, NoError>.pipe()
button.reactive.selectedTitle <~ SignalProducer(signal)
observer.send(value: "1")
expect(button.selectedItem?.title) == "1"
observer.send(value: "99")
expect(button.selectedItem?.title) == "99"
observer.send(value: nil)
expect(button.selectedItem?.title).to(beNil())
expect(button.indexOfSelectedItem) == -1
}
it("should emit selected item changes") {
var values = [NSMenuItem]()
button.reactive.selectedItems.observeValues { values.append($0) }
button.menu?.performActionForItem(at: 1)
button.menu?.performActionForItem(at: 99)
let titles = values.map { $0.title }
expect(titles) == ["1", "99"]
}
}
}
}
| mit | b8b0494237f014ca9932a0d40517a994 | 26.106383 | 71 | 0.660126 | 3.769231 | false | false | false | false |
robconrad/fledger-common | FledgerCommon/services/models/item/ItemServiceImpl.swift | 1 | 2547 | //
// ItemService.swift
// fledger-ios
//
// Created by Robert Conrad on 4/12/15.
// Copyright (c) 2015 TwoSpec Inc. All rights reserved.
//
import Foundation
import SQLite
class ItemServiceImpl: ItemService, HasShieldedPersistenceEngine {
let engine: ShieldedPersistenceEngine<Item, StandardPersistenceEngine<Item>>
private let table: SchemaType
private let id: Expression<Int64>
required init() {
id = DatabaseSvc().items[Fields.id]
let _table = DatabaseSvc().items.join(DatabaseSvc().types, on: Fields.typeId == DatabaseSvc().types[Fields.id])
table = _table
engine = ShieldedPersistenceEngine(engine: StandardPersistenceEngine<Item>(
modelType: ModelType.Item,
fromPFObject: { pf in Item(pf: pf) },
fromRow: { row in Item(row: row) },
table: table,
defaultOrder: { q in q.order(Fields.date.desc, _table[Fields.id].desc) },
baseFilter: { q in q.filter(Fields.amount != 0) }
))
}
func getTransferPair(first: Item) -> Item? {
return DatabaseSvc().db.pluck(table.filter(
Fields.date == first.date &&
Fields.comments == first.comments &&
Fields.accountId != first.accountId &&
Fields.typeId == TypeSvc().transferId
)).map { Item(row: $0) }
}
func getSum(item: Item, filters: Filters) -> Double {
return DatabaseSvc().db.scalar(table.filter(
Fields.date < item.date ||
(Fields.date == item.date && id <= item.id!))
.select(Fields.amount.sum)) ?? 0
}
func getFiltersFromDefaults() -> ItemFilters {
let filters = ItemFilters()
filters.accountId = (NSUserDefaults.standardUserDefaults().valueForKey("filters.accountId") as? NSNumber)?.longLongValue
filters.startDate = NSUserDefaults.standardUserDefaults().valueForKey("filters.startDate") as? NSDate
filters.endDate = NSUserDefaults.standardUserDefaults().valueForKey("filters.endDate") as? NSDate
filters.typeId = (NSUserDefaults.standardUserDefaults().valueForKey("filters.typeId") as? NSNumber)?.longLongValue
filters.groupId = (NSUserDefaults.standardUserDefaults().valueForKey("filters.groupId") as? NSNumber)?.longLongValue
filters.count = ItemSvc().defaultCount()
filters.offset = 0
return filters
}
func defaultCount() -> Int {
return 30
}
} | mit | 94c8692fae2e12925ff05d325cddef7e | 34.887324 | 128 | 0.62073 | 4.597473 | false | false | false | false |
lennet/bugreporter | Bugreporter/Helper/ValidatorUtility.swift | 1 | 2065 | //
// ValidatorUtility.swift
// Bugreporter
//
// Created by Leo Thomas on 16/07/16.
// Copyright © 2016 Leonard Thomas. All rights reserved.
//
import Foundation
class ValidatorUtility {
class func validTitle(value: String) -> Bool {
return !value.isEmpty // TODO!
}
class func validDescription(value: String) -> Bool {
return !value.isEmpty // TODO!
}
class func validEnvironment(value: String) -> Bool {
do {
// check for device
let deviceRegexp = try NSRegularExpression(pattern: "(iPhone|iPad)(\\s){0,3}(Pro|Air|s)?\\d?", options: .useUnixLineSeparators)
guard deviceRegexp.numberOfMatches(in: value, options: .withoutAnchoringBounds, range: NSMakeRange(0, value.characters.count)) > 0 else {
return false
}
let inputWithoutDevice = deviceRegexp.stringByReplacingMatches(in: value, options: .withoutAnchoringBounds, range: NSMakeRange(0, value.characters.count), withTemplate: "")
// check for two version numbers (Device & App)
let versionRegexp = try NSRegularExpression(pattern: "(\\d\\.)?(\\d+\\.)?(\\*|\\d+)", options: .useUnixLineSeparators)
guard versionRegexp.numberOfMatches(in: inputWithoutDevice, options: .withoutAnchoringBounds, range: NSMakeRange(0, inputWithoutDevice.characters.count)) >= 2 else {
return false
}
} catch {
return false
}
return true
}
class func validReproduceSteps(value: String) -> Bool {
var lines: [String] = []
value.enumerateLines { (line, stop) in
lines.append(line)
}
var validLines = lines.count
for line in lines {
if line.characters.count < 5 {
validLines -= 1
}
}
guard validLines > 2 else {
return false
}
return true
}
}
| mit | acd0d513d73e7c2a2c545a3a54cb54cd | 29.352941 | 184 | 0.563953 | 4.766744 | false | false | false | false |
kevin00223/iOS-demo | rac_demo/Pods/ReactiveSwift/Sources/Scheduler.swift | 2 | 19500 | //
// Scheduler.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Dispatch
import Foundation
#if os(Linux)
import let CDispatch.NSEC_PER_SEC
#endif
/// Represents a serial queue of work items.
public protocol Scheduler: class {
/// Enqueues an action on the scheduler.
///
/// When the work is executed depends on the scheduler in use.
///
/// - parameters:
/// - action: The action to be scheduled.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(_ action: @escaping () -> Void) -> Disposable?
}
/// A particular kind of scheduler that supports enqueuing actions at future
/// dates.
public protocol DateScheduler: Scheduler {
/// The current date, as determined by this scheduler.
///
/// This can be implemented to deterministically return a known date (e.g.,
/// for testing purposes).
var currentDate: Date { get }
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: The start date.
/// - action: A closure of the action to be performed.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(after date: Date, action: @escaping () -> Void) -> Disposable?
/// Schedules a recurring action at the given interval, beginning at the
/// given date.
///
/// - parameters:
/// - date: The start date.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition.
/// - action: A closure of the action to be performed.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `schedule(after:interval:leeway:action)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable?
}
/// A scheduler that performs all work synchronously.
public final class ImmediateScheduler: Scheduler {
public init() {}
/// Immediately calls passed in `action`.
///
/// - parameters:
/// - action: A closure of the action to be performed.
///
/// - returns: `nil`.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
action()
return nil
}
}
/// A scheduler that performs all work on the main queue, as soon as possible.
///
/// If the caller is already running on the main queue when an action is
/// scheduled, it may be run synchronously. However, ordering between actions
/// will always be preserved.
public final class UIScheduler: Scheduler {
private static let dispatchSpecificKey = DispatchSpecificKey<UInt8>()
private static let dispatchSpecificValue = UInt8.max
private static var __once: () = {
DispatchQueue.main.setSpecific(key: UIScheduler.dispatchSpecificKey,
value: dispatchSpecificValue)
}()
#if os(Linux)
private var queueLength: Atomic<Int32> = Atomic(0)
#else
// `inout` references do not guarantee atomicity. Use `UnsafeMutablePointer`
// instead.
//
// https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20161205/004147.html
private let queueLength: UnsafeMutablePointer<Int32> = {
let memory = UnsafeMutablePointer<Int32>.allocate(capacity: 1)
memory.initialize(to: 0)
return memory
}()
deinit {
queueLength.deinitialize(count: 1)
queueLength.deallocate()
}
#endif
/// Initializes `UIScheduler`
public init() {
/// This call is to ensure the main queue has been setup appropriately
/// for `UIScheduler`. It is only called once during the application
/// lifetime, since Swift has a `dispatch_once` like mechanism to
/// lazily initialize global variables and static variables.
_ = UIScheduler.__once
}
/// Queues an action to be performed on main queue. If the action is called
/// on the main thread and no work is queued, no scheduling takes place and
/// the action is called instantly.
///
/// - parameters:
/// - action: A closure of the action to be performed on the main thread.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
let positionInQueue = enqueue()
// If we're already running on the main queue, and there isn't work
// already enqueued, we can skip scheduling and just execute directly.
if positionInQueue == 1 && DispatchQueue.getSpecific(key: UIScheduler.dispatchSpecificKey) == UIScheduler.dispatchSpecificValue {
action()
dequeue()
return nil
} else {
let disposable = AnyDisposable()
DispatchQueue.main.async {
defer { self.dequeue() }
guard !disposable.isDisposed else { return }
action()
}
return disposable
}
}
private func dequeue() {
#if os(Linux)
queueLength.modify { $0 -= 1 }
#else
OSAtomicDecrement32(queueLength)
#endif
}
private func enqueue() -> Int32 {
#if os(Linux)
return queueLength.modify { value -> Int32 in
value += 1
return value
}
#else
return OSAtomicIncrement32(queueLength)
#endif
}
}
/// A `Hashable` wrapper for `DispatchSourceTimer`. `Hashable` conformance is
/// based on the identity of the wrapper object rather than the wrapped
/// `DispatchSourceTimer`, so two wrappers wrapping the same timer will *not*
/// be equal.
private final class DispatchSourceTimerWrapper: Hashable {
private let value: DispatchSourceTimer
fileprivate var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
fileprivate init(_ value: DispatchSourceTimer) {
self.value = value
}
fileprivate static func ==(lhs: DispatchSourceTimerWrapper, rhs: DispatchSourceTimerWrapper) -> Bool {
// Note that this isn't infinite recursion thanks to `===`.
return lhs === rhs
}
}
/// A scheduler backed by a serial GCD queue.
public final class QueueScheduler: DateScheduler {
/// A singleton `QueueScheduler` that always targets the main thread's GCD
/// queue.
///
/// - note: Unlike `UIScheduler`, this scheduler supports scheduling for a
/// future date, and will always schedule asynchronously (even if
/// already running on the main thread).
public static let main = QueueScheduler(internalQueue: DispatchQueue.main)
public var currentDate: Date {
return Date()
}
public let queue: DispatchQueue
private var timers: Atomic<Set<DispatchSourceTimerWrapper>>
internal init(internalQueue: DispatchQueue) {
queue = internalQueue
timers = Atomic(Set())
}
/// Initializes a scheduler that will target the given queue with its
/// work.
///
/// - note: Even if the queue is concurrent, all work items enqueued with
/// the `QueueScheduler` will be serial with respect to each other.
///
/// - warning: Obsoleted in OS X 10.11
@available(OSX, deprecated:10.10, obsoleted:10.11, message:"Use init(qos:name:targeting:) instead")
@available(iOS, deprecated:8.0, obsoleted:9.0, message:"Use init(qos:name:targeting:) instead.")
public convenience init(queue: DispatchQueue, name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler") {
self.init(internalQueue: DispatchQueue(label: name, target: queue))
}
/// Initializes a scheduler that creates a new serial queue with the
/// given quality of service class.
///
/// - parameters:
/// - qos: Dispatch queue's QoS value.
/// - name: A name for the queue in the form of reverse domain.
/// - targeting: (Optional) The queue on which this scheduler's work is
/// targeted
@available(OSX 10.10, *)
public convenience init(
qos: DispatchQoS = .default,
name: String = "org.reactivecocoa.ReactiveSwift.QueueScheduler",
targeting targetQueue: DispatchQueue? = nil
) {
self.init(internalQueue: DispatchQueue(
label: name,
qos: qos,
target: targetQueue
))
}
/// Schedules action for dispatch on internal queue
///
/// - parameters:
/// - action: A closure of the action to be scheduled.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
let d = AnyDisposable()
queue.async {
if !d.isDisposed {
action()
}
}
return d
}
private func wallTime(with date: Date) -> DispatchWallTime {
let (seconds, frac) = modf(date.timeIntervalSince1970)
let nsec: Double = frac * Double(NSEC_PER_SEC)
let walltime = timespec(tv_sec: Int(seconds), tv_nsec: Int(nsec))
return DispatchWallTime(timespec: walltime)
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: The start date.
/// - action: A closure of the action to be performed.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? {
let d = AnyDisposable()
queue.asyncAfter(wallDeadline: wallTime(with: date)) {
if !d.isDisposed {
action()
}
}
return d
}
/// Schedules a recurring action at the given interval and beginning at the
/// given start date. A reasonable default timer interval leeway is
/// provided.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - action: Closure of the action to repeat.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `schedule(after:interval:leeway:action)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, interval: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return schedule(after: date, interval: interval, leeway: interval * 0.1, action: action)
}
/// Schedules a recurring action at the given interval with provided leeway,
/// beginning at the given start time.
///
/// - precondition: `interval` must be non-negative number.
/// - precondition: `leeway` must be non-negative number.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: A closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
precondition(interval.timeInterval >= 0)
precondition(leeway.timeInterval >= 0)
let timer = DispatchSource.makeTimerSource(
flags: DispatchSource.TimerFlags(rawValue: UInt(0)),
queue: queue
)
#if swift(>=4.0)
timer.schedule(wallDeadline: wallTime(with: date),
repeating: interval,
leeway: leeway)
#else
timer.scheduleRepeating(wallDeadline: wallTime(with: date),
interval: interval,
leeway: leeway)
#endif
timer.setEventHandler(handler: action)
timer.resume()
let wrappedTimer = DispatchSourceTimerWrapper(timer)
timers.modify { timers in
timers.insert(wrappedTimer)
}
return AnyDisposable { [weak self] in
timer.cancel()
if let scheduler = self {
scheduler.timers.modify { timers in
timers.remove(wrappedTimer)
}
}
}
}
}
/// A scheduler that implements virtualized time, for use in testing.
public final class TestScheduler: DateScheduler {
private final class ScheduledAction {
let date: Date
let action: () -> Void
init(date: Date, action: @escaping () -> Void) {
self.date = date
self.action = action
}
func less(_ rhs: ScheduledAction) -> Bool {
return date.compare(rhs.date) == .orderedAscending
}
}
private let lock = NSRecursiveLock()
private var _currentDate: Date
/// The virtual date that the scheduler is currently at.
public var currentDate: Date {
let d: Date
lock.lock()
d = _currentDate
lock.unlock()
return d
}
private var scheduledActions: [ScheduledAction] = []
/// Initializes a TestScheduler with the given start date.
///
/// - parameters:
/// - startDate: The start date of the scheduler.
public init(startDate: Date = Date(timeIntervalSinceReferenceDate: 0)) {
lock.name = "org.reactivecocoa.ReactiveSwift.TestScheduler"
_currentDate = startDate
}
private func schedule(_ action: ScheduledAction) -> Disposable {
lock.lock()
scheduledActions.append(action)
scheduledActions.sort { $0.less($1) }
lock.unlock()
return AnyDisposable {
self.lock.lock()
self.scheduledActions = self.scheduledActions.filter { $0 !== action }
self.lock.unlock()
}
}
/// Enqueues an action on the scheduler.
///
/// - note: The work is executed on `currentDate` as it is understood by the
/// scheduler.
///
/// - parameters:
/// - action: An action that will be performed on scheduler's
/// `currentDate`.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(_ action: @escaping () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: currentDate, action: action))
}
/// Schedules an action for execution after some delay.
///
/// - parameters:
/// - delay: A delay for execution.
/// - action: A closure of the action to perform.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after delay: DispatchTimeInterval, action: @escaping () -> Void) -> Disposable? {
return schedule(after: currentDate.addingTimeInterval(delay), action: action)
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: A starting date.
/// - action: A closure of the action to perform.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after date: Date, action: @escaping () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: date, action: action))
}
/// Schedules a recurring action at the given interval, beginning at the
/// given start date.
///
/// - precondition: `interval` must be non-negative.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - disposable: A disposable.
/// - action: A closure of the action to repeat.
///
/// - note: If you plan to specify an `interval` value greater than 200,000
/// seconds, use `schedule(after:interval:leeway:action)` instead
/// and specify your own `leeway` value to avoid potential overflow.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
private func schedule(after date: Date, interval: DispatchTimeInterval, disposable: SerialDisposable, action: @escaping () -> Void) {
precondition(interval.timeInterval >= 0)
disposable.inner = schedule(after: date) { [unowned self] in
action()
self.schedule(after: date.addingTimeInterval(interval), interval: interval, disposable: disposable, action: action)
}
}
/// Schedules a recurring action after given delay repeated at the given,
/// interval, beginning at the given interval counted from `currentDate`.
///
/// - parameters:
/// - delay: A delay for action's dispatch.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: A closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
@discardableResult
public func schedule(after delay: DispatchTimeInterval, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? {
return schedule(after: currentDate.addingTimeInterval(delay), interval: interval, leeway: leeway, action: action)
}
/// Schedules a recurring action at the given interval with
/// provided leeway, beginning at the given start date.
///
/// - parameters:
/// - date: A date to schedule the first action for.
/// - interval: A repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: A closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
public func schedule(after date: Date, interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), action: @escaping () -> Void) -> Disposable? {
let disposable = SerialDisposable()
schedule(after: date, interval: interval, disposable: disposable, action: action)
return disposable
}
/// Advances the virtualized clock by an extremely tiny interval, dequeuing
/// and executing any actions along the way.
///
/// This is intended to be used as a way to execute actions that have been
/// scheduled to run as soon as possible.
public func advance() {
advance(by: .nanoseconds(1))
}
/// Advances the virtualized clock by the given interval, dequeuing and
/// executing any actions along the way.
///
/// - parameters:
/// - interval: Interval by which the current date will be advanced.
public func advance(by interval: DispatchTimeInterval) {
lock.lock()
advance(to: currentDate.addingTimeInterval(interval))
lock.unlock()
}
/// Advances the virtualized clock to the given future date, dequeuing and
/// executing any actions up until that point.
///
/// - parameters:
/// - newDate: Future date to which the virtual clock will be advanced.
public func advance(to newDate: Date) {
lock.lock()
assert(currentDate.compare(newDate) != .orderedDescending)
while scheduledActions.count > 0 {
if newDate.compare(scheduledActions[0].date) == .orderedAscending {
break
}
_currentDate = scheduledActions[0].date
let scheduledAction = scheduledActions.remove(at: 0)
scheduledAction.action()
}
_currentDate = newDate
lock.unlock()
}
/// Dequeues and executes all scheduled actions, leaving the scheduler's
/// date at `Date.distantFuture()`.
public func run() {
advance(to: Date.distantFuture)
}
/// Rewinds the virtualized clock by the given interval.
/// This simulates that user changes device date.
///
/// - parameters:
/// - interval: An interval by which the current date will be retreated.
public func rewind(by interval: DispatchTimeInterval) {
lock.lock()
let newDate = currentDate.addingTimeInterval(-interval)
assert(currentDate.compare(newDate) != .orderedAscending)
_currentDate = newDate
lock.unlock()
}
}
| mit | 7d373ff8f00d285ff3e407c3c271c6a8 | 31.125206 | 179 | 0.687692 | 3.890662 | false | false | false | false |
NextFaze/FazeKit | Sources/FazeKit/Classes/DateAdditions.swift | 1 | 3012 | //
// Copyright 2016 NextFaze
//
// 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.
//
// DateAdditions.swift
// FazeKit
//
// Created by swoolcock on 12/08/2016.
//
import Foundation
public extension Date {
func timeComponents(includeSeconds: Bool = false) -> DateComponents {
var units: NSCalendar.Unit = [NSCalendar.Unit.hour, NSCalendar.Unit.minute]
if includeSeconds {
units = [NSCalendar.Unit.hour, NSCalendar.Unit.minute, NSCalendar.Unit.second]
}
return (Calendar.current as NSCalendar).components(units, from: self)
}
func dateComponents() -> DateComponents {
let units: NSCalendar.Unit = [.year, .month, .day, .weekday]
return (Calendar.current as NSCalendar).components(units, from: self)
}
func dateAndTimeComponents() -> DateComponents {
let units: NSCalendar.Unit = [.year, .month, .day, .hour, .minute, .second]
return (Calendar.current as NSCalendar).components(units, from: self)
}
static func dateFromComponents(day: Int? = nil,
month: Int? = nil,
year: Int? = nil,
hour: Int? = nil,
minute: Int? = nil,
second: Int? = nil,
nanosecond: Int? = nil) -> Date? {
var components = DateComponents()
components.day = day
components.month = month
components.year = year
components.hour = hour
components.minute = minute
components.second = second
components.nanosecond = nanosecond
return Calendar.current.date(from: components)
}
func dateWithTimeComponents(hour: Int? = 0,
minute: Int? = 0,
second: Int? = nil,
nanosecond: Int? = nil) -> Date? {
var components = (Calendar.current as NSCalendar).components([.year, .month, .day], from: self)
components.hour = hour
components.minute = minute
components.second = second
components.nanosecond = nanosecond
return Calendar.current.date(from: components)
}
func stringWithFormat(_ format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
formatter.locale = Locale.current
return formatter.string(from: self)
}
}
| apache-2.0 | 181b6d87f05819ce927c6b2c7df6d231 | 37.126582 | 103 | 0.59595 | 4.735849 | false | false | false | false |
kellanburket/Passenger | Pod/Classes/Passenger/Media/Media.swift | 1 | 2964 | //
// PassengerMedia.swift
// Pods
//
// Created by Kellan Cummings on 7/3/15.
//
//
import Foundation
private var queue: NSOperationQueue = {
var queue = NSOperationQueue()
queue.name = "MediaLoadingQueue"
queue.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount
return queue
}()
/**
Base class for loading media objects from Urls. Any `Model` property which could take a Url type can take a media type instead.
*/
public class Media: ApiObject {
/**
The raw media URL
*/
public var url: NSURL?
/**
The delegate to be called on image load success/failure
*/
public var delegate: MediaLoadDelegate?
/**
Operation queue priority level
*/
public var priority: NSOperationQueuePriority = .Normal
private lazy var request: HttpRequest? = {
if let url = self.url {
return HttpRequest(URL: url, method: HttpMethod.Get, params: [String: AnyObject]()) { data, response, error in
if let response = response as? NSHTTPURLResponse {
switch response.statusCode {
case 200:
//println("\t(200)\tSuccess")
self.loadMedia(data)
default:
println("\t\(response.statusCode)\t\(response)")
if let delegate = self.delegate {
delegate.mediaDidNotLoad(self)
}
}
} else {
println("\tError\t\(error)")
if let delegate = self.delegate {
delegate.mediaDidNotLoad(self)
}
}
}
} else {
println("No Url Set.")
return nil
}
}()
internal func loadMedia(data: NSData) {
fatalError("Must Override Method")
}
/**
Attempts to load an image from the server using it's `url` property
:param: delegate A delegate to handle the load results
:param: queue The background queue to add the image loading process to, defaults to in-class queue
:param: priority The priority level of the operation, defaults to `.Normal`
*/
public func load(delegate: MediaLoadDelegate? = nil, queue: NSOperationQueue? = nil, priority: NSOperationQueuePriority = .Normal) {
self.delegate = delegate
if let request = request {
Http.get(request, queue: queue ?? queue, priority: priority)
} else {
println("No Http request set for '\(self.url)'")
}
}
convenience public init(url: NSURL) {
self.init()
self.url = url
}
required public init(_ properties: [String: AnyObject] = [String: AnyObject]()) {
super.init(properties)
}
} | mit | b6e1100c456623898cf2230787f10d45 | 29.255102 | 136 | 0.549595 | 5.066667 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Jetpack/Classes/ViewRelated/WordPress-to-Jetpack Migration/Common/Views/MigrationStepView.swift | 1 | 4023 | import UIKit
class MigrationStepView: UIView {
private let headerView: MigrationHeaderView
private let centerView: UIView
private let actionsView: MigrationActionsView
private lazy var centerContentView: UIView = {
let view = UIView()
view.addSubview(centerView)
return view
}()
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [headerView, centerContentView])
stackView.axis = .vertical
stackView.spacing = Constants.stackViewSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
return stackView
}()
private lazy var contentView: UIView = {
let contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(mainStackView)
return contentView
}()
private lazy var mainScrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(contentView)
return scrollView
}()
init(headerView: MigrationHeaderView,
actionsView: MigrationActionsView,
centerView: UIView) {
self.headerView = headerView
self.centerView = centerView
centerView.translatesAutoresizingMaskIntoConstraints = false
self.actionsView = actionsView
headerView.directionalLayoutMargins = Constants.headerViewMargins
actionsView.translatesAutoresizingMaskIntoConstraints = false
super.init(frame: .zero)
backgroundColor = MigrationAppearance.backgroundColor
addSubview(mainScrollView)
addSubview(actionsView)
activateConstraints()
}
private func activateConstraints() {
centerContentView.pinSubviewToAllEdges(centerView, insets: Constants.centerContentMargins)
contentView.pinSubviewToAllEdges(mainStackView)
NSLayoutConstraint.activate([
mainScrollView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
mainScrollView.leadingAnchor.constraint(equalTo: leadingAnchor),
mainScrollView.trailingAnchor.constraint(equalTo: trailingAnchor),
mainScrollView.bottomAnchor.constraint(equalTo: bottomAnchor),
])
mainScrollView.pinSubviewToAllEdges(contentView)
NSLayoutConstraint.activate([
contentView.widthAnchor.constraint(equalTo: widthAnchor),
actionsView.leadingAnchor.constraint(equalTo: leadingAnchor),
actionsView.trailingAnchor.constraint(equalTo: trailingAnchor),
actionsView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let bottomInset = actionsView.frame.size.height - safeAreaInsets.bottom
mainScrollView.contentInset.bottom = bottomInset + Constants.additionalBottomContentInset
mainScrollView.verticalScrollIndicatorInsets.bottom = bottomInset
mainScrollView.contentInset.top = Constants.topContentInset
}
private enum Constants {
/// Adds space between the content bottom edge and actions sheet top edge.
///
/// Bottom inset is added to the `scrollView` so the content is not covered by the Actions Sheet view.
/// The value of the bottom inset is computed in `layoutSubviews`.
static let additionalBottomContentInset: CGFloat = 10
/// Adds top padding to the `scrollView`.
static let topContentInset: CGFloat = UINavigationBar().intrinsicContentSize.height
static let centerContentMargins = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30)
static let stackViewSpacing: CGFloat = 20
static let headerViewMargins = NSDirectionalEdgeInsets(top: 0, leading: 30, bottom: 0, trailing: 30)
}
}
| gpl-2.0 | ad22e3c370b1fcd20d98c5a5d7f49efb | 38.831683 | 110 | 0.707681 | 6.217929 | false | false | false | false |
acrocat/EverLayout | Source/EverLayoutBridge.swift | 1 | 6296 | // EverLayout
//
// Copyright (c) 2017 Dale Webster
//
// 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
// MARK: - A special function to easily read data from an InputStream
internal extension Data {
/// Read the data received in an input stream
///
/// - Parameter input: InputStream to read
init(reading input: InputStream) {
self.init()
input.open()
let bufferSize = 2048
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
while input.hasBytesAvailable {
let read = input.read(buffer, maxLength: bufferSize)
if (read == 0) {
break // added
}
self.append(buffer, count: read)
}
buffer.deallocate(capacity: bufferSize)
}
}
public class EverLayoutBridge: NSObject , StreamDelegate {
static let shared : EverLayoutBridge = EverLayoutBridge()
public static var connectedHost : CFString?
public static var connectedPort : UInt32?
public static var connected : Bool = false
private static var attemptingConnection : Bool = false
private static var inputStream : InputStream?
private static var outputStream : OutputStream?
private static var connectionLoop : Timer?
private static let DEFAULT_IP : String = "127.0.0.1"
private static let DEFAULT_PORT : String = "3000"
static var readStream : Unmanaged<CFReadStream>?
static var writeStream : Unmanaged<CFWriteStream>?
/// Try to establish a socket connection with the EverLayout Bridge server app
///
/// - Parameters:
/// - IP: Address to connect to
/// - port: Port to connect on
public static func connectToLayoutServer (withIP IP : String? = nil , port : String? = nil)
{
let address = (IP ?? self.DEFAULT_IP) as CFString
let port : UInt32 = UInt32(port ?? self.DEFAULT_PORT)!
self.connectedHost = address
self.connectedPort = port
// Schedule the timer
self.connectionLoop?.invalidate()
self.connectionLoop = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(attemptConnectionToLayoutServer), userInfo: nil, repeats: true)
}
@objc private static func attemptConnectionToLayoutServer () {
guard self.connected == false , self.attemptingConnection == false , let connectedHost = self.connectedHost , let connectedPort = self.connectedPort else { return }
self.attemptingConnection = true
self.inputStream?.close()
self.outputStream?.close()
self.inputStream = nil
self.outputStream = nil
// Attempt to link the streams to this server
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, connectedHost, connectedPort, &readStream, &writeStream)
self.inputStream = readStream!.takeRetainedValue()
self.outputStream = writeStream!.takeRetainedValue()
self.inputStream?.delegate = self.shared
self.outputStream?.delegate = self.shared
self.inputStream?.schedule(in: .current, forMode: .defaultRunLoopMode)
self.outputStream?.schedule(in: .current, forMode: .defaultRunLoopMode)
self.inputStream?.open()
self.outputStream?.open()
}
/// Uses NotificationCenter to send update messages to loaded layouts in the app
///
/// - Parameters:
/// - layoutName: Name of the layout that has been updated
/// - layoutData: The new layout data
private static func postLayoutUpdate (layoutName : String , layoutData : Data) {
let notificationName : Notification.Name = Notification.Name("layout-update__\(layoutName)")
NotificationCenter.default.post(name: notificationName, object: layoutData)
}
/// Report a message to the bridge
///
/// - Parameter message: message to report
public static func sendReport (message : String) {
// self.socket?.emit("report", [
// "message":message
// ])
}
public func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
EverLayoutBridge.attemptingConnection = false
if eventCode == Stream.Event.endEncountered {
EverLayoutBridge.connected = false
print("Lost connection to the bridge, attemping reconnection...")
} else if eventCode == Stream.Event.openCompleted {
if EverLayoutBridge.connected == false {
EverLayoutBridge.connected = true
print("Connected to layout server")
}
} else if eventCode == Stream.Event.hasBytesAvailable {
// Data has been received
if let aStream = aStream as? InputStream {
let data = Data(reading: aStream)
let jsonData = JSON(data)
if let layoutName = jsonData.dictionary?["name"]?.string {
print(layoutName)
EverLayoutBridge.postLayoutUpdate(layoutName: layoutName, layoutData: data)
}
}
}
}
}
| mit | aa100ecaef531140f508b3a5e5c8322f | 39.358974 | 173 | 0.645489 | 5.11039 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.