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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eTilbudsavis/native-ios-eta-sdk | Sources/EventsTracker/EventsPool.swift | 1 | 6334 | //
// _____ _ _____
// | __| |_ ___ ___| __|_ _ ___
// |__ | | . | . | | | | | |
// |_____|_|_|___| _|_____|___|_|_|
// |_|
//
// Copyright (c) 2016 ShopGun. All rights reserved.
import Foundation
import UIKit
class EventsPool {
typealias EventShippingHandler<T> = ([T], @escaping ([String: EventShipperResult]) -> Void) -> Void
let dispatchInterval: TimeInterval
let dispatchLimit: Int
let shippingHandler: EventShippingHandler<ShippableEvent>
let cache: EventsCache<ShippableEvent>
init(dispatchInterval: TimeInterval,
dispatchLimit: Int,
shippingHandler: @escaping EventShippingHandler<ShippableEvent>,
cache: EventsCache<ShippableEvent>
) {
self.dispatchInterval = dispatchInterval
self.dispatchLimit = dispatchLimit
self.shippingHandler = shippingHandler
self.cache = cache
poolQueue.async {
// start flushing the cache on creation
if self.shouldFlushEvents() {
self.flushPendingEvents()
} else {
self.startTimerIfNeeded()
}
}
NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
}
/// Add an object to the pool
func push(event: ShippableEvent) {
poolQueue.async {
// add the object to the tail of the cache
self.cache.write(toTail: [event])
// flush any pending events (only if limit reached)
if self.shouldFlushEvents() {
self.flushPendingEvents()
} else {
self.startTimerIfNeeded()
}
}
}
// MARK: - Private
fileprivate var dispatchIntervalDelay: TimeInterval = 0
fileprivate let poolQueue: DispatchQueue = DispatchQueue(label: "com.shopgun.ios.sdk.pool.queue", attributes: [])
@objc
private func appDidEnterBackground(_ notification: Notification) {
poolQueue.async { [weak self] in
self?.flushPendingEvents()
}
}
// MARK: - Flushing
fileprivate var isFlushing: Bool = false
fileprivate func flushPendingEvents() {
// currently flushing. no-op
guard isFlushing == false else {
return
}
let eventsToShip = self.cache.read(fromHead: self.dispatchLimit)
// get the objects to be shipped
guard eventsToShip.count > 0 else {
return
}
isFlushing = true
// stop any running timer (will be restarted on completion)
flushTimer?.invalidate()
flushTimer = nil
// pass the objects to the shipper (on a bg queue)
DispatchQueue.global(qos: .background).async { [weak self] in
self?.shippingHandler(eventsToShip) { [weak self] results in
// perform completion in pool's queue (this will block events arriving until completed)
self?.poolQueue.async { [weak self] in
self?.handleShipperResults(results)
}
}
}
}
/// Handle the results recieved from the shipper. This will remove the successful & failed results from the cache, update the intervalDelay, and restart the timer
private func handleShipperResults(_ results: [String: EventShipperResult]) {
let idsToRemove: [String] = results.reduce([]) {
switch $1.value {
case .error, .success:
return $0 + [$1.key]
case .retry:
return $0
}
}
let counts = results.reduce(into: (success: 0, error: 0, retry: 0)) { (res, el) in
switch el.value {
case .error:
res.error += 1
case .success:
res.success += 1
case .retry:
res.retry += 1
}
}
Logger.log("📦 Events Shipped \(counts)", level: .debug, source: .EventsTracker)
// remove the successfully shipped events
self.cache.remove(ids: idsToRemove)
// if no events are shipped then scale back the interval
self.dispatchIntervalDelay = {
if idsToRemove.count == 0 && self.dispatchInterval > 0 {
let currentInterval = self.dispatchInterval + self.dispatchIntervalDelay
let maxInterval: TimeInterval = 60 * 5 // 5 mins
let newInterval = min(currentInterval * 1.1, maxInterval)
return newInterval - self.dispatchInterval
} else {
return 0
}
}()
self.isFlushing = false
// start the timer
self.startTimerIfNeeded()
}
fileprivate func shouldFlushEvents() -> Bool {
if isFlushing {
return false
}
// if pool size >= dispatchLimit
if self.cache.objectCount >= dispatchLimit {
return true
}
return false
}
// MARK: - Timer
fileprivate var flushTimer: Timer?
fileprivate func startTimerIfNeeded() {
guard flushTimer == nil && isFlushing == false && self.cache.objectCount > 0 else {
return
}
let interval = dispatchInterval + dispatchIntervalDelay
// generate a new timer. needs to be performed on main runloop
flushTimer = Timer(timeInterval: interval, target: self, selector: #selector(flushTimerTick(_:)), userInfo: nil, repeats: false)
RunLoop.main.add(flushTimer!, forMode: RunLoop.Mode.common)
}
@objc fileprivate func flushTimerTick(_ timer: Timer?) {
// called from main runloop
poolQueue.async {
self.flushTimer?.invalidate()
self.flushTimer = nil
self.flushPendingEvents()
}
}
}
| mit | 74e704d1c5f5c735eb5f3b0a356c34d4 | 31.137056 | 166 | 0.552045 | 5.101531 | false | false | false | false |
devpunk/cartesian | cartesian/View/DrawProject/Canvas/VDrawProjectCanvasNodeEffect.swift | 1 | 2214 | import UIKit
class VDrawProjectCanvasNodeEffect:UIView
{
private weak var viewCanvas:VDrawProjectCanvasView!
private var model:MDrawProjectCanvasEffect?
private let image:UIImage
private let imageWidth:CGFloat
private let imageHeight:CGFloat
init(
viewCanvas:VDrawProjectCanvasView,
model:DDrawable)
{
image = #imageLiteral(resourceName: "assetNodeEffectStar")
imageWidth = image.size.width
imageHeight = image.size.height
super.init(frame:CGRect.zero)
isHidden = true
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
isUserInteractionEnabled = false
self.viewCanvas = viewCanvas
let viewMask:VDrawProjectCanvasViewSpatial = VDrawProjectCanvasViewSpatial(
model:model,
viewCanvas:viewCanvas)
mask = viewMask
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
mask?.frame = bounds
mask?.setNeedsDisplay()
super.layoutSubviews()
}
override func draw(_ rect:CGRect)
{
guard
let _:CGContext = UIGraphicsGetCurrentContext(),
let model:MDrawProjectCanvasEffect = self.model
else
{
return
}
for item:MDrawProjectCanvasEffectItem in model.items
{
item.step()
let rect:CGRect = CGRect(
x:item.positionX,
y:item.positionY,
width:imageWidth,
height:imageHeight)
image.draw(in:rect)
}
}
//MARK: public
func start()
{
setNeedsDisplay()
let width:CGFloat = bounds.size.width
let height:CGFloat = bounds.size.height
model = MDrawProjectCanvasEffect(width:width, height:height)
isHidden = false
}
func end()
{
model = nil
isHidden = true
}
func tick()
{
setNeedsDisplay()
}
}
| mit | 9b7302cfe967bc29e64c949e7c346a86 | 22.305263 | 83 | 0.560976 | 5.439803 | false | false | false | false |
spearal/SpearalIOS | SpearalIOS/SpearalType.swift | 1 | 1418 | /**
* == @Spearal ==>
*
* Copyright (C) 2014 Franck WOLFF & William DRAI (http://www.spearal.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// author: Franck WOLFF
import Foundation
enum SpearalType: UInt8 {
// No parameters (0x00...0x0f).
case NULL = 0x00
case TRUE = 0x01
case FALSE = 0x02
// 4 bits of parameters (0x10...0xf0).
case INTEGRAL = 0x10
case BIG_INTEGRAL = 0x20
case FLOATING = 0x30
case BIG_FLOATING = 0x40
case STRING = 0x50
case BYTE_ARRAY = 0x60
case DATE_TIME = 0x70
case COLLECTION = 0x80
case MAP = 0x90
case ENUM = 0xa0
case CLASS = 0xb0
case BEAN = 0xc0
static func valueOf(parameterizedType:UInt8) -> SpearalType? {
return SpearalType(rawValue: parameterizedType < 0x10 ? parameterizedType : parameterizedType & UInt8(0xf0))
}
} | apache-2.0 | 8424d441b615b84307f89f9485483533 | 24.339286 | 116 | 0.657264 | 3.721785 | false | false | false | false |
skyfe79/RxGitSearch | RxGitSearch/service/GithubService.swift | 1 | 3269 | //
// GitHub.swift
// RxGitSearch
//
// Created by burt on 2016. 2. 5..
// Copyright © 2016년 burt. All rights reserved.
//
// [email protected]
// http://blog.burt.pe.kr
// http://github.com/skyfe79
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
import RxSwift
import RxCocoa
enum SearchWhere {
case REPOSITORY
case CODE
case ISSUE
case USER
}
final class GithubService<T: SearchResponseBase> {
private init() {}
static func rx_search(searchWhere: SearchWhere, what: String, repository: String? = nil, language: String? = nil) -> Observable<T> {
let parameter = SearchParameter.Builder()
.query(what)
.language(language)
.repository(repository)
.sort(.STARS)
.order(.DESC)
.build()
return rx_search(searchWhere, parameter: parameter)
}
static func rx_search(searchWhere: SearchWhere, parameter: SearchParameter) -> Observable<T> {
return Observable.create { subscriber -> Disposable in
let request = self.search(searchWhere, parameter: parameter)
.responseString(completionHandler: { (response : Response<String, NSError>) -> Void in
if let _ = response.result.value {
//print(result)
} else {
subscriber.onError(NSError(domain: "There is no results", code: 1000, userInfo: nil))
}
})
.responseObject({ (response : Response<T, NSError>) -> Void in
switch response.result {
case .Success(let value):
if value.isApiRateLimited() {
subscriber.onError(NSError(domain: value.apiRateLimitMessage!, code: -1, userInfo: nil))
} else {
subscriber.onNext(value)
subscriber.onCompleted()
}
case .Failure(let error):
subscriber.onError(error)
}
})
return AnonymousDisposable {
request.cancel()
}
}
}
static func search(searchWhere: SearchWhere, what: String) -> Request {
let parameter = SearchParameter.Builder()
.query(what)
.sort(.STARS)
.order(.DESC)
.build()
return self.search(searchWhere, parameter: parameter)
}
static func search(searchWhere: SearchWhere, parameter: SearchParameter) -> Request {
let search : Search
switch searchWhere {
case .REPOSITORY:
search = Search.Repository(param: parameter)
case .ISSUE:
search = Search.Issue(param: parameter)
case .CODE:
search = Search.Code(param: parameter)
case .USER:
search = Search.User(param: parameter)
}
let request = Alamofire.request(search)
return request
}
}
| mit | eb3b6c61db2ee3f85c24f09aa3e264f0 | 30.708738 | 136 | 0.514697 | 5.159558 | false | false | false | false |
apple/swift-nio-ssl | Tests/LinuxMain.swift | 1 | 2074 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// LinuxMain.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
#if os(Linux) || os(FreeBSD) || os(Android)
@testable import NIOSSLTests
@main
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
class LinuxMainRunner {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static func main() {
XCTMain([
testCase(ByteBufferBIOTest.allTests),
testCase(CertificateVerificationTests.allTests),
testCase(ClientSNITests.allTests),
testCase(CustomPrivateKeyTests.allTests),
testCase(IdentityVerificationTest.allTests),
testCase(NIOSSLALPNTest.allTests),
testCase(NIOSSLIntegrationTest.allTests),
testCase(NIOSSLSecureBytesTests.allTests),
testCase(ObjectIdentifierTests.allTests),
testCase(SSLCertificateExtensionsTests.allTests),
testCase(SSLCertificateTest.allTests),
testCase(SSLPKCS12BundleTest.allTests),
testCase(SSLPrivateKeyTest.allTests),
testCase(SecurityFrameworkVerificationTests.allTests),
testCase(TLSConfigurationTest.allTests),
testCase(UnwrappingTests.allTests),
])
}
}
#endif
| apache-2.0 | 6d788ba133e82cc0aad10591d2f96a5c | 38.132075 | 162 | 0.646577 | 5.263959 | false | true | false | false |
CosmicMind/Samples | Projects/Programmatic/TabsController/TabsController/BlueViewController.swift | 1 | 2803 | /*
* Copyright (C) 2015 - 2018, 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
import Material
class BlueViewController: UIViewController {
let v1 = UIView()
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Color.blue.base
prepareTabItem()
v1.motionIdentifier = "v1"
v1.backgroundColor = Color.red.base
view.layout(v1).width(100).vertically().right()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("Blue viewWillAppear")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("Blue viewDidAppear")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("Blue viewWillDisappear")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print("Blue viewDidDisappear")
}
}
extension BlueViewController {
fileprivate func prepareTabItem() {
tabItem.title = "Blue"
// tabItem.image = Icon.pen
tabItem.setTabItemImage(Icon.add, for: .normal)
tabItem.setTabItemImage(Icon.pen, for: .selected)
tabItem.setTabItemImage(Icon.photoLibrary, for: .highlighted)
}
}
| bsd-3-clause | 794b51cc644e2fed97f60cfd52fbf400 | 34.0375 | 88 | 0.738851 | 4.491987 | false | false | false | false |
carlos4242/raspberry-weather | LightDimmer.swift4a/main.swift | 1 | 3507 | import AVR
typealias IntegerLiteralType = UInt8
SetupSerial(baudRate: 9600)
// configuration constants
let triacPin = 4
let storedBrightnessLocation: UInt16 = 34
let storedOnOffLocation: UInt16 = 35
let brightnessi2cRegister = 6
let onOffi2cRegister = 7
let rotaryPin1 = 6
let rotaryPin2 = 7
let centerPin = 8
// pin state remembers the most recent states of the lines from the rotary encoder
var lastPinState: PinsState = (false, false, false)
// the delay factor is a UInt8 value that is easy to handle, as an I2C variable, etc.
// it is simply multiplied by 100 to get the number of microseconds to wait after
// a zero cross is detected before firing the triac
// in my experiments, values less than 500us seem to be unstable
// likewise, although theoretically a mains cycle (in the UK) is 10ms, 10,000us...
// values greater than 9000us seem to cause instability so I've clipped boundary
// between 5-90 for delay factor, corresponding to .5ms - 9ms
// defaults until EEPROM is read
var delayFactor = 90
var delayUs: UInt32 = 9000
var enabled = false
// setup triac pin
pinMode(pin: triacPin, mode: OUTPUT)
func boolForUInt8(_ value: UInt8) -> Bool {
if value > 0 {
return true
} else {
return false
}
}
func uint8ForBool(_ value: Bool) -> UInt8 {
if value {
return 1
}
return 0
}
func i2cUpdate(register: UInt8, value: UInt8) {
if register == brightnessi2cRegister {
updateDelay(value)
} else if register == onOffi2cRegister {
updateEnabled(boolForUInt8(value))
}
}
func i2cRead(register: UInt8) -> UInt8 {
if register == brightnessi2cRegister {
return delayFactor
} else if register == onOffi2cRegister {
return uint8ForBool(enabled)
}
return 0
}
// the update function, calcs and storage
// the de
func updateDelay(_ newDelayFactorIn: UInt8) {
var newDelayFactor = newDelayFactorIn
if newDelayFactor > 90 {
newDelayFactor = 90
}
if newDelayFactor < 5 {
newDelayFactor = 5
}
delayFactor = newDelayFactor
delayUs = UInt32(newDelayFactor) &* 100
writeEEPROM(address: storedBrightnessLocation, value: newDelayFactor)
}
func updateEnabled(_ newEnabled: Bool) {
enabled = newEnabled
writeEEPROM(address: storedOnOffLocation, value: uint8ForBool(newEnabled))
}
// initialise brightness from EEPROM
updateDelay(readEEPROM(address: storedBrightnessLocation))
enabled = boolForUInt8(readEEPROM(address: storedOnOffLocation))
// the core of the program, a delayed triac fire a set time after zero cross
setupPin2InterruptCallback(edgeType: RISING_EDGE) {
setupTimerSingleShotInterruptCallback(microseconds: delayUs) {
digitalWrite(pin: triacPin, value: HIGH)
delay(microseconds: 200)
digitalWrite(pin: triacPin, value: LOW)
}
}
// Use I2C to communicate to the pi for remote control
i2cSlaveSetupRegisterReceiveCallback { register, value in
i2cUpdate(register: register, value: value)
}
i2cSlaveSetupRegisterSendCallback { register -> UInt8 in
return i2cRead(register: register)
}
setupI2CSlave(address: 0x23, activatePullups: false)
func incrementBrightness() {
updateDelay(delayFactor &+ 5)
}
func decrementBrightness() {
updateDelay(delayFactor &- 5)
}
func centerPinPressed() {
updateEnabled(!enabled)
}
while (true) {
checkRotaryEncoder(
pin1: rotaryPin1,
pin2: rotaryPin2,
centerPin: centerPin,
lastPinState: &lastPinState,
clockwise: incrementBrightness,
counterclockwise: decrementBrightness,
centerPinPressed: centerPinPressed)
}
| gpl-2.0 | ce40cd1ef8daa6908093aceaa8fb58e0 | 23.524476 | 85 | 0.7428 | 3.726886 | false | false | false | false |
lllyyy/LY | U17-master/U17/U17/Procedure/Home/ViewController/UVIPListViewController.swift | 1 | 5315 | //
// UVIPListViewController.swift
// U17
//
// Created by charles on 2017/10/23.
// Copyright © 2017年 None. All rights reserved.
//
import UIKit
class UVIPListViewController: UBaseViewController {
private var vipList = [ComicListModel]()
private lazy var collectionView: UICollectionView = {
let lt = UCollectionViewSectionBackgroundLayout()
lt.minimumInteritemSpacing = 5
lt.minimumLineSpacing = 10
let cw = UICollectionView(frame: CGRect.zero, collectionViewLayout: lt)
cw.backgroundColor = UIColor.background
cw.delegate = self
cw.dataSource = self
cw.alwaysBounceVertical = true
cw.register(cellType: UComicCCell.self)
cw.register(supplementaryViewType: UComicCHead.self, ofKind: UICollectionElementKindSectionHeader)
cw.register(supplementaryViewType: UComicCFoot.self, ofKind: UICollectionElementKindSectionFooter)
cw.uHead = URefreshHeader{ self.loadData() }
cw.uFoot = URefreshTipKissFooter(with: "VIP用户专享\nVIP用户可以免费阅读全部漫画哦~")
cw.uempty = UEmptyView { self.loadData() }
return cw
}()
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
private func loadData() {
ApiLoadingProvider.request(UApi.vipList, model: VipListModel.self) { (returnData) in
self.collectionView.uHead.endRefreshing()
self.collectionView.uempty?.allowShow = true
self.vipList = returnData?.newVipList ?? []
self.collectionView.reloadData()
}
}
override func configUI() {
view.addSubview(collectionView)
collectionView.snp.makeConstraints{ $0.edges.equalTo(self.view.usnp.edges) }
}
}
extension UVIPListViewController: UCollectionViewSectionBackgroundLayoutDelegateLayout, UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return vipList.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor {
return UIColor.white
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let comicList = vipList[section]
return comicList.comics?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
let head = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, for: indexPath, viewType: UComicCHead.self)
let comicList = vipList[indexPath.section]
head.iconView.kf.setImage(urlString: comicList.titleIconUrl)
head.titleLabel.text = comicList.itemTitle
head.moreButton.isHidden = !comicList.canMore
head.moreActionClosure { [weak self] in
let vc = UComicListViewController(argCon: comicList.argCon, argName: comicList.argName, argValue: comicList.argValue)
vc.title = comicList.itemTitle
self?.navigationController?.pushViewController(vc, animated: true)
}
return head
} else {
let foot = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, for: indexPath, viewType: UComicCFoot.self)
return foot
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
let comicList = vipList[section]
return comicList.itemTitle?.count ?? 0 > 0 ? CGSize(width: screenWidth, height: 44) : CGSize.zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return vipList.count - 1 != section ? CGSize(width: screenWidth, height: 10) : CGSize.zero
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: UComicCCell.self)
cell.style = .withTitle
let comicList = vipList[indexPath.section]
cell.model = comicList.comics?[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = floor(Double(screenWidth - 10.0) / 3.0)
return CGSize(width: width, height: 240)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let comicList = vipList[indexPath.section]
guard let model = comicList.comics?[indexPath.row] else { return }
let vc = UComicViewController(comicid: model.comicId)
navigationController?.pushViewController(vc, animated: true)
}
}
| mit | 5891db12eb340e0139f77781928d78b6 | 43.352941 | 170 | 0.694581 | 5.331313 | false | false | false | false |
ahoppen/swift | test/PlaygroundTransform/module_file_id.swift | 21 | 1018 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -whole-module-optimization -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/SilentPCMacroRuntime.swift %S/Inputs/PlaygroundsRuntime.swift
// RUN: %target-build-swift -Xfrontend -playground -o %t/test -I=%t %t/PlaygroundSupport.o %S/Inputs/PlaygroundModuleAndFileIDs.swift %t/main.swift
// RUN: %target-codesign %t/test
// RUN: %target-run %t/test | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -o %t/test2 -I=%t %t/PlaygroundSupport.o %S/Inputs/PlaygroundModuleAndFileIDs.swift %t/main.swift
// RUN: %target-codesign %t/test2
// RUN: %target-run %t/test2 | %FileCheck %s
// REQUIRES: executable_test
import PlaygroundSupport
var a = 2
var b = 3
a + b
// CHECK: [1:2] [{{.*}}] __builtin_log[a='2']
// CHECK-NEXT: [1:2] [{{.*}}] __builtin_log[b='3']
// CHECK-NEXT: [1:2] [{{.*}}] __builtin_log[='5']
| apache-2.0 | 75e557ef74e8fe7878d80b3f6c889e4c | 52.578947 | 255 | 0.694499 | 3.00295 | false | true | false | false |
soulfly/guinea-pig-smart-bot | node_modules/quickblox/samples/cordova/video_chat/plugins/cordova-plugin-iosrtc/src/PluginRTCDTMFSender.swift | 4 | 1481 | import Foundation
class PluginRTCDTMFSender : NSObject, RTCDTMFSenderDelegate {
var rtcDTMFSender: RTCDTMFSender?
var eventListener: ((data: NSDictionary) -> Void)?
/**
* Constructor for pc.createDTMFSender().
*/
init(
rtcPeerConnection: RTCPeerConnection,
track: RTCMediaStreamTrack,
eventListener: (data: NSDictionary) -> Void
) {
NSLog("PluginRTCDTMFSender#init()")
self.eventListener = eventListener
self.rtcDTMFSender = rtcPeerConnection.createDTMFSenderForTrack(track as? RTCAudioTrack)
if self.rtcDTMFSender == nil {
NSLog("PluginRTCDTMFSender#init() | rtcPeerConnection.createDTMFSenderForTrack() failed")
return
}
}
deinit {
NSLog("PluginRTCDTMFSender#deinit()")
}
func run() {
NSLog("PluginRTCDTMFSender#run()")
self.rtcDTMFSender!.delegate = self
}
func insertDTMF(tones: String, duration: Int, interToneGap: Int) {
NSLog("PluginRTCDTMFSender#insertDTMF()")
let result = self.rtcDTMFSender!.insertDTMF(tones, withDuration: duration, andInterToneGap: interToneGap)
if !result {
NSLog("PluginRTCDTMFSender#indertDTMF() | RTCDTMFSender#indertDTMF() failed")
}
}
/**
* Methods inherited from RTCDTMFSenderDelegate.
*/
func toneChange(tone: String) {
NSLog("PluginRTCDTMFSender | tone change [tone:%@]", tone)
if self.eventListener != nil {
self.eventListener!(data: [
"type": "tonechange",
"tone": tone
])
}
}
}
| apache-2.0 | 822da7007862b3e5cc19e4810a3810fb | 20.784615 | 107 | 0.685348 | 3.907652 | false | false | false | false |
prolificinteractive/NavigationControllerBlurTransition | Pod/Classes/UIView+Constraints.swift | 2 | 4311 | //Copyright (c) 2015 Prolific Interactive.
//
//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
private var installedConstraintsHandle: UInt8 = 0
internal extension UIView
{
var installedConstraints: [NSLayoutConstraint]? {
get {
return objc_getAssociatedObject(self, &installedConstraintsHandle) as? [NSLayoutConstraint]
} set {
objc_setAssociatedObject(self, &installedConstraintsHandle, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
func makeEdgesEqualTo(view: UIView)
{
self.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: self,
attribute: .Top,
relatedBy: .Equal,
toItem: view,
attribute: .Top,
multiplier: 1.0,
constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: self,
attribute: .Bottom,
relatedBy: .Equal,
toItem: view,
attribute: .Bottom,
multiplier: 1.0,
constant: 0.0)
let leadingConstraint = NSLayoutConstraint(item: self,
attribute: .Leading,
relatedBy: .Equal,
toItem: view,
attribute: .Leading,
multiplier: 1.0,
constant: 0.0)
let trailingConstraint = NSLayoutConstraint(item: self,
attribute: .Trailing,
relatedBy: .Equal,
toItem: view,
attribute: .Trailing,
multiplier: 1.0,
constant: 0.0)
let constraints = [topConstraint, bottomConstraint, leadingConstraint, trailingConstraint]
view.addConstraints(constraints)
self.installedConstraints = constraints
}
func makeConstraintsToRightOfView(view: UIView)
{
view.layoutIfNeeded()
self.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: self,
attribute: .Top,
relatedBy: .Equal,
toItem: view,
attribute: .Top,
multiplier: 1.0,
constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: self,
attribute: .Bottom,
relatedBy: .Equal,
toItem: view,
attribute: .Bottom,
multiplier: 1.0,
constant: 0.0)
let leadingConstraint = NSLayoutConstraint(item: self,
attribute: .Leading,
relatedBy: .Equal,
toItem: view,
attribute: .Leading,
multiplier: 1.0,
constant: CGRectGetWidth(view.frame))
let widthConstraint = NSLayoutConstraint(item: self,
attribute: .Width,
relatedBy: .Equal,
toItem: view,
attribute: .Width,
multiplier: 1.0,
constant: 0.0)
let constraints = [topConstraint, bottomConstraint, leadingConstraint, widthConstraint]
view.addConstraints(constraints)
self.installedConstraints = constraints
}
func removeInstalledConstraints()
{
guard let constraints = self.installedConstraints else {
return
}
NSLayoutConstraint.deactivateConstraints(constraints)
}
}
| mit | 211679489838210a9f41b563b450074a | 32.944882 | 107 | 0.632568 | 5.18149 | false | false | false | false |
ahoppen/swift | validation-test/stdlib/Dictionary.swift | 8 | 169983 | // RUN: %empty-directory(%t)
//
// RUN: %gyb %s -o %t/main.swift
// RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o
// RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift %t/main.swift -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -o %t/Dictionary -Xfrontend -disable-access-control
//
// RUN: %target-codesign %t/Dictionary && %line-directive %t/main.swift -- %target-run %t/Dictionary
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
#if _runtime(_ObjC)
import Foundation
import StdlibUnittestFoundationExtras
#endif
extension Dictionary {
func _rawIdentifier() -> Int {
return unsafeBitCast(self, to: Int.self)
}
}
// Check that the generic parameters are called 'Key' and 'Value'.
protocol TestProtocol1 {}
struct TestError: Error {}
extension Dictionary where Key : TestProtocol1, Value : TestProtocol1 {
var _keyValueAreTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension DictionaryIndex where Key : TestProtocol1, Value : TestProtocol1 {
var _keyValueAreTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension DictionaryIterator
where Key : TestProtocol1, Value : TestProtocol1 {
var _keyValueAreTestProtocol1: Bool {
fatalError("not implemented")
}
}
var DictionaryTestSuite = TestSuite("Dictionary")
DictionaryTestSuite.test("AssociatedTypes") {
typealias Collection = Dictionary<MinimalHashableValue, OpaqueValue<Int>>
expectCollectionAssociatedTypes(
collectionType: Collection.self,
iteratorType: DictionaryIterator<MinimalHashableValue, OpaqueValue<Int>>.self,
subSequenceType: Slice<Collection>.self,
indexType: DictionaryIndex<MinimalHashableValue, OpaqueValue<Int>>.self,
indicesType: DefaultIndices<Collection>.self)
}
DictionaryTestSuite.test("sizeof") {
var dict = [1: "meow", 2: "meow"]
#if arch(i386) || arch(arm) || arch(arm64_32)
expectEqual(4, MemoryLayout.size(ofValue: dict))
#else
expectEqual(8, MemoryLayout.size(ofValue: dict))
#endif
}
DictionaryTestSuite.test("Index.Hashable") {
let d = [1: "meow", 2: "meow", 3: "meow"]
let e = Dictionary(uniqueKeysWithValues: zip(d.indices, d))
expectEqual(d.count, e.count)
expectNotNil(e[d.startIndex])
}
DictionaryTestSuite.test("valueDestruction") {
var d1 = Dictionary<Int, TestValueTy>()
for i in 100...110 {
d1[i] = TestValueTy(i)
}
var d2 = Dictionary<TestKeyTy, TestValueTy>()
for i in 100...110 {
d2[TestKeyTy(i)] = TestValueTy(i)
}
}
DictionaryTestSuite.test("COW.Smoke") {
var d1 = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10)
let identity1 = d1._rawIdentifier()
d1[TestKeyTy(10)] = TestValueTy(1010)
d1[TestKeyTy(20)] = TestValueTy(1020)
d1[TestKeyTy(30)] = TestValueTy(1030)
var d2 = d1
_fixLifetime(d2)
assert(identity1 == d2._rawIdentifier())
d2[TestKeyTy(40)] = TestValueTy(2040)
assert(identity1 != d2._rawIdentifier())
d1[TestKeyTy(50)] = TestValueTy(1050)
assert(identity1 == d1._rawIdentifier())
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
func getCOWFastDictionary() -> Dictionary<Int, Int> {
var d = Dictionary<Int, Int>(minimumCapacity: 10)
d[10] = 1010
d[20] = 1020
d[30] = 1030
return d
}
func getCOWFastDictionaryWithCOWValues() -> Dictionary<Int, TestValueCOWTy> {
var d = Dictionary<Int, TestValueCOWTy>(minimumCapacity: 10)
d[10] = TestValueCOWTy(1010)
d[20] = TestValueCOWTy(1020)
d[30] = TestValueCOWTy(1030)
return d
}
func getCOWSlowDictionary() -> Dictionary<TestKeyTy, TestValueTy> {
var d = Dictionary<TestKeyTy, TestValueTy>(minimumCapacity: 10)
d[TestKeyTy(10)] = TestValueTy(1010)
d[TestKeyTy(20)] = TestValueTy(1020)
d[TestKeyTy(30)] = TestValueTy(1030)
return d
}
func getCOWSlowEquatableDictionary()
-> Dictionary<TestKeyTy, TestEquatableValueTy> {
var d = Dictionary<TestKeyTy, TestEquatableValueTy>(minimumCapacity: 10)
d[TestKeyTy(10)] = TestEquatableValueTy(1010)
d[TestKeyTy(20)] = TestEquatableValueTy(1020)
d[TestKeyTy(30)] = TestEquatableValueTy(1030)
return d
}
func expectUnique<T: AnyObject>(_ v: inout T) {
expectTrue(isKnownUniquelyReferenced(&v))
}
func expectUnique<T: AnyObject>(_ v: inout T?) {
guard v != nil else { return }
expectTrue(isKnownUniquelyReferenced(&v))
}
DictionaryTestSuite.test("COW.Fast.IndexesDontAffectUniquenessCheck") {
var d = getCOWFastDictionary()
let identity1 = d._rawIdentifier()
let startIndex = d.startIndex
let endIndex = d.endIndex
assert(startIndex != endIndex)
assert(startIndex < endIndex)
assert(startIndex <= endIndex)
assert(!(startIndex >= endIndex))
assert(!(startIndex > endIndex))
assert(identity1 == d._rawIdentifier())
d[40] = 2040
assert(identity1 == d._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("COW.Slow.IndexesDontAffectUniquenessCheck") {
var d = getCOWSlowDictionary()
let identity1 = d._rawIdentifier()
let startIndex = d.startIndex
let endIndex = d.endIndex
assert(startIndex != endIndex)
assert(startIndex < endIndex)
assert(startIndex <= endIndex)
assert(!(startIndex >= endIndex))
assert(!(startIndex > endIndex))
assert(identity1 == d._rawIdentifier())
d[TestKeyTy(40)] = TestValueTy(2040)
assert(identity1 == d._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("COW.Fast.SubscriptWithIndexDoesNotReallocate") {
let d = getCOWFastDictionary()
let identity1 = d._rawIdentifier()
let startIndex = d.startIndex
let empty = startIndex == d.endIndex
assert((d.startIndex < d.endIndex) == !empty)
assert(d.startIndex <= d.endIndex)
assert((d.startIndex >= d.endIndex) == empty)
assert(!(d.startIndex > d.endIndex))
assert(identity1 == d._rawIdentifier())
assert(d[startIndex].1 != 0)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithIndexDoesNotReallocate") {
let d = getCOWSlowDictionary()
let identity1 = d._rawIdentifier()
let startIndex = d.startIndex
let empty = startIndex == d.endIndex
assert((d.startIndex < d.endIndex) == !empty)
assert(d.startIndex <= d.endIndex)
assert((d.startIndex >= d.endIndex) == empty)
assert(!(d.startIndex > d.endIndex))
assert(identity1 == d._rawIdentifier())
assert(d[startIndex].1.value != 0)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("COW.Fast.SubscriptWithKeyDoesNotReallocate")
.code {
var d = getCOWFastDictionary()
let identity1 = d._rawIdentifier()
assert(d[10]! == 1010)
assert(identity1 == d._rawIdentifier())
// Insert a new key-value pair.
d[40] = 2040
assert(identity1 == d._rawIdentifier())
assert(d.count == 4)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 2040)
// Overwrite a value in existing binding.
d[10] = 2010
assert(identity1 == d._rawIdentifier())
assert(d.count == 4)
assert(d[10]! == 2010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 2040)
// Delete an existing key.
d[10] = nil
assert(identity1 == d._rawIdentifier())
assert(d.count == 3)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 2040)
// Try to delete a key that does not exist.
d[42] = nil
assert(identity1 == d._rawIdentifier())
assert(d.count == 3)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 2040)
do {
var d2: [MinimalHashableValue : OpaqueValue<Int>] = [:]
MinimalHashableValue.timesEqualEqualWasCalled = 0
MinimalHashableValue.timesHashIntoWasCalled = 0
expectNil(d2[MinimalHashableValue(42)])
// If the dictionary is empty, we shouldn't be computing the hash value of
// the provided key.
expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableValue.timesHashIntoWasCalled)
}
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeyDoesNotReallocate")
.code {
var d = getCOWSlowDictionary()
let identity1 = d._rawIdentifier()
assert(d[TestKeyTy(10)]!.value == 1010)
assert(identity1 == d._rawIdentifier())
// Insert a new key-value pair.
d[TestKeyTy(40)] = TestValueTy(2040)
assert(identity1 == d._rawIdentifier())
assert(d.count == 4)
assert(d[TestKeyTy(10)]!.value == 1010)
assert(d[TestKeyTy(20)]!.value == 1020)
assert(d[TestKeyTy(30)]!.value == 1030)
assert(d[TestKeyTy(40)]!.value == 2040)
// Overwrite a value in existing binding.
d[TestKeyTy(10)] = TestValueTy(2010)
assert(identity1 == d._rawIdentifier())
assert(d.count == 4)
assert(d[TestKeyTy(10)]!.value == 2010)
assert(d[TestKeyTy(20)]!.value == 1020)
assert(d[TestKeyTy(30)]!.value == 1030)
assert(d[TestKeyTy(40)]!.value == 2040)
// Delete an existing key.
d[TestKeyTy(10)] = nil
assert(identity1 == d._rawIdentifier())
assert(d.count == 3)
assert(d[TestKeyTy(20)]!.value == 1020)
assert(d[TestKeyTy(30)]!.value == 1030)
assert(d[TestKeyTy(40)]!.value == 2040)
// Try to delete a key that does not exist.
d[TestKeyTy(42)] = nil
assert(identity1 == d._rawIdentifier())
assert(d.count == 3)
assert(d[TestKeyTy(20)]!.value == 1020)
assert(d[TestKeyTy(30)]!.value == 1030)
assert(d[TestKeyTy(40)]!.value == 2040)
do {
var d2: [MinimalHashableClass : OpaqueValue<Int>] = [:]
MinimalHashableClass.timesEqualEqualWasCalled = 0
MinimalHashableClass.timesHashIntoWasCalled = 0
expectNil(d2[MinimalHashableClass(42)])
// If the dictionary is empty, we shouldn't be computing the hash value of
// the provided key.
expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableClass.timesHashIntoWasCalled)
}
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKey.Uniqueness") {
var d = getCOWSlowEquatableDictionary()
expectUnique(&d[TestKeyTy(20)])
}
DictionaryTestSuite.test("COW.Fast.UpdateValueForKeyDoesNotReallocate") {
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
// Insert a new key-value pair.
assert(d1.updateValue(2040, forKey: 40) == .none)
assert(identity1 == d1._rawIdentifier())
assert(d1[40]! == 2040)
// Overwrite a value in existing binding.
assert(d1.updateValue(2010, forKey: 10)! == 1010)
assert(identity1 == d1._rawIdentifier())
assert(d1[10]! == 2010)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Insert a new key-value pair.
d2.updateValue(2040, forKey: 40)
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d1[40] == .none)
assert(d2.count == 4)
assert(d2[10]! == 1010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
assert(d2[40]! == 2040)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Overwrite a value in existing binding.
d2.updateValue(2010, forKey: 10)
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d2.count == 3)
assert(d2[10]! == 2010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Slow.UpdateValueForKeyDoesNotReallocate") {
do {
var d1 = getCOWSlowDictionary()
let identity1 = d1._rawIdentifier()
// Insert a new key-value pair.
assert(d1.updateValue(TestValueTy(2040), forKey: TestKeyTy(40)) == nil)
assert(identity1 == d1._rawIdentifier())
assert(d1.count == 4)
assert(d1[TestKeyTy(40)]!.value == 2040)
// Overwrite a value in existing binding.
assert(d1.updateValue(TestValueTy(2010), forKey: TestKeyTy(10))!.value == 1010)
assert(identity1 == d1._rawIdentifier())
assert(d1.count == 4)
assert(d1[TestKeyTy(10)]!.value == 2010)
}
do {
var d1 = getCOWSlowDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Insert a new key-value pair.
d2.updateValue(TestValueTy(2040), forKey: TestKeyTy(40))
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
assert(d1[TestKeyTy(20)]!.value == 1020)
assert(d1[TestKeyTy(30)]!.value == 1030)
assert(d1[TestKeyTy(40)] == nil)
assert(d2.count == 4)
assert(d2[TestKeyTy(10)]!.value == 1010)
assert(d2[TestKeyTy(20)]!.value == 1020)
assert(d2[TestKeyTy(30)]!.value == 1030)
assert(d2[TestKeyTy(40)]!.value == 2040)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWSlowDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Overwrite a value in existing binding.
d2.updateValue(TestValueTy(2010), forKey: TestKeyTy(10))
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
assert(d1[TestKeyTy(20)]!.value == 1020)
assert(d1[TestKeyTy(30)]!.value == 1030)
assert(d2.count == 3)
assert(d2[TestKeyTy(10)]!.value == 2010)
assert(d2[TestKeyTy(20)]!.value == 1020)
assert(d2[TestKeyTy(30)]!.value == 1030)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Fast.MergeSequenceDoesNotReallocate")
.code {
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
// Merge some new values.
d1.merge([(40, 2040), (50, 2050)]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(d1.count == 5)
assert(d1[50]! == 2050)
// Merge and overwrite some existing values.
d1.merge([(10, 2010), (60, 2060)]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(d1.count == 6)
assert(d1[10]! == 2010)
assert(d1[60]! == 2060)
// Merge, keeping existing values.
d1.merge([(30, 2030), (70, 2070)]) { x, _ in x }
assert(identity1 == d1._rawIdentifier())
assert(d1.count == 7)
assert(d1[30]! == 1030)
assert(d1[70]! == 2070)
let d2 = d1.merging([(40, 3040), (80, 3080)]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d2.count == 8)
assert(d2[40]! == 3040)
assert(d2[80]! == 3080)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Merge some new values.
d2.merge([(40, 2040), (50, 2050)]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d1[40] == nil)
assert(d2.count == 5)
assert(d2[10]! == 1010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
assert(d2[40]! == 2040)
assert(d2[50]! == 2050)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Merge and overwrite some existing values.
d2.merge([(10, 2010)]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d2.count == 3)
assert(d2[10]! == 2010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Merge, keeping existing values.
d2.merge([(10, 2010)]) { x, _ in x }
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d2.count == 3)
assert(d2[10]! == 1010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Fast.MergeDictionaryDoesNotReallocate")
.code {
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
// Merge some new values.
d1.merge([40: 2040, 50: 2050]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(d1.count == 5)
assert(d1[50]! == 2050)
// Merge and overwrite some existing values.
d1.merge([10: 2010, 60: 2060]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(d1.count == 6)
assert(d1[10]! == 2010)
assert(d1[60]! == 2060)
// Merge, keeping existing values.
d1.merge([30: 2030, 70: 2070]) { x, _ in x }
assert(identity1 == d1._rawIdentifier())
assert(d1.count == 7)
assert(d1[30]! == 1030)
assert(d1[70]! == 2070)
let d2 = d1.merging([40: 3040, 80: 3080]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d2.count == 8)
assert(d2[40]! == 3040)
assert(d2[80]! == 3080)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Merge some new values.
d2.merge([40: 2040, 50: 2050]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d1[40] == nil)
assert(d2.count == 5)
assert(d2[10]! == 1010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
assert(d2[40]! == 2040)
assert(d2[50]! == 2050)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Merge and overwrite some existing values.
d2.merge([10: 2010]) { _, y in y }
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d2.count == 3)
assert(d2[10]! == 2010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Merge, keeping existing values.
d2.merge([10: 2010]) { x, _ in x }
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d1[20]! == 1020)
assert(d1[30]! == 1030)
assert(d2.count == 3)
assert(d2[10]! == 1010)
assert(d2[20]! == 1020)
assert(d2[30]! == 1030)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("Merge.ThrowingIsSafe") {
var d: [TestKeyTy: TestValueTy] = [
TestKeyTy(10): TestValueTy(1),
TestKeyTy(20): TestValueTy(2),
TestKeyTy(30): TestValueTy(3),
]
let d2: [TestKeyTy: TestValueTy] = [
TestKeyTy(40): TestValueTy(4),
TestKeyTy(50): TestValueTy(5),
TestKeyTy(10): TestValueTy(1),
]
struct TE: Error {}
do {
// Throwing must not leave the dictionary in an inconsistent state.
try d.merge(d2) { v1, v2 in throw TE() }
expectTrue(false, "merge did not throw")
} catch {
expectTrue(error is TE)
}
}
DictionaryTestSuite.test("COW.Fast.DefaultedSubscriptDoesNotReallocate") {
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
// No mutation on access.
assert(d1[10, default: 0] + 1 == 1011)
assert(d1[40, default: 0] + 1 == 1)
assert(identity1 == d1._rawIdentifier())
assert(d1[10]! == 1010)
// Increment existing in place.
d1[10, default: 0] += 1
assert(identity1 == d1._rawIdentifier())
assert(d1[10]! == 1011)
// Add incremented default value.
d1[40, default: 0] += 1
assert(identity1 == d1._rawIdentifier())
assert(d1[40]! == 1)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// No mutation on access.
assert(d2[10, default: 0] + 1 == 1011)
assert(d2[40, default: 0] + 1 == 1)
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Increment existing in place.
d2[10, default: 0] += 1
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1[10]! == 1010)
assert(d2[10]! == 1011)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
// Add incremented default value.
d2[40, default: 0] += 1
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d1[40] == nil)
assert(d2[40]! == 1)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Fast.DefaultedSubscriptDoesNotCopyValue") {
do {
var d = getCOWFastDictionaryWithCOWValues()
let identityValue30 = d[30]!.baseAddress
// Increment the value without having to reallocate the underlying Base
// instance, as uniquely referenced.
d[30, default: TestValueCOWTy()].value += 1
assert(identityValue30 == d[30]!.baseAddress)
assert(d[30]!.value == 1031)
let value40 = TestValueCOWTy()
let identityValue40 = value40.baseAddress
// Increment the value, reallocating the underlying Base, as not uniquely
// referenced.
d[40, default: value40].value += 1
assert(identityValue40 != d[40]!.baseAddress)
assert(d[40]!.value == 1)
// Keep variables alive.
_fixLifetime(d)
_fixLifetime(value40)
}
}
DictionaryTestSuite.test("COW.Slow.DefaultedSubscript.Uniqueness") {
var d = getCOWSlowEquatableDictionary()
expectUnique(&d[TestKeyTy(20), default: TestEquatableValueTy(0)])
expectUnique(&d[TestKeyTy(40), default: TestEquatableValueTy(0)])
}
func bumpValue(_ value: inout TestEquatableValueTy) {
value = TestEquatableValueTy(value.value + 1)
}
func bumpValueAndThrow(_ value: inout TestEquatableValueTy) throws {
value = TestEquatableValueTy(value.value + 1)
throw TestError()
}
DictionaryTestSuite.test("COW.Slow.DefaultedSubscript.Insertion.modify") {
var d = getCOWSlowEquatableDictionary()
bumpValue(&d[TestKeyTy(40), default: TestEquatableValueTy(1040)])
expectEqual(TestEquatableValueTy(1041), d[TestKeyTy(40)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.DefaultedSubscript.Mutation.modify") {
var d = getCOWSlowEquatableDictionary()
bumpValue(&d[TestKeyTy(10), default: TestEquatableValueTy(2000)])
expectEqual(TestEquatableValueTy(1011), d[TestKeyTy(10)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.DefaultedSubscript.Insertion.modifyThrow") {
var d = getCOWSlowEquatableDictionary()
do {
try bumpValueAndThrow(
&d[TestKeyTy(40), default: TestEquatableValueTy(1040)])
expectTrue(false, "Did not throw")
} catch {
expectTrue(error is TestError)
}
expectEqual(TestEquatableValueTy(1041), d[TestKeyTy(40)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.DefaultedSubscript.Mutation.modifyThrow") {
var d = getCOWSlowEquatableDictionary()
do {
try bumpValueAndThrow(
&d[TestKeyTy(10), default: TestEquatableValueTy(2000)])
expectTrue(false, "Did not throw")
} catch {
expectTrue(error is TestError)
}
expectEqual(TestEquatableValueTy(1011), d[TestKeyTy(10)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Fast.IndexForKeyDoesNotReallocate") {
let d = getCOWFastDictionary()
let identity1 = d._rawIdentifier()
// Find an existing key.
do {
let foundIndex1 = d.index(forKey: 10)!
assert(identity1 == d._rawIdentifier())
let foundIndex2 = d.index(forKey: 10)!
assert(foundIndex1 == foundIndex2)
assert(d[foundIndex1].0 == 10)
assert(d[foundIndex1].1 == 1010)
assert(identity1 == d._rawIdentifier())
}
// Try to find a key that is not present.
do {
let foundIndex1 = d.index(forKey: 1111)
assert(foundIndex1 == nil)
assert(identity1 == d._rawIdentifier())
}
do {
let d2: [MinimalHashableValue : OpaqueValue<Int>] = [:]
MinimalHashableValue.timesEqualEqualWasCalled = 0
MinimalHashableValue.timesHashIntoWasCalled = 0
expectNil(d2.index(forKey: MinimalHashableValue(42)))
// If the dictionary is empty, we shouldn't be computing the hash value of
// the provided key.
expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableValue.timesHashIntoWasCalled)
}
}
DictionaryTestSuite.test("COW.Slow.IndexForKeyDoesNotReallocate") {
let d = getCOWSlowDictionary()
let identity1 = d._rawIdentifier()
// Find an existing key.
do {
let foundIndex1 = d.index(forKey: TestKeyTy(10))!
assert(identity1 == d._rawIdentifier())
let foundIndex2 = d.index(forKey: TestKeyTy(10))!
assert(foundIndex1 == foundIndex2)
assert(d[foundIndex1].0 == TestKeyTy(10))
assert(d[foundIndex1].1.value == 1010)
assert(identity1 == d._rawIdentifier())
}
// Try to find a key that is not present.
do {
let foundIndex1 = d.index(forKey: TestKeyTy(1111))
assert(foundIndex1 == nil)
assert(identity1 == d._rawIdentifier())
}
do {
let d2: [MinimalHashableClass : OpaqueValue<Int>] = [:]
MinimalHashableClass.timesEqualEqualWasCalled = 0
MinimalHashableClass.timesHashIntoWasCalled = 0
expectNil(d2.index(forKey: MinimalHashableClass(42)))
// If the dictionary is empty, we shouldn't be computing the hash value of
// the provided key.
expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableClass.timesHashIntoWasCalled)
}
}
DictionaryTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate")
.code {
do {
var d = getCOWFastDictionary()
let identity1 = d._rawIdentifier()
let foundIndex1 = d.index(forKey: 10)!
assert(identity1 == d._rawIdentifier())
assert(d[foundIndex1].0 == 10)
assert(d[foundIndex1].1 == 1010)
let removed = d.remove(at: foundIndex1)
assert(removed.0 == 10)
assert(removed.1 == 1010)
assert(identity1 == d._rawIdentifier())
assert(d.index(forKey: 10) == nil)
}
do {
let d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
let foundIndex1 = d2.index(forKey: 10)!
assert(d2[foundIndex1].0 == 10)
assert(d2[foundIndex1].1 == 1010)
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
let removed = d2.remove(at: foundIndex1)
assert(removed.0 == 10)
assert(removed.1 == 1010)
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d2.index(forKey: 10) == nil)
}
}
DictionaryTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate")
.code {
do {
var d = getCOWSlowDictionary()
let identity1 = d._rawIdentifier()
let foundIndex1 = d.index(forKey: TestKeyTy(10))!
assert(identity1 == d._rawIdentifier())
assert(d[foundIndex1].0 == TestKeyTy(10))
assert(d[foundIndex1].1.value == 1010)
let removed = d.remove(at: foundIndex1)
assert(removed.0 == TestKeyTy(10))
assert(removed.1.value == 1010)
assert(identity1 == d._rawIdentifier())
assert(d.index(forKey: TestKeyTy(10)) == nil)
}
do {
let d1 = getCOWSlowDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
let foundIndex1 = d2.index(forKey: TestKeyTy(10))!
assert(d2[foundIndex1].0 == TestKeyTy(10))
assert(d2[foundIndex1].1.value == 1010)
let removed = d2.remove(at: foundIndex1)
assert(removed.0 == TestKeyTy(10))
assert(removed.1.value == 1010)
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
assert(d2.index(forKey: TestKeyTy(10)) == nil)
}
}
DictionaryTestSuite.test("COW.Fast.RemoveValueForKeyDoesNotReallocate")
.code {
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var deleted = d1.removeValue(forKey: 0)
assert(deleted == nil)
assert(identity1 == d1._rawIdentifier())
deleted = d1.removeValue(forKey: 10)
assert(deleted! == 1010)
assert(identity1 == d1._rawIdentifier())
// Keep variables alive.
_fixLifetime(d1)
}
do {
let d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
var deleted = d2.removeValue(forKey: 0)
assert(deleted == nil)
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
deleted = d2.removeValue(forKey: 10)
assert(deleted! == 1010)
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Slow.RemoveValueForKeyDoesNotReallocate")
.code {
do {
var d1 = getCOWSlowDictionary()
let identity1 = d1._rawIdentifier()
var deleted = d1.removeValue(forKey: TestKeyTy(0))
assert(deleted == nil)
assert(identity1 == d1._rawIdentifier())
deleted = d1.removeValue(forKey: TestKeyTy(10))
assert(deleted!.value == 1010)
assert(identity1 == d1._rawIdentifier())
// Keep variables alive.
_fixLifetime(d1)
}
do {
let d1 = getCOWSlowDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
var deleted = d2.removeValue(forKey: TestKeyTy(0))
assert(deleted == nil)
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
deleted = d2.removeValue(forKey: TestKeyTy(10))
assert(deleted!.value == 1010)
assert(identity1 == d1._rawIdentifier())
assert(identity1 != d2._rawIdentifier())
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Fast.RemoveAllDoesNotReallocate") {
do {
var d = getCOWFastDictionary()
let originalCapacity = d.capacity
assert(d.count == 3)
assert(d[10]! == 1010)
d.removeAll()
// We cannot assert that identity changed, since the new buffer of smaller
// size can be allocated at the same address as the old one.
let identity1 = d._rawIdentifier()
assert(d.capacity < originalCapacity)
assert(d.count == 0)
assert(d[10] == nil)
d.removeAll()
assert(identity1 == d._rawIdentifier())
assert(d.count == 0)
assert(d[10] == nil)
}
do {
var d = getCOWFastDictionary()
let identity1 = d._rawIdentifier()
let originalCapacity = d.capacity
assert(d.count == 3)
assert(d[10]! == 1010)
d.removeAll(keepingCapacity: true)
assert(identity1 == d._rawIdentifier())
assert(d.capacity == originalCapacity)
assert(d.count == 0)
assert(d[10] == nil)
d.removeAll(keepingCapacity: true)
assert(identity1 == d._rawIdentifier())
assert(d.capacity == originalCapacity)
assert(d.count == 0)
assert(d[10] == nil)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
assert(d1.count == 3)
assert(d1[10]! == 1010)
var d2 = d1
d2.removeAll()
let identity2 = d2._rawIdentifier()
assert(identity1 == d1._rawIdentifier())
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d2.count == 0)
assert(d2[10] == nil)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
let originalCapacity = d1.capacity
assert(d1.count == 3)
assert(d1[10] == 1010)
var d2 = d1
d2.removeAll(keepingCapacity: true)
let identity2 = d2._rawIdentifier()
assert(identity1 == d1._rawIdentifier())
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[10]! == 1010)
assert(d2.capacity == originalCapacity)
assert(d2.count == 0)
assert(d2[10] == nil)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Slow.RemoveAllDoesNotReallocate") {
do {
var d = getCOWSlowDictionary()
let originalCapacity = d.capacity
assert(d.count == 3)
assert(d[TestKeyTy(10)]!.value == 1010)
d.removeAll()
// We cannot assert that identity changed, since the new buffer of smaller
// size can be allocated at the same address as the old one.
let identity1 = d._rawIdentifier()
assert(d.capacity < originalCapacity)
assert(d.count == 0)
assert(d[TestKeyTy(10)] == nil)
d.removeAll()
assert(identity1 == d._rawIdentifier())
assert(d.count == 0)
assert(d[TestKeyTy(10)] == nil)
}
do {
var d = getCOWSlowDictionary()
let identity1 = d._rawIdentifier()
let originalCapacity = d.capacity
assert(d.count == 3)
assert(d[TestKeyTy(10)]!.value == 1010)
d.removeAll(keepingCapacity: true)
assert(identity1 == d._rawIdentifier())
assert(d.capacity == originalCapacity)
assert(d.count == 0)
assert(d[TestKeyTy(10)] == nil)
d.removeAll(keepingCapacity: true)
assert(identity1 == d._rawIdentifier())
assert(d.capacity == originalCapacity)
assert(d.count == 0)
assert(d[TestKeyTy(10)] == nil)
}
do {
var d1 = getCOWSlowDictionary()
let identity1 = d1._rawIdentifier()
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
var d2 = d1
d2.removeAll()
let identity2 = d2._rawIdentifier()
assert(identity1 == d1._rawIdentifier())
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
assert(d2.count == 0)
assert(d2[TestKeyTy(10)] == nil)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
do {
var d1 = getCOWSlowDictionary()
let identity1 = d1._rawIdentifier()
let originalCapacity = d1.capacity
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
var d2 = d1
d2.removeAll(keepingCapacity: true)
let identity2 = d2._rawIdentifier()
assert(identity1 == d1._rawIdentifier())
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[TestKeyTy(10)]!.value == 1010)
assert(d2.capacity == originalCapacity)
assert(d2.count == 0)
assert(d2[TestKeyTy(10)] == nil)
// Keep variables alive.
_fixLifetime(d1)
_fixLifetime(d2)
}
}
DictionaryTestSuite.test("COW.Fast.CountDoesNotReallocate") {
let d = getCOWFastDictionary()
let identity1 = d._rawIdentifier()
assert(d.count == 3)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("COW.Slow.CountDoesNotReallocate") {
let d = getCOWSlowDictionary()
let identity1 = d._rawIdentifier()
assert(d.count == 3)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("COW.Fast.GenerateDoesNotReallocate") {
let d = getCOWFastDictionary()
let identity1 = d._rawIdentifier()
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
pairs += [(key, value)]
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("COW.Slow.GenerateDoesNotReallocate") {
let d = getCOWSlowDictionary()
let identity1 = d._rawIdentifier()
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
pairs += [(key.value, value.value)]
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("COW.Fast.EqualityTestDoesNotReallocate") {
let d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
var d2 = getCOWFastDictionary()
let identity2 = d2._rawIdentifier()
assert(d1 == d2)
assert(identity1 == d1._rawIdentifier())
assert(identity2 == d2._rawIdentifier())
d2[40] = 2040
assert(d1 != d2)
assert(identity1 == d1._rawIdentifier())
assert(identity2 == d2._rawIdentifier())
}
DictionaryTestSuite.test("COW.Slow.EqualityTestDoesNotReallocate") {
let d1 = getCOWSlowEquatableDictionary()
let identity1 = d1._rawIdentifier()
var d2 = getCOWSlowEquatableDictionary()
let identity2 = d2._rawIdentifier()
assert(d1 == d2)
assert(identity1 == d1._rawIdentifier())
assert(identity2 == d2._rawIdentifier())
d2[TestKeyTy(40)] = TestEquatableValueTy(2040)
assert(d1 != d2)
assert(identity1 == d1._rawIdentifier())
assert(identity2 == d2._rawIdentifier())
}
//===---
// Keys and Values collection tests.
//===---
DictionaryTestSuite.test("COW.Fast.Values.AccessDoesNotReallocate") {
var d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
assert([1010, 1020, 1030] == d1.values.sorted())
assert(identity1 == d1._rawIdentifier())
var d2 = d1
assert(identity1 == d2._rawIdentifier())
let i = d2.index(forKey: 10)!
assert(d1.values[i] == 1010)
assert(d1[i] == (10, 1010))
d2.values[i] += 1
assert(d2.values[i] == 1011)
assert(d2[10]! == 1011)
assert(identity1 != d2._rawIdentifier())
assert(d1[10]! == 1010)
assert(identity1 == d1._rawIdentifier())
checkCollection(
Array(d1.values),
d1.values,
stackTrace: SourceLocStack())
{ $0 == $1 }
}
DictionaryTestSuite.test("COW.Slow.Values.Modify") {
var d1 = getCOWSlowEquatableDictionary()
var d2: [TestKeyTy: TestEquatableValueTy] = [
TestKeyTy(40): TestEquatableValueTy(1040),
TestKeyTy(50): TestEquatableValueTy(1050),
TestKeyTy(60): TestEquatableValueTy(1060),
]
d1.values = d2.values
expectEqual(d1, d2)
expectNil(d1[TestKeyTy(10)])
expectNil(d1[TestKeyTy(20)])
expectNil(d1[TestKeyTy(30)])
expectEqual(TestEquatableValueTy(1040), d1[TestKeyTy(40)])
expectEqual(TestEquatableValueTy(1050), d1[TestKeyTy(50)])
expectEqual(TestEquatableValueTy(1060), d1[TestKeyTy(60)])
}
@inline(never)
func replaceValuesThenThrow<K: Hashable, V>(
_ v: inout Dictionary<K, V>.Values,
with v2: Dictionary<K, V>.Values
) throws {
v = v2
throw TestError()
}
DictionaryTestSuite.test("COW.Slow.Values.ModifyThrow") {
var d1 = getCOWSlowEquatableDictionary()
var d2: [TestKeyTy: TestEquatableValueTy] = [
TestKeyTy(40): TestEquatableValueTy(1040),
TestKeyTy(50): TestEquatableValueTy(1050),
TestKeyTy(60): TestEquatableValueTy(1060),
]
do {
try replaceValuesThenThrow(&d1.values, with: d2.values)
expectTrue(false, "Did not throw")
} catch {
expectTrue(error is TestError)
}
expectEqual(d1, d2)
expectNil(d1[TestKeyTy(10)])
expectNil(d1[TestKeyTy(20)])
expectNil(d1[TestKeyTy(30)])
expectEqual(TestEquatableValueTy(1040), d1[TestKeyTy(40)])
expectEqual(TestEquatableValueTy(1050), d1[TestKeyTy(50)])
expectEqual(TestEquatableValueTy(1060), d1[TestKeyTy(60)])
}
DictionaryTestSuite.test("COW.Slow.Values.Uniqueness") {
var d = getCOWSlowEquatableDictionary()
let i = d.index(forKey: TestKeyTy(20))!
expectUnique(&d.values[i])
}
DictionaryTestSuite.test("COW.Fast.Keys.AccessDoesNotReallocate") {
let d1 = getCOWFastDictionary()
let identity1 = d1._rawIdentifier()
assert([10, 20, 30] == d1.keys.sorted())
let i = d1.index(forKey: 10)!
assert(d1.keys[i] == 10)
assert(d1[i] == (10, 1010))
assert(identity1 == d1._rawIdentifier())
checkCollection(
Array(d1.keys),
d1.keys,
stackTrace: SourceLocStack())
{ $0 == $1 }
do {
var d2: [MinimalHashableValue : Int] = [
MinimalHashableValue(10): 1010,
MinimalHashableValue(20): 1020,
MinimalHashableValue(30): 1030,
MinimalHashableValue(40): 1040,
MinimalHashableValue(50): 1050,
MinimalHashableValue(60): 1060,
MinimalHashableValue(70): 1070,
MinimalHashableValue(80): 1080,
MinimalHashableValue(90): 1090,
]
// Make collisions less likely
d2.reserveCapacity(1000)
// Find the last key in the dictionary
var lastKey: MinimalHashableValue = d2.first!.key
for i in d2.indices { lastKey = d2[i].key }
// firstIndex(where:) - linear search
MinimalHashableValue.timesEqualEqualWasCalled = 0
let j = d2.firstIndex(where: { (k, _) in k == lastKey })!
expectGE(MinimalHashableValue.timesEqualEqualWasCalled, 8)
// index(forKey:) - O(1) bucket + linear search
MinimalHashableValue.timesEqualEqualWasCalled = 0
let k = d2.index(forKey: lastKey)!
expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4)
// keys.firstIndex(of:) - O(1) bucket + linear search
MinimalHashableValue.timesEqualEqualWasCalled = 0
let l = d2.keys.firstIndex(of: lastKey)!
expectLE(MinimalHashableValue.timesEqualEqualWasCalled, 4)
expectEqual(j, k)
expectEqual(k, l)
}
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Insertion") {
var d = getCOWSlowEquatableDictionary()
d[TestKeyTy(40)] = TestEquatableValueTy(1040)
expectEqual(TestEquatableValueTy(1040), d[TestKeyTy(40)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Mutation") {
var d = getCOWSlowEquatableDictionary()
d[TestKeyTy(10)] = TestEquatableValueTy(2010)
expectEqual(TestEquatableValueTy(2010), d[TestKeyTy(10)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Removal") {
var d = getCOWSlowEquatableDictionary()
d[TestKeyTy(10)] = nil
expectNil(d[TestKeyTy(10)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Noop") {
var d = getCOWSlowEquatableDictionary()
d[TestKeyTy(40)] = nil
expectNil(d[TestKeyTy(40)])
// Note: Leak tests are done in tearDown.
}
extension Optional {
@inline(never)
mutating func setWrapped(to value: Wrapped) {
self = .some(value)
}
@inline(never)
mutating func setWrappedThenThrow(to value: Wrapped) throws {
self = .some(value)
throw TestError()
}
@inline(never)
mutating func clear() {
self = .none
}
@inline(never)
mutating func clearThenThrow() throws {
self = .none
throw TestError()
}
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Insertion.modify") {
var d = getCOWSlowEquatableDictionary()
d[TestKeyTy(40)].setWrapped(to: TestEquatableValueTy(1040))
expectEqual(TestEquatableValueTy(1040), d[TestKeyTy(40)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Mutation.modify") {
var d = getCOWSlowEquatableDictionary()
d[TestKeyTy(10)].setWrapped(to: TestEquatableValueTy(2010))
expectEqual(TestEquatableValueTy(2010), d[TestKeyTy(10)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Removal.modify") {
var d = getCOWSlowEquatableDictionary()
d[TestKeyTy(10)].clear()
expectNil(d[TestKeyTy(10)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Noop.modify") {
var d = getCOWSlowEquatableDictionary()
d[TestKeyTy(40)].clear()
expectNil(d[TestKeyTy(40)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Insertion.modifyThrow") {
var d = getCOWSlowEquatableDictionary()
do {
try d[TestKeyTy(40)].setWrappedThenThrow(to: TestEquatableValueTy(1040))
expectTrue(false, "Did not throw")
} catch {
expectTrue(error is TestError)
}
expectEqual(TestEquatableValueTy(1040), d[TestKeyTy(40)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Mutation.modifyThrow") {
var d = getCOWSlowEquatableDictionary()
do {
try d[TestKeyTy(10)].setWrappedThenThrow(to: TestEquatableValueTy(2010))
expectTrue(false, "Did not throw")
} catch {
expectTrue(error is TestError)
}
expectEqual(TestEquatableValueTy(2010), d[TestKeyTy(10)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Removal.modifyThrow") {
var d = getCOWSlowEquatableDictionary()
do {
try d[TestKeyTy(10)].clearThenThrow()
expectTrue(false, "Did not throw")
} catch {
expectTrue(error is TestError)
}
expectNil(d[TestKeyTy(10)])
// Note: Leak tests are done in tearDown.
}
DictionaryTestSuite.test("COW.Slow.SubscriptWithKeys.Noop.modifyThrow") {
var d = getCOWSlowEquatableDictionary()
do {
try d[TestKeyTy(40)].clearThenThrow()
expectTrue(false, "Did not throw")
} catch {
expectTrue(error is TestError)
}
expectNil(d[TestKeyTy(40)])
// Note: Leak tests are done in tearDown.
}
//===---
// Native dictionary tests.
//===---
func helperDeleteThree(
_ k1: RawTestKeyTy,
_ k2: RawTestKeyTy,
_ k3: RawTestKeyTy
) {
var d1 = Dictionary<RawTestKeyTy, TestValueTy>(minimumCapacity: 10)
d1[k1] = TestValueTy(1010)
d1[k2] = TestValueTy(1020)
d1[k3] = TestValueTy(1030)
assert(d1[k1]?.value == 1010)
assert(d1[k2]?.value == 1020)
assert(d1[k3]?.value == 1030)
d1[k1] = nil
assert(d1[k1]?.value == nil)
assert(d1[k2]?.value == 1020)
assert(d1[k3]?.value == 1030)
d1[k2] = nil
assert(d1[k1]?.value == nil)
assert(d1[k2]?.value == nil)
assert(d1[k3]?.value == 1030)
d1[k3] = nil
assert(d1[k1]?.value == nil)
assert(d1[k2]?.value == nil)
assert(d1[k3]?.value == nil)
assert(d1.count == 0)
}
DictionaryTestSuite.test("deleteChainCollision") {
let k1 = RawTestKeyTy(value: 10, hashValue: 0)
let k2 = RawTestKeyTy(value: 20, hashValue: 0)
let k3 = RawTestKeyTy(value: 30, hashValue: 0)
helperDeleteThree(k1, k2, k3)
}
DictionaryTestSuite.test("deleteChainNoCollision") {
let k1 = RawTestKeyTy(value: 10, hashValue: 0)
let k2 = RawTestKeyTy(value: 20, hashValue: 1)
let k3 = RawTestKeyTy(value: 30, hashValue: 2)
helperDeleteThree(k1, k2, k3)
}
DictionaryTestSuite.test("deleteChainCollision2") {
let k1_0 = RawTestKeyTy(value: 10, hashValue: 0)
let k2_0 = RawTestKeyTy(value: 20, hashValue: 0)
let k3_2 = RawTestKeyTy(value: 30, hashValue: 2)
let k4_0 = RawTestKeyTy(value: 40, hashValue: 0)
let k5_2 = RawTestKeyTy(value: 50, hashValue: 2)
let k6_0 = RawTestKeyTy(value: 60, hashValue: 0)
var d = Dictionary<RawTestKeyTy, TestValueTy>(minimumCapacity: 10)
d[k1_0] = TestValueTy(1010) // in bucket 0
d[k2_0] = TestValueTy(1020) // in bucket 1
d[k3_2] = TestValueTy(1030) // in bucket 2
d[k4_0] = TestValueTy(1040) // in bucket 3
d[k5_2] = TestValueTy(1050) // in bucket 4
d[k6_0] = TestValueTy(1060) // in bucket 5
d[k3_2] = nil
assert(d[k1_0]!.value == 1010)
assert(d[k2_0]!.value == 1020)
assert(d[k3_2] == nil)
assert(d[k4_0]!.value == 1040)
assert(d[k5_2]!.value == 1050)
assert(d[k6_0]!.value == 1060)
}
DictionaryTestSuite.test("deleteChainCollisionRandomized") {
let seed = UInt64.random(in: .min ... .max)
var generator = LinearCongruentialGenerator(seed: seed)
print("using LinearCongruentialGenerator(seed: \(seed))")
func check(_ d: Dictionary<RawTestKeyTy, TestValueTy>) {
let keys = Array(d.keys)
for i in 0..<keys.count {
for j in 0..<i {
expectNotEqual(keys[i], keys[j])
}
}
for k in keys {
expectNotNil(d[k])
}
}
let collisionChains = Int.random(in: 1...8, using: &generator)
let chainOverlap = Int.random(in: 0...5, using: &generator)
let chainLength = 7
var knownKeys: [RawTestKeyTy] = []
func getKey(_ value: Int) -> RawTestKeyTy {
for k in knownKeys {
if k.value == value {
return k
}
}
let hashValue = Int.random(in: 0 ..< (chainLength - chainOverlap), using: &generator) * collisionChains
let k = RawTestKeyTy(value: value, hashValue: hashValue)
knownKeys += [k]
return k
}
var d = Dictionary<RawTestKeyTy, TestValueTy>(minimumCapacity: 30)
for _ in 1..<300 {
let key = getKey(Int.random(in: 0 ..< (collisionChains * chainLength), using: &generator))
if Int.random(in: 0 ..< (chainLength * 2), using: &generator) == 0 {
d[key] = nil
} else {
d[key] = TestValueTy(key.value * 10)
}
check(d)
}
}
DictionaryTestSuite.test("init(dictionaryLiteral:)") {
do {
var empty = Dictionary<Int, Int>()
assert(empty.count == 0)
assert(empty[1111] == nil)
}
do {
var d = Dictionary(dictionaryLiteral: (10, 1010))
assert(d.count == 1)
assert(d[10]! == 1010)
assert(d[1111] == nil)
}
do {
var d = Dictionary(dictionaryLiteral:
(10, 1010), (20, 1020))
assert(d.count == 2)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[1111] == nil)
}
do {
var d = Dictionary(dictionaryLiteral:
(10, 1010), (20, 1020), (30, 1030))
assert(d.count == 3)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[1111] == nil)
}
do {
var d = Dictionary(dictionaryLiteral:
(10, 1010), (20, 1020), (30, 1030), (40, 1040))
assert(d.count == 4)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
assert(d[40]! == 1040)
assert(d[1111] == nil)
}
do {
var d: Dictionary<Int, Int> = [ 10: 1010, 20: 1020, 30: 1030 ]
assert(d.count == 3)
assert(d[10]! == 1010)
assert(d[20]! == 1020)
assert(d[30]! == 1030)
}
}
DictionaryTestSuite.test("init(uniqueKeysWithValues:)") {
do {
var d = Dictionary(uniqueKeysWithValues: [(10, 1010), (20, 1020), (30, 1030)])
expectEqual(d.count, 3)
expectEqual(d[10]!, 1010)
expectEqual(d[20]!, 1020)
expectEqual(d[30]!, 1030)
expectNil(d[1111])
}
do {
var d = Dictionary<Int, Int>(uniqueKeysWithValues: EmptyCollection<(Int, Int)>())
expectEqual(d.count, 0)
expectNil(d[1111])
}
do {
expectCrashLater()
_ = Dictionary(uniqueKeysWithValues: [(10, 1010), (20, 1020), (10, 2010)])
}
}
DictionaryTestSuite.test("init(_:uniquingKeysWith:)") {
do {
let d = Dictionary(
[(10, 1010), (20, 1020), (30, 1030), (10, 2010)], uniquingKeysWith: min)
expectEqual(d.count, 3)
expectEqual(d[10]!, 1010)
expectEqual(d[20]!, 1020)
expectEqual(d[30]!, 1030)
expectNil(d[1111])
}
do {
let d = Dictionary(
[(10, 1010), (20, 1020), (30, 1030), (10, 2010)] as [(Int, Int)],
uniquingKeysWith: +)
expectEqual(d.count, 3)
expectEqual(d[10]!, 3020)
expectEqual(d[20]!, 1020)
expectEqual(d[30]!, 1030)
expectNil(d[1111])
}
do {
let d = Dictionary([(10, 1010), (20, 1020), (30, 1030), (10, 2010)]) {
(a, b) in Int("\(a)\(b)")!
}
expectEqual(d.count, 3)
expectEqual(d[10]!, 10102010)
expectEqual(d[20]!, 1020)
expectEqual(d[30]!, 1030)
expectNil(d[1111])
}
do {
let d = Dictionary([(10, 1010), (10, 2010), (10, 3010), (10, 4010)]) { $1 }
expectEqual(d.count, 1)
expectEqual(d[10]!, 4010)
expectNil(d[1111])
}
do {
let d = Dictionary(EmptyCollection<(Int, Int)>(), uniquingKeysWith: min)
expectEqual(d.count, 0)
expectNil(d[1111])
}
struct TE: Error {}
do {
// No duplicate keys, so no error thrown.
let d1 = try Dictionary([(10, 1), (20, 2), (30, 3)]) { (_,_) in throw TE() }
expectEqual(d1.count, 3)
// Duplicate keys, should throw error.
_ = try Dictionary([(10, 1), (10, 2)]) { (_,_) in throw TE() }
_ = assertionFailure()
} catch {
assert(error is TE)
}
}
DictionaryTestSuite.test("init(grouping:by:)") {
let r = 0..<10
let d1 = Dictionary(grouping: r, by: { $0 % 3 })
expectEqual(3, d1.count)
expectEqual([0, 3, 6, 9], d1[0]!)
expectEqual([1, 4, 7], d1[1]!)
expectEqual([2, 5, 8], d1[2]!)
let d2 = Dictionary(grouping: r, by: { $0 })
expectEqual(10, d2.count)
let d3 = Dictionary(grouping: 0..<0, by: { $0 })
expectEqual(0, d3.count)
}
DictionaryTestSuite.test("mapValues(_:)") {
let d1 = [10: 1010, 20: 1020, 30: 1030]
let d2 = d1.mapValues(String.init)
expectEqual(d1.count, d2.count)
expectEqual(d1.keys.first, d2.keys.first)
for (key, _) in d1 {
expectEqual(String(d1[key]!), d2[key]!)
}
do {
let d3: [MinimalHashableValue : Int] = Dictionary(
uniqueKeysWithValues: d1.lazy.map { (MinimalHashableValue($0), $1) })
expectEqual(d3.count, 3)
MinimalHashableValue.timesEqualEqualWasCalled = 0
MinimalHashableValue.timesHashIntoWasCalled = 0
// Calling mapValues shouldn't ever recalculate any hashes.
let d4 = d3.mapValues(String.init)
expectEqual(d4.count, d3.count)
expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled)
expectEqual(0, MinimalHashableValue.timesHashIntoWasCalled)
}
}
DictionaryTestSuite.test("capacity/init(minimumCapacity:)") {
let d0 = Dictionary<String, Int>(minimumCapacity: 0)
expectGE(d0.capacity, 0)
let d1 = Dictionary<String, Int>(minimumCapacity: 1)
expectGE(d1.capacity, 1)
let d3 = Dictionary<String, Int>(minimumCapacity: 3)
expectGE(d3.capacity, 3)
let d4 = Dictionary<String, Int>(minimumCapacity: 4)
expectGE(d4.capacity, 4)
let d10 = Dictionary<String, Int>(minimumCapacity: 10)
expectGE(d10.capacity, 10)
let d100 = Dictionary<String, Int>(minimumCapacity: 100)
expectGE(d100.capacity, 100)
let d1024 = Dictionary<String, Int>(minimumCapacity: 1024)
expectGE(d1024.capacity, 1024)
}
DictionaryTestSuite.test("capacity/reserveCapacity(_:)") {
var d1 = [10: 1010, 20: 1020, 30: 1030]
expectEqual(3, d1.capacity)
d1[40] = 1040
expectEqual(6, d1.capacity)
// Reserving new capacity jumps up to next limit.
d1.reserveCapacity(7)
expectEqual(12, d1.capacity)
// Can reserve right up to a limit.
d1.reserveCapacity(24)
expectEqual(24, d1.capacity)
// Fill up to the limit, no reallocation.
d1.merge(stride(from: 50, through: 240, by: 10).lazy.map { ($0, 1000 + $0) },
uniquingKeysWith: { (_,_) in fatalError() })
expectEqual(24, d1.count)
expectEqual(24, d1.capacity)
d1[250] = 1250
expectEqual(48, d1.capacity)
}
#if _runtime(_ObjC)
//===---
// NSDictionary -> Dictionary bridging tests.
//===---
func getAsNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary {
let keys = Array(d.keys.map { TestObjCKeyTy($0) })
let values = Array(d.values.map { TestObjCValueTy($0) })
// Return an `NSMutableDictionary` to make sure that it has a unique
// pointer identity.
return NSMutableDictionary(objects: values, forKeys: keys)
}
func getAsEquatableNSDictionary(_ d: Dictionary<Int, Int>) -> NSDictionary {
let keys = Array(d.keys.map { TestObjCKeyTy($0) })
let values = Array(d.values.map { TestObjCEquatableValueTy($0) })
// Return an `NSMutableDictionary` to make sure that it has a unique
// pointer identity.
return NSMutableDictionary(objects: values, forKeys: keys)
}
func getAsNSMutableDictionary(_ d: Dictionary<Int, Int>) -> NSMutableDictionary {
let keys = Array(d.keys.map { TestObjCKeyTy($0) })
let values = Array(d.values.map { TestObjCValueTy($0) })
return NSMutableDictionary(objects: values, forKeys: keys)
}
func getBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> {
let nsd = getAsNSDictionary([10: 1010, 20: 1020, 30: 1030])
return convertNSDictionaryToDictionary(nsd)
}
func getBridgedVerbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, AnyObject> {
let nsd = getAsNSDictionary(d)
return convertNSDictionaryToDictionary(nsd)
}
func getBridgedVerbatimDictionaryAndNSMutableDictionary()
-> (Dictionary<NSObject, AnyObject>, NSMutableDictionary) {
let nsd = getAsNSMutableDictionary([10: 1010, 20: 1020, 30: 1030])
return (convertNSDictionaryToDictionary(nsd), nsd)
}
func getBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
let nsd = getAsNSDictionary([10: 1010, 20: 1020, 30: 1030 ])
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
func getBridgedNonverbatimDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
let nsd = getAsNSDictionary(d)
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
func getBridgedNonverbatimDictionaryAndNSMutableDictionary()
-> (Dictionary<TestBridgedKeyTy, TestBridgedValueTy>, NSMutableDictionary) {
let nsd = getAsNSMutableDictionary([10: 1010, 20: 1020, 30: 1030])
return (Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self), nsd)
}
func getBridgedVerbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<NSObject, TestObjCEquatableValueTy> {
let nsd = getAsEquatableNSDictionary(d)
return convertNSDictionaryToDictionary(nsd)
}
func getBridgedNonverbatimEquatableDictionary(_ d: Dictionary<Int, Int>) -> Dictionary<TestBridgedKeyTy, TestBridgedEquatableValueTy> {
let nsd = getAsEquatableNSDictionary(d)
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
func getHugeBridgedVerbatimDictionaryHelper() -> NSDictionary {
let keys = (1...32).map { TestObjCKeyTy($0) }
let values = (1...32).map { TestObjCValueTy(1000 + $0) }
return NSMutableDictionary(objects: values, forKeys: keys)
}
func getHugeBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> {
let nsd = getHugeBridgedVerbatimDictionaryHelper()
return convertNSDictionaryToDictionary(nsd)
}
func getHugeBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
let nsd = getHugeBridgedVerbatimDictionaryHelper()
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
/// A mock dictionary that stores its keys and values in parallel arrays, which
/// allows it to return inner pointers to the keys array in fast enumeration.
@objc
class ParallelArrayDictionary : NSDictionary {
struct Keys {
var key0: AnyObject = TestObjCKeyTy(10)
var key1: AnyObject = TestObjCKeyTy(20)
var key2: AnyObject = TestObjCKeyTy(30)
var key3: AnyObject = TestObjCKeyTy(40)
}
var keys = [ Keys() ]
var value: AnyObject = TestObjCValueTy(1111)
override init() {
super.init()
}
override init(
objects: UnsafePointer<AnyObject>?,
forKeys keys: UnsafePointer<NSCopying>?,
count: Int) {
super.init(objects: objects, forKeys: keys, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by ParallelArrayDictionary")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> Any {
// Ensure that copying this dictionary does not produce a CoreFoundation
// object.
return self
}
override func countByEnumerating(
with state: UnsafeMutablePointer<NSFastEnumerationState>,
objects: AutoreleasingUnsafeMutablePointer<AnyObject?>,
count: Int
) -> Int {
var theState = state.pointee
if theState.state == 0 {
theState.state = 1
theState.itemsPtr = AutoreleasingUnsafeMutablePointer(keys._baseAddressIfContiguous)
theState.mutationsPtr = _fastEnumerationStorageMutationsPtr
state.pointee = theState
return 4
}
return 0
}
override func object(forKey aKey: Any) -> Any? {
return value
}
override var count: Int {
return 4
}
}
func getParallelArrayBridgedVerbatimDictionary() -> Dictionary<NSObject, AnyObject> {
let nsd: NSDictionary = ParallelArrayDictionary()
return convertNSDictionaryToDictionary(nsd)
}
func getParallelArrayBridgedNonverbatimDictionary() -> Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
let nsd: NSDictionary = ParallelArrayDictionary()
return Swift._forceBridgeFromObjectiveC(nsd, Dictionary.self)
}
@objc
class CustomImmutableNSDictionary : NSDictionary {
init(_privateInit: ()) {
super.init()
}
override init() {
expectUnreachable()
super.init()
}
override init(
objects: UnsafePointer<AnyObject>?,
forKeys keys: UnsafePointer<NSCopying>?,
count: Int) {
expectUnreachable()
super.init(objects: objects, forKeys: keys, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by CustomImmutableNSDictionary")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> Any {
CustomImmutableNSDictionary.timesCopyWithZoneWasCalled += 1
return self
}
override func object(forKey aKey: Any) -> Any? {
CustomImmutableNSDictionary.timesObjectForKeyWasCalled += 1
return getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]).object(forKey: aKey)
}
override func keyEnumerator() -> NSEnumerator {
CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled += 1
return getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]).keyEnumerator()
}
override var count: Int {
CustomImmutableNSDictionary.timesCountWasCalled += 1
return 3
}
static var timesCopyWithZoneWasCalled = 0
static var timesObjectForKeyWasCalled = 0
static var timesKeyEnumeratorWasCalled = 0
static var timesCountWasCalled = 0
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.DictionaryIsCopied") {
let (d, nsd) = getBridgedVerbatimDictionaryAndNSMutableDictionary()
assert(isCocoaDictionary(d))
// Find an existing key.
do {
let kv = d[d.index(forKey: TestObjCKeyTy(10))!]
assert(kv.0 == TestObjCKeyTy(10))
assert((kv.1 as! TestObjCValueTy).value == 1010)
}
// Delete the key from the NSMutableDictionary.
assert(nsd[TestObjCKeyTy(10)] != nil)
nsd.removeObject(forKey: TestObjCKeyTy(10))
assert(nsd[TestObjCKeyTy(10)] == nil)
// Find an existing key, again.
do {
let kv = d[d.index(forKey: TestObjCKeyTy(10))!]
assert(kv.0 == TestObjCKeyTy(10))
assert((kv.1 as! TestObjCValueTy).value == 1010)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.DictionaryIsCopied") {
let (d, nsd) = getBridgedNonverbatimDictionaryAndNSMutableDictionary()
assert(isNativeDictionary(d))
// Find an existing key.
do {
let kv = d[d.index(forKey: TestBridgedKeyTy(10))!]
assert(kv.0 == TestBridgedKeyTy(10))
assert(kv.1.value == 1010)
}
// Delete the key from the NSMutableDictionary.
assert(nsd[TestBridgedKeyTy(10) as NSCopying] != nil)
nsd.removeObject(forKey: TestBridgedKeyTy(10) as NSCopying)
assert(nsd[TestBridgedKeyTy(10) as NSCopying] == nil)
// Find an existing key, again.
do {
let kv = d[d.index(forKey: TestBridgedKeyTy(10))!]
assert(kv.0 == TestBridgedKeyTy(10))
assert(kv.1.value == 1010)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.NSDictionaryIsRetained") {
let nsd: NSDictionary =
NSDictionary(dictionary:
getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]))
let d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd)
let bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d)
expectEqual(
unsafeBitCast(nsd, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nsd)
_fixLifetime(d)
_fixLifetime(bridgedBack)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.NSDictionaryIsCopied") {
let nsd: NSDictionary =
NSDictionary(dictionary:
getAsNSDictionary([10: 1010, 20: 1020, 30: 1030]))
let d: [TestBridgedKeyTy : TestBridgedValueTy] =
convertNSDictionaryToDictionary(nsd)
let bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d)
expectNotEqual(
unsafeBitCast(nsd, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nsd)
_fixLifetime(d)
_fixLifetime(bridgedBack)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ImmutableDictionaryIsRetained") {
let nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ())
CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0
CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0
CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0
CustomImmutableNSDictionary.timesCountWasCalled = 0
let d: [NSObject : AnyObject] = convertNSDictionaryToDictionary(nsd)
expectEqual(1, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled)
expectEqual(0, CustomImmutableNSDictionary.timesObjectForKeyWasCalled)
expectEqual(0, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled)
expectEqual(0, CustomImmutableNSDictionary.timesCountWasCalled)
let bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d)
expectEqual(
unsafeBitCast(nsd, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nsd)
_fixLifetime(d)
_fixLifetime(bridgedBack)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ImmutableDictionaryIsCopied") {
//some bridged NSDictionary operations on non-standard NSDictionary subclasses
//autorelease keys and values. Make sure the leak checker isn't confused
autoreleasepool {
let nsd: NSDictionary = CustomImmutableNSDictionary(_privateInit: ())
CustomImmutableNSDictionary.timesCopyWithZoneWasCalled = 0
CustomImmutableNSDictionary.timesObjectForKeyWasCalled = 0
CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled = 0
CustomImmutableNSDictionary.timesCountWasCalled = 0
TestBridgedValueTy.bridgeOperations = 0
let d: [TestBridgedKeyTy : TestBridgedValueTy] =
convertNSDictionaryToDictionary(nsd)
expectEqual(0, CustomImmutableNSDictionary.timesCopyWithZoneWasCalled)
expectEqual(3, CustomImmutableNSDictionary.timesObjectForKeyWasCalled)
expectEqual(1, CustomImmutableNSDictionary.timesKeyEnumeratorWasCalled)
expectNotEqual(0, CustomImmutableNSDictionary.timesCountWasCalled)
expectEqual(3, TestBridgedValueTy.bridgeOperations)
let bridgedBack: NSDictionary = convertDictionaryToNSDictionary(d)
expectNotEqual(
unsafeBitCast(nsd, to: Int.self),
unsafeBitCast(bridgedBack, to: Int.self))
_fixLifetime(nsd)
_fixLifetime(d)
_fixLifetime(bridgedBack)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.IndexForKey") {
let d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
// Find an existing key.
do {
var kv = d[d.index(forKey: TestObjCKeyTy(10))!]
assert(kv.0 == TestObjCKeyTy(10))
assert((kv.1 as! TestObjCValueTy).value == 1010)
kv = d[d.index(forKey: TestObjCKeyTy(20))!]
assert(kv.0 == TestObjCKeyTy(20))
assert((kv.1 as! TestObjCValueTy).value == 1020)
kv = d[d.index(forKey: TestObjCKeyTy(30))!]
assert(kv.0 == TestObjCKeyTy(30))
assert((kv.1 as! TestObjCValueTy).value == 1030)
}
// Try to find a key that does not exist.
assert(d.index(forKey: TestObjCKeyTy(40)) == nil)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.IndexForKey") {
let d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
// Find an existing key.
do {
var kv = d[d.index(forKey: TestBridgedKeyTy(10))!]
assert(kv.0 == TestBridgedKeyTy(10))
assert(kv.1.value == 1010)
kv = d[d.index(forKey: TestBridgedKeyTy(20))!]
assert(kv.0 == TestBridgedKeyTy(20))
assert(kv.1.value == 1020)
kv = d[d.index(forKey: TestBridgedKeyTy(30))!]
assert(kv.0 == TestBridgedKeyTy(30))
assert(kv.1.value == 1030)
}
// Try to find a key that does not exist.
assert(d.index(forKey: TestBridgedKeyTy(40)) == nil)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex") {
let d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
let startIndex = d.startIndex
let endIndex = d.endIndex
assert(startIndex != endIndex)
assert(startIndex < endIndex)
assert(startIndex <= endIndex)
assert(!(startIndex >= endIndex))
assert(!(startIndex > endIndex))
assert(identity1 == d._rawIdentifier())
var pairs = Array<(Int, Int)>()
for i in d.indices {
let (key, value) = d[i]
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs += [kv]
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(identity1 == d._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex") {
let d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
let startIndex = d.startIndex
let endIndex = d.endIndex
assert(startIndex != endIndex)
assert(startIndex < endIndex)
assert(startIndex <= endIndex)
assert(!(startIndex >= endIndex))
assert(!(startIndex > endIndex))
assert(identity1 == d._rawIdentifier())
var pairs = Array<(Int, Int)>()
for i in d.indices {
let (key, value) = d[i]
let kv = (key.value, value.value)
pairs += [kv]
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(identity1 == d._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex_Empty") {
let d = getBridgedVerbatimDictionary([:])
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
let startIndex = d.startIndex
let endIndex = d.endIndex
assert(startIndex == endIndex)
assert(!(startIndex < endIndex))
assert(startIndex <= endIndex)
assert(startIndex >= endIndex)
assert(!(startIndex > endIndex))
assert(identity1 == d._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex_Empty") {
let d = getBridgedNonverbatimDictionary([:])
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
let startIndex = d.startIndex
let endIndex = d.endIndex
assert(startIndex == endIndex)
assert(!(startIndex < endIndex))
assert(startIndex <= endIndex)
assert(startIndex >= endIndex)
assert(!(startIndex > endIndex))
assert(identity1 == d._rawIdentifier())
// Keep indexes alive during the calls above.
_fixLifetime(startIndex)
_fixLifetime(endIndex)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithKey") {
var d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
// Read existing key-value pairs.
var v = d[TestObjCKeyTy(10)] as! TestObjCValueTy
assert(v.value == 1010)
v = d[TestObjCKeyTy(20)] as! TestObjCValueTy
assert(v.value == 1020)
v = d[TestObjCKeyTy(30)] as! TestObjCValueTy
assert(v.value == 1030)
assert(identity1 == d._rawIdentifier())
// Insert a new key-value pair.
d[TestObjCKeyTy(40)] = TestObjCValueTy(2040)
let identity2 = d._rawIdentifier()
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 4)
v = d[TestObjCKeyTy(10)] as! TestObjCValueTy
assert(v.value == 1010)
v = d[TestObjCKeyTy(20)] as! TestObjCValueTy
assert(v.value == 1020)
v = d[TestObjCKeyTy(30)] as! TestObjCValueTy
assert(v.value == 1030)
v = d[TestObjCKeyTy(40)] as! TestObjCValueTy
assert(v.value == 2040)
// Overwrite value in existing binding.
d[TestObjCKeyTy(10)] = TestObjCValueTy(2010)
assert(identity2 == d._rawIdentifier())
assert(isNativeDictionary(d))
assert(d.count == 4)
v = d[TestObjCKeyTy(10)] as! TestObjCValueTy
assert(v.value == 2010)
v = d[TestObjCKeyTy(20)] as! TestObjCValueTy
assert(v.value == 1020)
v = d[TestObjCKeyTy(30)] as! TestObjCValueTy
assert(v.value == 1030)
v = d[TestObjCKeyTy(40)] as! TestObjCValueTy
assert(v.value == 2040)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithKey") {
var d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
// Read existing key-value pairs.
var v = d[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = d[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = d[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
assert(identity1 == d._rawIdentifier())
// Insert a new key-value pair.
d[TestBridgedKeyTy(40)] = TestBridgedValueTy(2040)
let identity2 = d._rawIdentifier()
// Storage identity may or may not change depending on allocation behavior.
// (d is eagerly bridged to a regular uniquely referenced native Dictionary.)
//assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 4)
v = d[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = d[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = d[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
v = d[TestBridgedKeyTy(40)]
assert(v!.value == 2040)
// Overwrite value in existing binding.
d[TestBridgedKeyTy(10)] = TestBridgedValueTy(2010)
assert(identity2 == d._rawIdentifier())
assert(isNativeDictionary(d))
assert(d.count == 4)
v = d[TestBridgedKeyTy(10)]
assert(v!.value == 2010)
v = d[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = d[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
v = d[TestBridgedKeyTy(40)]
assert(v!.value == 2040)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.UpdateValueForKey") {
// Insert a new key-value pair.
do {
var d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
let oldValue: AnyObject? =
d.updateValue(TestObjCValueTy(2040), forKey: TestObjCKeyTy(40))
assert(oldValue == nil)
let identity2 = d._rawIdentifier()
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 4)
assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
assert((d[TestObjCKeyTy(40)] as! TestObjCValueTy).value == 2040)
}
// Overwrite a value in existing binding.
do {
var d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
let oldValue: AnyObject? =
d.updateValue(TestObjCValueTy(2010), forKey: TestObjCKeyTy(10))
assert((oldValue as! TestObjCValueTy).value == 1010)
let identity2 = d._rawIdentifier()
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 3)
assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 2010)
assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.UpdateValueForKey") {
// Insert a new key-value pair.
do {
var d = getBridgedNonverbatimDictionary()
// let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
let oldValue =
d.updateValue(TestBridgedValueTy(2040), forKey: TestBridgedKeyTy(40))
assert(oldValue == nil)
// let identity2 = d._rawIdentifier()
// Storage identity may or may not change depending on allocation behavior.
// (d is eagerly bridged to a regular uniquely referenced native Dictionary.)
//assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 4)
assert(d[TestBridgedKeyTy(10)]!.value == 1010)
assert(d[TestBridgedKeyTy(20)]!.value == 1020)
assert(d[TestBridgedKeyTy(30)]!.value == 1030)
assert(d[TestBridgedKeyTy(40)]!.value == 2040)
}
// Overwrite a value in existing binding.
do {
var d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
let oldValue =
d.updateValue(TestBridgedValueTy(2010), forKey: TestBridgedKeyTy(10))!
assert(oldValue.value == 1010)
let identity2 = d._rawIdentifier()
assert(identity1 == identity2)
assert(isNativeDictionary(d))
assert(d.count == 3)
assert(d[TestBridgedKeyTy(10)]!.value == 2010)
assert(d[TestBridgedKeyTy(20)]!.value == 1020)
assert(d[TestBridgedKeyTy(30)]!.value == 1030)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") {
var d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
let foundIndex1 = d.index(forKey: TestObjCKeyTy(10))!
assert(d[foundIndex1].0 == TestObjCKeyTy(10))
assert((d[foundIndex1].1 as! TestObjCValueTy).value == 1010)
assert(identity1 == d._rawIdentifier())
let removedElement = d.remove(at: foundIndex1)
assert(identity1 != d._rawIdentifier())
assert(isNativeDictionary(d))
assert(removedElement.0 == TestObjCKeyTy(10))
assert((removedElement.1 as! TestObjCValueTy).value == 1010)
assert(d.count == 2)
assert(d.index(forKey: TestObjCKeyTy(10)) == nil)
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt")
.code {
var d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
let foundIndex1 = d.index(forKey: TestBridgedKeyTy(10))!
assert(d[foundIndex1].0 == TestBridgedKeyTy(10))
assert(d[foundIndex1].1.value == 1010)
assert(identity1 == d._rawIdentifier())
let removedElement = d.remove(at: foundIndex1)
assert(identity1 == d._rawIdentifier())
assert(isNativeDictionary(d))
assert(removedElement.0 == TestObjCKeyTy(10) as TestBridgedKeyTy)
assert(removedElement.1.value == 1010)
assert(d.count == 2)
assert(d.index(forKey: TestBridgedKeyTy(10)) == nil)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveValueForKey") {
do {
var d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
var deleted: AnyObject? = d.removeValue(forKey: TestObjCKeyTy(0))
assert(deleted == nil)
assert(identity1 == d._rawIdentifier())
assert(isCocoaDictionary(d))
deleted = d.removeValue(forKey: TestObjCKeyTy(10))
assert((deleted as! TestObjCValueTy).value == 1010)
let identity2 = d._rawIdentifier()
assert(identity1 != identity2)
assert(isNativeDictionary(d))
assert(d.count == 2)
assert(d[TestObjCKeyTy(10)] == nil)
assert((d[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
assert(identity2 == d._rawIdentifier())
}
do {
var d1 = getBridgedVerbatimDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(isCocoaDictionary(d1))
assert(isCocoaDictionary(d2))
var deleted: AnyObject? = d2.removeValue(forKey: TestObjCKeyTy(0))
assert(deleted == nil)
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
assert(isCocoaDictionary(d1))
assert(isCocoaDictionary(d2))
deleted = d2.removeValue(forKey: TestObjCKeyTy(10))
assert((deleted as! TestObjCValueTy).value == 1010)
let identity2 = d2._rawIdentifier()
assert(identity1 != identity2)
assert(isCocoaDictionary(d1))
assert(isNativeDictionary(d2))
assert(d2.count == 2)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
assert((d1[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d1[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
assert(identity1 == d1._rawIdentifier())
assert(d2[TestObjCKeyTy(10)] == nil)
assert((d2[TestObjCKeyTy(20)] as! TestObjCValueTy).value == 1020)
assert((d2[TestObjCKeyTy(30)] as! TestObjCValueTy).value == 1030)
assert(identity2 == d2._rawIdentifier())
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveValueForKey")
.code {
do {
var d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
var deleted = d.removeValue(forKey: TestBridgedKeyTy(0))
assert(deleted == nil)
assert(identity1 == d._rawIdentifier())
assert(isNativeDictionary(d))
deleted = d.removeValue(forKey: TestBridgedKeyTy(10))
assert(deleted!.value == 1010)
let identity2 = d._rawIdentifier()
assert(identity1 == identity2)
assert(isNativeDictionary(d))
assert(d.count == 2)
assert(d[TestBridgedKeyTy(10)] == nil)
assert(d[TestBridgedKeyTy(20)]!.value == 1020)
assert(d[TestBridgedKeyTy(30)]!.value == 1030)
assert(identity2 == d._rawIdentifier())
}
do {
var d1 = getBridgedNonverbatimDictionary()
let identity1 = d1._rawIdentifier()
var d2 = d1
assert(isNativeDictionary(d1))
assert(isNativeDictionary(d2))
var deleted = d2.removeValue(forKey: TestBridgedKeyTy(0))
assert(deleted == nil)
assert(identity1 == d1._rawIdentifier())
assert(identity1 == d2._rawIdentifier())
assert(isNativeDictionary(d1))
assert(isNativeDictionary(d2))
deleted = d2.removeValue(forKey: TestBridgedKeyTy(10))
assert(deleted!.value == 1010)
let identity2 = d2._rawIdentifier()
assert(identity1 != identity2)
assert(isNativeDictionary(d1))
assert(isNativeDictionary(d2))
assert(d2.count == 2)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
assert(d1[TestBridgedKeyTy(20)]!.value == 1020)
assert(d1[TestBridgedKeyTy(30)]!.value == 1030)
assert(identity1 == d1._rawIdentifier())
assert(d2[TestBridgedKeyTy(10)] == nil)
assert(d2[TestBridgedKeyTy(20)]!.value == 1020)
assert(d2[TestBridgedKeyTy(30)]!.value == 1030)
assert(identity2 == d2._rawIdentifier())
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.RemoveAll") {
do {
var d = getBridgedVerbatimDictionary([:])
assert(isCocoaDictionary(d))
assert(d.count == 0)
let empty = Dictionary<Int, Int>()
expectNotEqual(empty._rawIdentifier(), d._rawIdentifier())
d.removeAll()
assert(empty._rawIdentifier() == d._rawIdentifier())
assert(d.count == 0)
}
do {
var d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
let originalCapacity = d.count
assert(d.count == 3)
assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
d.removeAll()
assert(identity1 != d._rawIdentifier())
assert(d.capacity < originalCapacity)
assert(d.count == 0)
assert(d[TestObjCKeyTy(10)] == nil)
}
do {
var d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
let originalCapacity = d.count
assert(d.count == 3)
assert((d[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
d.removeAll(keepingCapacity: true)
assert(identity1 != d._rawIdentifier())
assert(d.capacity >= originalCapacity)
assert(d.count == 0)
assert(d[TestObjCKeyTy(10)] == nil)
}
do {
var d1 = getBridgedVerbatimDictionary()
let identity1 = d1._rawIdentifier()
assert(isCocoaDictionary(d1))
let originalCapacity = d1.count
assert(d1.count == 3)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
var d2 = d1
d2.removeAll()
let identity2 = d2._rawIdentifier()
assert(identity1 == d1._rawIdentifier())
assert(identity2 != identity1)
assert(d1.count == 3)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
assert(d2.capacity < originalCapacity)
assert(d2.count == 0)
assert(d2[TestObjCKeyTy(10)] == nil)
}
do {
var d1 = getBridgedVerbatimDictionary()
let identity1 = d1._rawIdentifier()
assert(isCocoaDictionary(d1))
let originalCapacity = d1.count
assert(d1.count == 3)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
var d2 = d1
d2.removeAll(keepingCapacity: true)
let identity2 = d2._rawIdentifier()
assert(identity1 == d1._rawIdentifier())
assert(identity2 != identity1)
assert(d1.count == 3)
assert((d1[TestObjCKeyTy(10)] as! TestObjCValueTy).value == 1010)
assert(d2.capacity >= originalCapacity)
assert(d2.count == 0)
assert(d2[TestObjCKeyTy(10)] == nil)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAll") {
if #available(macOS 15.0, iOS 13.0, watchOS 6.0, tvOS 13.0, *) {
// Identity of empty dictionaries changed in
// https://github.com/apple/swift/pull/22527
var d = getBridgedNonverbatimDictionary([:])
assert(isNativeDictionary(d))
assert(d.count == 0)
let empty = Dictionary<Int, Int>()
expectEqual(empty._rawIdentifier(), d._rawIdentifier())
d.removeAll()
assert(empty._rawIdentifier() == d._rawIdentifier())
assert(d.count == 0)
}
do {
var d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
let originalCapacity = d.count
assert(d.count == 3)
assert(d[TestBridgedKeyTy(10)]!.value == 1010)
d.removeAll()
assert(identity1 != d._rawIdentifier())
assert(d.capacity < originalCapacity)
assert(d.count == 0)
assert(d[TestBridgedKeyTy(10)] == nil)
}
do {
var d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
let originalCapacity = d.count
assert(d.count == 3)
assert(d[TestBridgedKeyTy(10)]!.value == 1010)
d.removeAll(keepingCapacity: true)
assert(identity1 == d._rawIdentifier())
assert(d.capacity >= originalCapacity)
assert(d.count == 0)
assert(d[TestBridgedKeyTy(10)] == nil)
}
do {
let d1 = getBridgedNonverbatimDictionary()
let identity1 = d1._rawIdentifier()
assert(isNativeDictionary(d1))
let originalCapacity = d1.count
assert(d1.count == 3)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
var d2 = d1
d2.removeAll()
let identity2 = d2._rawIdentifier()
assert(identity1 == d1._rawIdentifier())
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
assert(d2.capacity < originalCapacity)
assert(d2.count == 0)
assert(d2[TestBridgedKeyTy(10)] == nil)
}
do {
let d1 = getBridgedNonverbatimDictionary()
let identity1 = d1._rawIdentifier()
assert(isNativeDictionary(d1))
let originalCapacity = d1.count
assert(d1.count == 3)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
var d2 = d1
d2.removeAll(keepingCapacity: true)
let identity2 = d2._rawIdentifier()
assert(identity1 == d1._rawIdentifier())
assert(identity2 != identity1)
assert(d1.count == 3)
assert(d1[TestBridgedKeyTy(10)]!.value == 1010)
assert(d2.capacity >= originalCapacity)
assert(d2.count == 0)
assert(d2[TestBridgedKeyTy(10)] == nil)
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Count") {
let d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
assert(d.count == 3)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Count") {
let d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
assert(d.count == 3)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate") {
let d = getBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate") {
let d = getBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = (key.value, value.value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Empty") {
let d = getBridgedVerbatimDictionary([:])
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
var iter = d.makeIterator()
// Cannot write code below because of
// <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison
// assert(iter.next() == .none)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Empty") {
let d = getBridgedNonverbatimDictionary([:])
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
var iter = d.makeIterator()
// Cannot write code below because of
// <rdar://problem/16811736> Optional tuples are broken as optionals regarding == comparison
// assert(iter.next() == .none)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_Huge") {
let d = getHugeBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
var expectedPairs = Array<(Int, Int)>()
for i in 1...32 {
expectedPairs += [(i, 1000 + i)]
}
assert(equalsUnordered(pairs, expectedPairs))
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Huge") {
let d = getHugeBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = (key.value, value.value)
pairs.append(kv)
}
var expectedPairs = Array<(Int, Int)>()
for i in 1...32 {
expectedPairs += [(i, 1000 + i)]
}
assert(equalsUnordered(pairs, expectedPairs))
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == d._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.Generate_ParallelArray") {
autoreleasepoolIfUnoptimizedReturnAutoreleased {
// Add an autorelease pool because ParallelArrayDictionary autoreleases
// values in objectForKey.
let d = getParallelArrayBridgedVerbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isCocoaDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
let expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ]
assert(equalsUnordered(pairs, expectedPairs))
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == d._rawIdentifier())
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_ParallelArray") {
//some bridged NSDictionary operations on non-standard NSDictionary subclasses
//autorelease keys and values. Make sure the leak checker isn't confused
autoreleasepool {
let d = getParallelArrayBridgedNonverbatimDictionary()
let identity1 = d._rawIdentifier()
assert(isNativeDictionary(d))
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = (key.value, value.value)
pairs.append(kv)
}
let expectedPairs = [ (10, 1111), (20, 1111), (30, 1111), (40, 1111) ]
assert(equalsUnordered(pairs, expectedPairs))
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(iter.next() == nil)
assert(identity1 == d._rawIdentifier())
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Empty") {
let d1 = getBridgedVerbatimEquatableDictionary([:])
let identity1 = d1._rawIdentifier()
assert(isCocoaDictionary(d1))
var d2 = getBridgedVerbatimEquatableDictionary([:])
var identity2 = d2._rawIdentifier()
assert(isCocoaDictionary(d2))
// We can't check that `identity1 != identity2` because Foundation might be
// returning the same singleton NSDictionary for empty dictionaries.
assert(d1 == d2)
assert(identity1 == d1._rawIdentifier())
assert(identity2 == d2._rawIdentifier())
d2[TestObjCKeyTy(10)] = TestObjCEquatableValueTy(2010)
assert(isNativeDictionary(d2))
assert(identity2 != d2._rawIdentifier())
identity2 = d2._rawIdentifier()
assert(d1 != d2)
assert(identity1 == d1._rawIdentifier())
assert(identity2 == d2._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Empty") {
guard #available(macOS 15.0, iOS 13.0, watchOS 6.0, tvOS 13.0, *) else {
// Identity of empty dictionaries changed in
// https://github.com/apple/swift/pull/22527
return
}
let d1 = getBridgedNonverbatimEquatableDictionary([:])
let identity1 = d1._rawIdentifier()
assert(isNativeDictionary(d1))
var d2 = getBridgedNonverbatimEquatableDictionary([:])
let identity2 = d2._rawIdentifier()
assert(isNativeDictionary(d2))
assert(identity1 == identity2)
assert(d1 == d2)
assert(identity1 == d1._rawIdentifier())
assert(identity2 == d2._rawIdentifier())
d2[TestBridgedKeyTy(10)] = TestBridgedEquatableValueTy(2010)
assert(isNativeDictionary(d2))
assert(identity2 != d2._rawIdentifier())
assert(d1 != d2)
assert(identity1 == d1._rawIdentifier())
assert(identity2 != d2._rawIdentifier())
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Small") {
func helper(_ nd1: Dictionary<Int, Int>, _ nd2: Dictionary<Int, Int>, _ expectedEq: Bool) {
let d1 = getBridgedVerbatimEquatableDictionary(nd1)
let identity1 = d1._rawIdentifier()
assert(isCocoaDictionary(d1))
var d2 = getBridgedVerbatimEquatableDictionary(nd2)
var identity2 = d2._rawIdentifier()
assert(isCocoaDictionary(d2))
do {
let eq1 = (d1 == d2)
assert(eq1 == expectedEq)
let eq2 = (d2 == d1)
assert(eq2 == expectedEq)
let neq1 = (d1 != d2)
assert(neq1 != expectedEq)
let neq2 = (d2 != d1)
assert(neq2 != expectedEq)
}
assert(identity1 == d1._rawIdentifier())
assert(identity2 == d2._rawIdentifier())
d2[TestObjCKeyTy(1111)] = TestObjCEquatableValueTy(1111)
d2[TestObjCKeyTy(1111)] = nil
assert(isNativeDictionary(d2))
assert(identity2 != d2._rawIdentifier())
identity2 = d2._rawIdentifier()
do {
let eq1 = (d1 == d2)
assert(eq1 == expectedEq)
let eq2 = (d2 == d1)
assert(eq2 == expectedEq)
let neq1 = (d1 != d2)
assert(neq1 != expectedEq)
let neq2 = (d2 != d1)
assert(neq2 != expectedEq)
}
assert(identity1 == d1._rawIdentifier())
assert(identity2 == d2._rawIdentifier())
}
helper([:], [:], true)
helper([10: 1010],
[10: 1010],
true)
helper([10: 1010, 20: 1020],
[10: 1010, 20: 1020],
true)
helper([10: 1010, 20: 1020, 30: 1030],
[10: 1010, 20: 1020, 30: 1030],
true)
helper([10: 1010, 20: 1020, 30: 1030],
[10: 1010, 20: 1020, 1111: 1030],
false)
helper([10: 1010, 20: 1020, 30: 1030],
[10: 1010, 20: 1020, 30: 1111],
false)
helper([10: 1010, 20: 1020, 30: 1030],
[10: 1010, 20: 1020],
false)
helper([10: 1010, 20: 1020, 30: 1030],
[10: 1010],
false)
helper([10: 1010, 20: 1020, 30: 1030],
[:],
false)
helper([10: 1010, 20: 1020, 30: 1030],
[10: 1010, 20: 1020, 30: 1030, 40: 1040],
false)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.ArrayOfDictionaries") {
let nsa = NSMutableArray()
for i in 0..<3 {
nsa.add(
getAsNSDictionary([10: 1010 + i, 20: 1020 + i, 30: 1030 + i]))
}
var a = nsa as [AnyObject] as! [Dictionary<NSObject, AnyObject>]
for i in 0..<3 {
let d = a[i]
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
let expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ]
assert(equalsUnordered(pairs, expectedPairs))
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.ArrayOfDictionaries") {
let nsa = NSMutableArray()
for i in 0..<3 {
nsa.add(
getAsNSDictionary([10: 1010 + i, 20: 1020 + i, 30: 1030 + i]))
}
var a = nsa as [AnyObject] as! [Dictionary<TestBridgedKeyTy, TestBridgedValueTy>]
for i in 0..<3 {
let d = a[i]
var iter = d.makeIterator()
var pairs = Array<(Int, Int)>()
while let (key, value) = iter.next() {
let kv = (key.value, value.value)
pairs.append(kv)
}
let expectedPairs = [ (10, 1010 + i), (20, 1020 + i), (30, 1030 + i) ]
assert(equalsUnordered(pairs, expectedPairs))
}
}
DictionaryTestSuite.test("BridgedFromObjC.Nonverbatim.StringEqualityMismatch") {
// NSString's isEqual(_:) implementation is stricter than Swift's String, so
// Dictionary values bridged over from Objective-C may have duplicate keys.
// rdar://problem/35995647
let cafe1 = "Cafe\u{301}" as NSString
let cafe2 = "Café" as NSString
let nsd = NSMutableDictionary()
nsd.setObject(42, forKey: cafe1)
nsd.setObject(23, forKey: cafe2)
expectEqual(2, nsd.count)
expectTrue((42 as NSNumber).isEqual(nsd.object(forKey: cafe1)))
expectTrue((23 as NSNumber).isEqual(nsd.object(forKey: cafe2)))
let d = convertNSDictionaryToDictionary(nsd) as [String: Int]
expectEqual(1, d.count)
expectEqual(d["Cafe\u{301}"], d["Café"])
let v = d["Café"]
expectTrue(v == 42 || v == 23)
}
DictionaryTestSuite.test("Upcast.StringEqualityMismatch") {
// Upcasting from NSString to String keys changes their concept of equality,
// resulting in two equal keys, one of which should be discarded by the
// downcast. (Along with its associated value.)
// rdar://problem/35995647
let d: Dictionary<NSString, NSObject> = [
"cafe\u{301}": 1 as NSNumber,
"café": 2 as NSNumber,
]
expectEqual(d.count, 2)
let d2 = d as Dictionary<String, NSObject>
expectEqual(d2.count, 1)
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.OptionalDowncastFailure") {
let nsd = NSDictionary(
objects: [1 as NSNumber, 2 as NSNumber, 3 as NSNumber],
forKeys: ["One" as NSString, "Two" as NSString, "Three" as NSString])
expectNotNil(nsd as? [NSString: NSNumber])
expectNotNil(nsd as? [NSString: NSObject])
expectNotNil(nsd as? [NSObject: NSNumber])
expectNil(nsd as? [NSNumber: NSObject])
expectNil(nsd as? [NSObject: NSString])
}
DictionaryTestSuite
.test("BridgedFromObjC.Verbatim.ForcedDowncastFailure.Keys") {
let nsd = NSDictionary(
objects: [1 as NSNumber, 2 as NSNumber, 3 as NSNumber],
forKeys: ["One" as NSString, "Two" as NSString, "Three" as NSString])
let bridged = nsd as! [NSNumber: NSObject]
expectCrashLater()
// The forced downcast succeeds unconditionally; the cast is instead verified
// when we access individual elements.
_ = bridged.first
}
DictionaryTestSuite
.test("BridgedFromObjC.Verbatim.ForcedDowncastFailure.Values") {
let nsd = NSDictionary(
objects: [1 as NSNumber, 2 as NSNumber, 3 as NSNumber],
forKeys: ["One" as NSString, "Two" as NSString, "Three" as NSString])
let bridged = nsd as! [NSObject: NSString]
expectCrashLater()
// The forced downcast succeeds unconditionally; the cast is instead verified
// when we access individual elements.
_ = bridged.first
}
DictionaryTestSuite
.test("BridgedFromObjC.Verbatim.ForcedDowncastFailure.Both") {
let nsd = NSDictionary(
objects: [1 as NSNumber, 2 as NSNumber, 3 as NSNumber],
forKeys: ["One" as NSString, "Two" as NSString, "Three" as NSString])
let bridged = nsd as! [NSNumber: NSString]
expectCrashLater()
// The forced downcast succeeds unconditionally; the cast is instead verified
// when we access individual elements.
_ = bridged.first
}
DictionaryTestSuite
.test("BridgedFromObjC.Verbatim.ForcedDowncastFailure.Partial")
.code {
let nsd = NSMutableDictionary(
objects: (0..<10).map { "\($0)" as NSString },
forKeys: (0..<10).map { $0 as NSNumber })
nsd.setObject("cuckoo" as NSString, forKey: "cuckoo" as NSString)
let bridged = nsd as! [NSNumber: NSString]
// The forced downcast succeeds unconditionally; the cast is instead verified
// when we access individual elements.
for i in 0 ..< 10 {
expectEqual("\(i)" as NSString, bridged[i as NSNumber])
}
// The item with the unexpected key is only accessible when we iterate over
// the elements. There should be a trap when we get to it.
expectCrashLater()
for (key, value) in bridged {
_ = key
_ = value
}
}
DictionaryTestSuite.test("BridgedFromObjC.Verbatim.DowncastFailure.LeakTest") {
let nsd = NSMutableDictionary(
objects: (0..<100).map { TestObjCEquatableValueTy($0) },
forKeys: (0..<100).map { TestObjCKeyTy($0) })
expectNotNil(nsd as? [TestObjCKeyTy: TestObjCEquatableValueTy])
expectNotNil(nsd as? [TestObjCKeyTy: NSObject])
expectNotNil(nsd as? [NSObject: TestObjCEquatableValueTy])
// Inserting a single key-value pair of a different type should make all these
// downcasts fail.
nsd.setObject("cuckoo" as NSString, forKey: "cuckoo" as NSString)
expectNil(nsd as? [TestObjCKeyTy: TestObjCEquatableValueTy])
expectNil(nsd as? [TestObjCKeyTy: NSObject])
expectNil(nsd as? [NSObject: TestObjCEquatableValueTy])
// No crash test here -- we're relying on the leak tests in tearDown.
}
DictionaryTestSuite
.test("BridgedFromObjC.Nonverbatim.OptionalDowncastFailure") {
let nsd = NSDictionary(
objects: [1 as NSNumber, 2 as NSNumber, 3 as NSNumber],
forKeys: ["One" as NSString, "Two" as NSString, "Three" as NSString])
expectNotNil(nsd as? [String: Int])
expectNotNil(nsd as? [String: NSObject])
expectNotNil(nsd as? [NSObject: Int])
expectNil(nsd as? [Int: NSObject])
expectNil(nsd as? [NSObject: String])
}
DictionaryTestSuite
.test("BridgedFromObjC.Nonverbatim.ForcedDowncastFailure.Keys") {
let nsd = NSDictionary(
objects: [1 as NSNumber, 2 as NSNumber, 3 as NSNumber],
forKeys: ["One" as NSString, "Two" as NSString, "Three" as NSString])
expectCrashLater()
_ = nsd as! [Int: NSObject]
}
DictionaryTestSuite
.test("BridgedFromObjC.Nonverbatim.ForcedDowncastFailure.Values") {
let nsd = NSDictionary(
objects: [1 as NSNumber, 2 as NSNumber, 3 as NSNumber],
forKeys: ["One" as NSString, "Two" as NSString, "Three" as NSString])
expectCrashLater()
_ = nsd as! [NSObject: String]
}
DictionaryTestSuite
.test("BridgedFromObjC.Nonverbatim.ForcedDowncastFailure.Both") {
let nsd = NSDictionary(
objects: [1 as NSNumber, 2 as NSNumber, 3 as NSNumber],
forKeys: ["One" as NSString, "Two" as NSString, "Three" as NSString])
expectCrashLater()
_ = nsd as! [Int: String]
}
DictionaryTestSuite
.test("BridgedFromObjC.Nonverbatim.DowncastFailure.LeakTest") {
let nsd = NSMutableDictionary(
objects: (0..<100).map { TestObjCEquatableValueTy($0) },
forKeys: (0..<100).map { TestObjCKeyTy($0) })
expectNotNil(nsd as? [TestBridgedKeyTy: TestBridgedEquatableValueTy])
expectNotNil(nsd as? [TestBridgedKeyTy: NSObject])
expectNotNil(nsd as? [NSObject: TestBridgedEquatableValueTy])
// Inserting a single key-value pair of a different type should make all these
// downcasts fail.
nsd.setObject("cuckoo" as NSString, forKey: "cuckoo" as NSString)
expectNil(nsd as? [TestBridgedKeyTy: TestBridgedEquatableValueTy])
expectNil(nsd as? [TestBridgedKeyTy: NSObject])
expectNil(nsd as? [NSObject: TestBridgedEquatableValueTy])
// No crash test here -- we're relying on the leak tests in tearDown.
}
//===---
// Dictionary -> NSDictionary bridging tests.
//
// Key and Value are bridged verbatim.
//===---
DictionaryTestSuite.test("BridgedToObjC.Verbatim.Count") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
assert(d.count == 3)
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.ObjectForKey") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
var v: AnyObject? = d.object(forKey: TestObjCKeyTy(10)).map { $0 as AnyObject }
expectEqual(1010, (v as! TestObjCValueTy).value)
let idValue10 = unsafeBitCast(v, to: UInt.self)
v = d.object(forKey: TestObjCKeyTy(20)).map { $0 as AnyObject }
expectEqual(1020, (v as! TestObjCValueTy).value)
let idValue20 = unsafeBitCast(v, to: UInt.self)
v = d.object(forKey: TestObjCKeyTy(30)).map { $0 as AnyObject }
expectEqual(1030, (v as! TestObjCValueTy).value)
let idValue30 = unsafeBitCast(v, to: UInt.self)
expectNil(d.object(forKey: TestObjCKeyTy(40)))
// NSDictionary can store mixed key types. Swift's Dictionary is typed, but
// when bridged to NSDictionary, it should behave like one, and allow queries
// for mismatched key types.
expectNil(d.object(forKey: TestObjCInvalidKeyTy()))
for _ in 0..<3 {
expectEqual(idValue10, unsafeBitCast(
d.object(forKey: TestObjCKeyTy(10)).map { $0 as AnyObject }, to: UInt.self))
expectEqual(idValue20, unsafeBitCast(
d.object(forKey: TestObjCKeyTy(20)).map { $0 as AnyObject }, to: UInt.self))
expectEqual(idValue30, unsafeBitCast(
d.object(forKey: TestObjCKeyTy(30)).map { $0 as AnyObject }, to: UInt.self))
}
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
var capturedIdentityPairs = Array<(UInt, UInt)>()
for _ in 0..<3 {
let enumerator = d.keyEnumerator()
var dataPairs = Array<(Int, Int)>()
var identityPairs = Array<(UInt, UInt)>()
while let key = enumerator.nextObject() {
let keyObj = key as AnyObject
let value: AnyObject = d.object(forKey: keyObj)! as AnyObject
let dataPair =
((keyObj as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
dataPairs.append(dataPair)
let identityPair =
(unsafeBitCast(keyObj, to: UInt.self),
unsafeBitCast(value, to: UInt.self))
identityPairs.append(identityPair)
}
expectTrue(
equalsUnordered(dataPairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
if capturedIdentityPairs.isEmpty {
capturedIdentityPairs = identityPairs
} else {
expectTrue(equalsUnordered(capturedIdentityPairs, identityPairs))
}
assert(enumerator.nextObject() == nil)
assert(enumerator.nextObject() == nil)
assert(enumerator.nextObject() == nil)
}
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.NextObject_Empty") {
let d = getBridgedEmptyNSDictionary()
let enumerator = d.keyEnumerator()
assert(enumerator.nextObject() == nil)
assert(enumerator.nextObject() == nil)
assert(enumerator.nextObject() == nil)
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromSwift") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration.UseFromObjC") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
checkDictionaryFastEnumerationFromObjC(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.KeyEnumerator.FastEnumeration_Empty") {
let d = getBridgedEmptyNSDictionary()
checkDictionaryFastEnumerationFromSwift(
[], d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
checkDictionaryFastEnumerationFromObjC(
[], d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromSwift") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromObjC") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
checkDictionaryFastEnumerationFromObjC(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration_Empty") {
let d = getBridgedEmptyNSDictionary()
checkDictionaryFastEnumerationFromSwift(
[], d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
checkDictionaryFastEnumerationFromObjC(
[], d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
}
/// Check for buffer overruns/underruns in Swift's
/// `-[NSDictionary getObjects:andKeys:count:]` implementations.
func checkGetObjectsAndKeys(
_ dictionary: NSDictionary,
count: Int,
file: String = #file,
line: UInt = #line) {
let canary = NSObject()
let storageSize = 2 * max(count, dictionary.count) + 2
// Create buffers for storing keys and values at +0 refcounts,
// then call getObjects:andKeys:count: via a shim in
// StdlibUnittestFoundationExtras.
typealias UnmanagedPointer = UnsafeMutablePointer<Unmanaged<AnyObject>>
let keys = UnmanagedPointer.allocate(capacity: storageSize)
keys.initialize(repeating: Unmanaged.passUnretained(canary), count: storageSize)
let values = UnmanagedPointer.allocate(capacity: storageSize)
values.initialize(repeating: Unmanaged.passUnretained(canary), count: storageSize)
keys.withMemoryRebound(to: AnyObject.self, capacity: storageSize) { k in
values.withMemoryRebound(to: AnyObject.self, capacity: storageSize) { v in
dictionary.available_getObjects(
AutoreleasingUnsafeMutablePointer(v),
andKeys: AutoreleasingUnsafeMutablePointer(k),
count: count)
}
}
// Check results.
for i in 0 ..< storageSize {
let key = keys[i].takeUnretainedValue()
let value = values[i].takeUnretainedValue()
if i < min(count, dictionary.count) {
expectTrue(
key !== canary,
"""
Buffer underrun at offset \(i) with count \(count):
keys[\(i)] was left unchanged
""",
file: file, line: line)
expectTrue(
value !== canary,
"""
Buffer underrun at offset \(i) with count \(count):
values[\(i)] was left unchanged
""",
file: file, line: line)
if key !== canary, value !== canary {
autoreleasepoolIfUnoptimizedReturnAutoreleased {
// We need an autorelease pool because objectForKey returns
// autoreleased values.
expectTrue(
value === dictionary.object(forKey: key) as AnyObject,
"""
Inconsistency at offset \(i) with count \(count):
values[\(i)] does not match value for keys[\(i)]
""",
file: file, line: line)
}
}
} else {
expectTrue(
key === canary,
"""
Buffer overrun at offset \(i) with count \(count):
keys[\(i)] was overwritten with value \(key)
""",
file: file, line: line)
expectTrue(
value === canary,
"""
Buffer overrun at offset \(i) with count \(count):
values[\(i)] was overwritten with value \(key)
""",
file: file, line: line)
}
}
keys.deinitialize(count: storageSize) // noop
keys.deallocate()
values.deinitialize(count: storageSize) // noop
values.deallocate()
withExtendedLifetime(canary) {}
// [NSArray getObjects] does not retain the objects, so keep the dictionary alive.
withExtendedLifetime(dictionary) {}
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.getObjects:andKeys:count:") {
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
for count in 0 ..< d.count + 2 {
checkGetObjectsAndKeys(d, count: count)
}
}
DictionaryTestSuite.test("BridgedToObjC.Verbatim.getObjects:andKeys:count:/InvalidCount") {
expectCrashLater()
let d = getBridgedNSDictionaryOfRefTypesBridgedVerbatim()
checkGetObjectsAndKeys(d, count: -1)
}
//===---
// Dictionary -> NSDictionary bridging tests.
//
// Key type and value type are bridged non-verbatim.
//===---
DictionaryTestSuite.test("BridgedToObjC.KeyValue_ValueTypesCustomBridged") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
let enumerator = d.keyEnumerator()
var pairs = Array<(Int, Int)>()
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)! as AnyObject
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromSwift.Partial") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged(
numElements: 9)
checkDictionaryEnumeratorPartialFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030), (40, 1040), (50, 1050),
(60, 1060), (70, 1070), (80, 1080), (90, 1090) ],
d, maxFastEnumerationItems: 5,
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (9, 9))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.KeyEnumerator.FastEnumeration.UseFromObjC") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
checkDictionaryFastEnumerationFromObjC(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d.keyEnumerator() },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromSwift") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromObjC") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
checkDictionaryFastEnumerationFromObjC(
[ (10, 1010), (20, 1020), (30, 1030) ],
d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("BridgedToObjC.Custom.FastEnumeration_Empty") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged(
numElements: 0)
checkDictionaryFastEnumerationFromSwift(
[], d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
checkDictionaryFastEnumerationFromObjC(
[], d, { d },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
}
DictionaryTestSuite.test("BridgedToObjC.Custom.getObjects:andKeys:count:") {
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
for count in 0 ..< d.count + 2 {
checkGetObjectsAndKeys(d, count: count)
}
}
DictionaryTestSuite.test("BridgedToObjC.Custom.getObjects:andKeys:count:/InvalidCount") {
expectCrashLater()
let d = getBridgedNSDictionaryOfKeyValue_ValueTypesCustomBridged()
checkGetObjectsAndKeys(d, count: -1)
}
func getBridgedNSDictionaryOfKey_ValueTypeCustomBridged() -> NSDictionary {
assert(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self))
assert(_isBridgedVerbatimToObjectiveC(TestObjCValueTy.self))
var d = Dictionary<TestBridgedKeyTy, TestObjCValueTy>()
d[TestBridgedKeyTy(10)] = TestObjCValueTy(1010)
d[TestBridgedKeyTy(20)] = TestObjCValueTy(1020)
d[TestBridgedKeyTy(30)] = TestObjCValueTy(1030)
let bridged = convertDictionaryToNSDictionary(d)
assert(isNativeNSDictionary(bridged))
return bridged
}
DictionaryTestSuite.test("BridgedToObjC.Key_ValueTypeCustomBridged") {
let d = getBridgedNSDictionaryOfKey_ValueTypeCustomBridged()
let enumerator = d.keyEnumerator()
var pairs = Array<(Int, Int)>()
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)! as AnyObject
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
func getBridgedNSDictionaryOfValue_ValueTypeCustomBridged() -> NSDictionary {
assert(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self))
assert(!_isBridgedVerbatimToObjectiveC(TestBridgedValueTy.self))
var d = Dictionary<TestObjCKeyTy, TestBridgedValueTy>()
d[TestObjCKeyTy(10)] = TestBridgedValueTy(1010)
d[TestObjCKeyTy(20)] = TestBridgedValueTy(1020)
d[TestObjCKeyTy(30)] = TestBridgedValueTy(1030)
let bridged = convertDictionaryToNSDictionary(d)
assert(isNativeNSDictionary(bridged))
return bridged
}
DictionaryTestSuite.test("BridgedToObjC.Value_ValueTypeCustomBridged") {
let d = getBridgedNSDictionaryOfValue_ValueTypeCustomBridged()
let enumerator = d.keyEnumerator()
var pairs = Array<(Int, Int)>()
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)! as AnyObject
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
expectAutoreleasedKeysAndValues(unopt: (3, 3))
}
//===---
// NSDictionary -> Dictionary -> NSDictionary bridging tests.
//===---
func getRoundtripBridgedNSDictionary() -> NSDictionary {
let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) }
let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) }
let nsd = NSDictionary(objects: values, forKeys: keys)
let d: Dictionary<NSObject, AnyObject> = convertNSDictionaryToDictionary(nsd)
let bridgedBack = convertDictionaryToNSDictionary(d)
assert(isCocoaNSDictionary(bridgedBack))
// FIXME: this should be true.
//assert(unsafeBitCast(nsd, Int.self) == unsafeBitCast(bridgedBack, Int.self))
return bridgedBack
}
DictionaryTestSuite.test("BridgingRoundtrip") {
let d = getRoundtripBridgedNSDictionary()
let enumerator = d.keyEnumerator()
var pairs = Array<(key: Int, value: Int)>()
while let key = enumerator.nextObject() {
let value: AnyObject = d.object(forKey: key)! as AnyObject
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
expectEqualsUnordered([ (10, 1010), (20, 1020), (30, 1030) ], pairs)
}
//===---
// NSDictionary -> Dictionary implicit conversion.
//===---
DictionaryTestSuite.test("NSDictionaryToDictionaryConversion") {
let keys = [ 10, 20, 30 ].map { TestObjCKeyTy($0) }
let values = [ 1010, 1020, 1030 ].map { TestObjCValueTy($0) }
let nsd = NSDictionary(objects: values, forKeys: keys)
let d: Dictionary = nsd as Dictionary
var pairs = Array<(Int, Int)>()
for (key, value) in d {
let kv = ((key as! TestObjCKeyTy).value, (value as! TestObjCValueTy).value)
pairs.append(kv)
}
assert(equalsUnordered(pairs, [ (10, 1010), (20, 1020), (30, 1030) ]))
}
DictionaryTestSuite.test("DictionaryToNSDictionaryConversion") {
var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
checkDictionaryFastEnumerationFromSwift(
[ (10, 1010), (20, 1020), (30, 1030) ],
d as NSDictionary, { d as NSDictionary },
{ ($0 as! TestObjCKeyTy).value },
{ ($0 as! TestObjCValueTy).value })
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
//===---
// Dictionary upcasts
//===---
DictionaryTestSuite.test("DictionaryUpcastEntryPoint") {
var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
var dAsAnyObject: Dictionary<NSObject, AnyObject> = _dictionaryUpCast(d)
assert(dAsAnyObject.count == 3)
var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)]
assert((v! as! TestObjCValueTy).value == 1010)
v = dAsAnyObject[TestObjCKeyTy(20)]
assert((v! as! TestObjCValueTy).value == 1020)
v = dAsAnyObject[TestObjCKeyTy(30)]
assert((v! as! TestObjCValueTy).value == 1030)
}
DictionaryTestSuite.test("DictionaryUpcast") {
var d = Dictionary<TestObjCKeyTy, TestObjCValueTy>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
var dAsAnyObject: Dictionary<NSObject, AnyObject> = d
assert(dAsAnyObject.count == 3)
var v: AnyObject? = dAsAnyObject[TestObjCKeyTy(10)]
assert((v! as! TestObjCValueTy).value == 1010)
v = dAsAnyObject[TestObjCKeyTy(20)]
assert((v! as! TestObjCValueTy).value == 1020)
v = dAsAnyObject[TestObjCKeyTy(30)]
assert((v! as! TestObjCValueTy).value == 1030)
}
DictionaryTestSuite.test("DictionaryUpcastBridgedEntryPoint") {
var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32)
d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010)
d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020)
d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030)
do {
var dOO = d as Dictionary<NSObject, AnyObject>
assert(dOO.count == 3)
var v: AnyObject? = dOO[TestObjCKeyTy(10)]
assert((v! as! TestBridgedValueTy).value == 1010)
v = dOO[TestObjCKeyTy(20)]
assert((v! as! TestBridgedValueTy).value == 1020)
v = dOO[TestObjCKeyTy(30)]
assert((v! as! TestBridgedValueTy).value == 1030)
}
do {
var dOV = d as Dictionary<NSObject, TestBridgedValueTy>
assert(dOV.count == 3)
var v = dOV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dOV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dOV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
}
do {
var dVO = d as Dictionary<TestBridgedKeyTy, AnyObject>
assert(dVO.count == 3)
var v: AnyObject? = dVO[TestBridgedKeyTy(10)]
assert((v! as! TestBridgedValueTy).value == 1010)
v = dVO[TestBridgedKeyTy(20)]
assert((v! as! TestBridgedValueTy).value == 1020)
v = dVO[TestBridgedKeyTy(30)]
assert((v! as! TestBridgedValueTy).value == 1030)
}
}
DictionaryTestSuite.test("DictionaryUpcastBridged") {
var d = Dictionary<TestBridgedKeyTy, TestBridgedValueTy>(minimumCapacity: 32)
d[TestBridgedKeyTy(10)] = TestBridgedValueTy(1010)
d[TestBridgedKeyTy(20)] = TestBridgedValueTy(1020)
d[TestBridgedKeyTy(30)] = TestBridgedValueTy(1030)
do {
var dOO = d as Dictionary<NSObject, AnyObject>
assert(dOO.count == 3)
var v: AnyObject? = dOO[TestObjCKeyTy(10)]
assert((v! as! TestBridgedValueTy).value == 1010)
v = dOO[TestObjCKeyTy(20)]
assert((v! as! TestBridgedValueTy).value == 1020)
v = dOO[TestObjCKeyTy(30)]
assert((v! as! TestBridgedValueTy).value == 1030)
}
do {
var dOV = d as Dictionary<NSObject, TestBridgedValueTy>
assert(dOV.count == 3)
var v = dOV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dOV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dOV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
}
do {
var dVO = d as Dictionary<TestBridgedKeyTy, AnyObject>
assert(dVO.count == 3)
var v: AnyObject? = dVO[TestBridgedKeyTy(10)]
assert((v! as! TestBridgedValueTy).value == 1010)
v = dVO[TestBridgedKeyTy(20)]
assert((v! as! TestBridgedValueTy).value == 1020)
v = dVO[TestBridgedKeyTy(30)]
assert((v! as! TestBridgedValueTy).value == 1030)
}
}
//===---
// Dictionary downcasts
//===---
DictionaryTestSuite.test("DictionaryDowncastEntryPoint") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
let dCC: Dictionary<TestObjCKeyTy, TestObjCValueTy> = _dictionaryDownCast(d)
assert(dCC.count == 3)
var v = dCC[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCC[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCC[TestObjCKeyTy(30)]
assert(v!.value == 1030)
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("DictionaryDowncast") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
let dCC = d as! Dictionary<TestObjCKeyTy, TestObjCValueTy>
assert(dCC.count == 3)
var v = dCC[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCC[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCC[TestObjCKeyTy(30)]
assert(v!.value == 1030)
expectAutoreleasedKeysAndValues(unopt: (0, 3))
}
DictionaryTestSuite.test("DictionaryDowncastConditionalEntryPoint") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
if let dCC
= _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? {
assert(dCC.count == 3)
var v = dCC[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCC[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCC[TestObjCKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Unsuccessful downcast
d["hello" as NSString] = 17 as NSNumber
if let _
= _dictionaryDownCastConditional(d) as Dictionary<TestObjCKeyTy, TestObjCValueTy>? {
assert(false)
}
}
DictionaryTestSuite.test("DictionaryDowncastConditional") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
if let dCC = d as? Dictionary<TestObjCKeyTy, TestObjCValueTy> {
assert(dCC.count == 3)
var v = dCC[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCC[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCC[TestObjCKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Unsuccessful downcast
d["hello" as NSString] = 17 as NSNumber
if d is Dictionary<TestObjCKeyTy, TestObjCValueTy> {
assert(false)
}
}
DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCEntryPoint") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
let dCV = d as! Dictionary<TestObjCKeyTy, TestBridgedValueTy>
do {
assert(dCV.count == 3)
var v = dCV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
}
// Successful downcast.
let dVC = d as! Dictionary<TestBridgedKeyTy, TestObjCValueTy>
do {
assert(dVC.count == 3)
var v = dVC[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVC[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVC[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
}
// Successful downcast.
let dVV = d as! Dictionary<TestBridgedKeyTy, TestBridgedValueTy>
do {
assert(dVV.count == 3)
var v = dVV[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVV[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVV[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
}
}
DictionaryTestSuite.test("DictionaryBridgeFromObjectiveC") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
let dCV = d as! Dictionary<TestObjCKeyTy, TestBridgedValueTy>
do {
assert(dCV.count == 3)
var v = dCV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
}
// Successful downcast.
let dVC = d as! Dictionary<TestBridgedKeyTy, TestObjCValueTy>
do {
assert(dVC.count == 3)
var v = dVC[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVC[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVC[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
}
// Successful downcast.
let dVV = d as! Dictionary<TestBridgedKeyTy, TestBridgedValueTy>
do {
assert(dVV.count == 3)
var v = dVV[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVV[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVV[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
}
}
DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditionalEntryPoint") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
if let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> {
assert(dCV.count == 3)
var v = dCV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Successful downcast.
if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> {
assert(dVC.count == 3)
var v = dVC[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVC[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVC[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Successful downcast.
if let dVV = d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
assert(dVV.count == 3)
var v = dVV[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVV[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVV[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Unsuccessful downcasts
d["hello" as NSString] = 17 as NSNumber
if let _ = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> {
assert(false)
}
if let _
= d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> {
assert(false)
}
if let _
= d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
assert(false)
}
}
DictionaryTestSuite.test("DictionaryBridgeFromObjectiveCConditional") {
var d = Dictionary<NSObject, AnyObject>(minimumCapacity: 32)
d[TestObjCKeyTy(10)] = TestObjCValueTy(1010)
d[TestObjCKeyTy(20)] = TestObjCValueTy(1020)
d[TestObjCKeyTy(30)] = TestObjCValueTy(1030)
// Successful downcast.
if let dCV = d as? Dictionary<TestObjCKeyTy, TestBridgedValueTy> {
assert(dCV.count == 3)
var v = dCV[TestObjCKeyTy(10)]
assert(v!.value == 1010)
v = dCV[TestObjCKeyTy(20)]
assert(v!.value == 1020)
v = dCV[TestObjCKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Successful downcast.
if let dVC = d as? Dictionary<TestBridgedKeyTy, TestObjCValueTy> {
assert(dVC.count == 3)
var v = dVC[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVC[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVC[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Successful downcast.
if let dVV = d as? Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
assert(dVV.count == 3)
var v = dVV[TestBridgedKeyTy(10)]
assert(v!.value == 1010)
v = dVV[TestBridgedKeyTy(20)]
assert(v!.value == 1020)
v = dVV[TestBridgedKeyTy(30)]
assert(v!.value == 1030)
} else {
assert(false)
}
// Unsuccessful downcasts
d["hello" as NSString] = 17 as NSNumber
if d is Dictionary<TestObjCKeyTy, TestBridgedValueTy> {
assert(false)
}
if d is Dictionary<TestBridgedKeyTy, TestObjCValueTy> {
assert(false)
}
if d is Dictionary<TestBridgedKeyTy, TestBridgedValueTy> {
assert(false)
}
}
#endif // _runtime(_ObjC)
//===---
// Tests for APIs implemented strictly based on public interface. We only need
// to test them once, not for every storage type.
//===---
func getDerivedAPIsDictionary() -> Dictionary<Int, Int> {
var d = Dictionary<Int, Int>(minimumCapacity: 10)
d[10] = 1010
d[20] = 1020
d[30] = 1030
return d
}
var DictionaryDerivedAPIs = TestSuite("DictionaryDerivedAPIs")
DictionaryDerivedAPIs.test("isEmpty") {
do {
let empty = Dictionary<Int, Int>()
expectTrue(empty.isEmpty)
}
do {
let d = getDerivedAPIsDictionary()
expectFalse(d.isEmpty)
}
}
#if _runtime(_ObjC)
@objc
class MockDictionaryWithCustomCount : NSDictionary {
init(count: Int) {
self._count = count
super.init()
}
override init() {
expectUnreachable()
super.init()
}
override init(
objects: UnsafePointer<AnyObject>?,
forKeys keys: UnsafePointer<NSCopying>?,
count: Int) {
expectUnreachable()
super.init(objects: objects, forKeys: keys, count: count)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) not implemented by MockDictionaryWithCustomCount")
}
@objc(copyWithZone:)
override func copy(with zone: NSZone?) -> Any {
// Ensure that copying this dictionary produces an object of the same
// dynamic type.
return self
}
override func object(forKey aKey: Any) -> Any? {
expectUnreachable()
return NSObject()
}
override var count: Int {
MockDictionaryWithCustomCount.timesCountWasCalled += 1
return _count
}
var _count: Int = 0
static var timesCountWasCalled = 0
}
func getMockDictionaryWithCustomCount(count: Int)
-> Dictionary<NSObject, AnyObject> {
return MockDictionaryWithCustomCount(count: count) as Dictionary
}
func callGenericIsEmpty<C : Collection>(_ collection: C) -> Bool {
return collection.isEmpty
}
DictionaryDerivedAPIs.test("isEmpty/ImplementationIsCustomized") {
do {
let d = getMockDictionaryWithCustomCount(count: 0)
MockDictionaryWithCustomCount.timesCountWasCalled = 0
expectTrue(d.isEmpty)
expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled)
}
do {
let d = getMockDictionaryWithCustomCount(count: 0)
MockDictionaryWithCustomCount.timesCountWasCalled = 0
expectTrue(callGenericIsEmpty(d))
expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled)
}
do {
let d = getMockDictionaryWithCustomCount(count: 4)
MockDictionaryWithCustomCount.timesCountWasCalled = 0
expectFalse(d.isEmpty)
expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled)
}
do {
let d = getMockDictionaryWithCustomCount(count: 4)
MockDictionaryWithCustomCount.timesCountWasCalled = 0
expectFalse(callGenericIsEmpty(d))
expectEqual(1, MockDictionaryWithCustomCount.timesCountWasCalled)
}
}
#endif // _runtime(_ObjC)
DictionaryDerivedAPIs.test("keys") {
do {
let empty = Dictionary<Int, Int>()
let keys = Array(empty.keys)
expectTrue(equalsUnordered(keys, []))
}
do {
let d = getDerivedAPIsDictionary()
let keys = Array(d.keys)
expectTrue(equalsUnordered(keys, [ 10, 20, 30 ]))
}
}
DictionaryDerivedAPIs.test("values") {
do {
let empty = Dictionary<Int, Int>()
let values = Array(empty.values)
expectTrue(equalsUnordered(values, []))
}
do {
var d = getDerivedAPIsDictionary()
var values = Array(d.values)
expectTrue(equalsUnordered(values, [ 1010, 1020, 1030 ]))
d[11] = 1010
values = Array(d.values)
expectTrue(equalsUnordered(values, [ 1010, 1010, 1020, 1030 ]))
}
}
#if _runtime(_ObjC)
var ObjCThunks = TestSuite("ObjCThunks")
class ObjCThunksHelper : NSObject {
@objc dynamic func acceptArrayBridgedVerbatim(_ array: [TestObjCValueTy]) {
expectEqual(10, array[0].value)
expectEqual(20, array[1].value)
expectEqual(30, array[2].value)
}
@objc dynamic func acceptArrayBridgedNonverbatim(_ array: [TestBridgedValueTy]) {
// Cannot check elements because doing so would bridge them.
expectEqual(3, array.count)
}
@objc dynamic func returnArrayBridgedVerbatim() -> [TestObjCValueTy] {
return [ TestObjCValueTy(10), TestObjCValueTy(20),
TestObjCValueTy(30) ]
}
@objc dynamic func returnArrayBridgedNonverbatim() -> [TestBridgedValueTy] {
return [ TestBridgedValueTy(10), TestBridgedValueTy(20),
TestBridgedValueTy(30) ]
}
@objc dynamic func acceptDictionaryBridgedVerbatim(
_ d: [TestObjCKeyTy : TestObjCValueTy]) {
expectEqual(3, d.count)
expectEqual(1010, d[TestObjCKeyTy(10)]!.value)
expectEqual(1020, d[TestObjCKeyTy(20)]!.value)
expectEqual(1030, d[TestObjCKeyTy(30)]!.value)
}
@objc dynamic func acceptDictionaryBridgedNonverbatim(
_ d: [TestBridgedKeyTy : TestBridgedValueTy]) {
expectEqual(3, d.count)
// Cannot check elements because doing so would bridge them.
}
@objc dynamic func returnDictionaryBridgedVerbatim() ->
[TestObjCKeyTy : TestObjCValueTy] {
return [
TestObjCKeyTy(10): TestObjCValueTy(1010),
TestObjCKeyTy(20): TestObjCValueTy(1020),
TestObjCKeyTy(30): TestObjCValueTy(1030),
]
}
@objc dynamic func returnDictionaryBridgedNonverbatim() ->
[TestBridgedKeyTy : TestBridgedValueTy] {
return [
TestBridgedKeyTy(10): TestBridgedValueTy(1010),
TestBridgedKeyTy(20): TestBridgedValueTy(1020),
TestBridgedKeyTy(30): TestBridgedValueTy(1030),
]
}
}
ObjCThunks.test("Array/Accept") {
let helper = ObjCThunksHelper()
do {
helper.acceptArrayBridgedVerbatim(
[ TestObjCValueTy(10), TestObjCValueTy(20), TestObjCValueTy(30) ])
}
do {
TestBridgedValueTy.bridgeOperations = 0
helper.acceptArrayBridgedNonverbatim(
[ TestBridgedValueTy(10), TestBridgedValueTy(20),
TestBridgedValueTy(30) ])
expectEqual(0, TestBridgedValueTy.bridgeOperations)
}
}
ObjCThunks.test("Array/Return") {
let helper = ObjCThunksHelper()
do {
let a = helper.returnArrayBridgedVerbatim()
expectEqual(10, a[0].value)
expectEqual(20, a[1].value)
expectEqual(30, a[2].value)
}
do {
TestBridgedValueTy.bridgeOperations = 0
let a = helper.returnArrayBridgedNonverbatim()
expectEqual(0, TestBridgedValueTy.bridgeOperations)
TestBridgedValueTy.bridgeOperations = 0
expectEqual(10, a[0].value)
expectEqual(20, a[1].value)
expectEqual(30, a[2].value)
expectEqual(0, TestBridgedValueTy.bridgeOperations)
}
}
ObjCThunks.test("Dictionary/Accept") {
let helper = ObjCThunksHelper()
do {
helper.acceptDictionaryBridgedVerbatim(
[ TestObjCKeyTy(10): TestObjCValueTy(1010),
TestObjCKeyTy(20): TestObjCValueTy(1020),
TestObjCKeyTy(30): TestObjCValueTy(1030) ])
}
do {
TestBridgedKeyTy.bridgeOperations = 0
TestBridgedValueTy.bridgeOperations = 0
helper.acceptDictionaryBridgedNonverbatim(
[ TestBridgedKeyTy(10): TestBridgedValueTy(1010),
TestBridgedKeyTy(20): TestBridgedValueTy(1020),
TestBridgedKeyTy(30): TestBridgedValueTy(1030) ])
expectEqual(0, TestBridgedKeyTy.bridgeOperations)
expectEqual(0, TestBridgedValueTy.bridgeOperations)
}
}
ObjCThunks.test("Dictionary/Return") {
let helper = ObjCThunksHelper()
do {
let d = helper.returnDictionaryBridgedVerbatim()
expectEqual(3, d.count)
expectEqual(1010, d[TestObjCKeyTy(10)]!.value)
expectEqual(1020, d[TestObjCKeyTy(20)]!.value)
expectEqual(1030, d[TestObjCKeyTy(30)]!.value)
}
do {
TestBridgedKeyTy.bridgeOperations = 0
TestBridgedValueTy.bridgeOperations = 0
let d = helper.returnDictionaryBridgedNonverbatim()
expectEqual(0, TestBridgedKeyTy.bridgeOperations)
expectEqual(0, TestBridgedValueTy.bridgeOperations)
TestBridgedKeyTy.bridgeOperations = 0
TestBridgedValueTy.bridgeOperations = 0
expectEqual(3, d.count)
expectEqual(1010, d[TestBridgedKeyTy(10)]!.value)
expectEqual(1020, d[TestBridgedKeyTy(20)]!.value)
expectEqual(1030, d[TestBridgedKeyTy(30)]!.value)
expectEqual(0, TestBridgedKeyTy.bridgeOperations)
expectEqual(0, TestBridgedValueTy.bridgeOperations)
}
}
#endif // _runtime(_ObjC)
//===---
// Check that iterators traverse a snapshot of the collection.
//===---
DictionaryTestSuite.test("mutationDoesNotAffectIterator/subscript/store") {
var dict = getDerivedAPIsDictionary()
let iter = dict.makeIterator()
dict[10] = 1011
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,1") {
var dict = getDerivedAPIsDictionary()
let iter = dict.makeIterator()
expectEqual(1010, dict.removeValue(forKey: 10))
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
DictionaryTestSuite.test("mutationDoesNotAffectIterator/removeValueForKey,all") {
var dict = getDerivedAPIsDictionary()
let iter = dict.makeIterator()
expectEqual(1010, dict.removeValue(forKey: 10))
expectEqual(1020, dict.removeValue(forKey: 20))
expectEqual(1030, dict.removeValue(forKey: 30))
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
DictionaryTestSuite.test(
"mutationDoesNotAffectIterator/removeAll,keepingCapacity=false") {
var dict = getDerivedAPIsDictionary()
let iter = dict.makeIterator()
dict.removeAll(keepingCapacity: false)
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
DictionaryTestSuite.test(
"mutationDoesNotAffectIterator/removeAll,keepingCapacity=true") {
var dict = getDerivedAPIsDictionary()
let iter = dict.makeIterator()
dict.removeAll(keepingCapacity: true)
expectEqualsUnordered(
[ (10, 1010), (20, 1020), (30, 1030) ],
Array(IteratorSequence(iter)))
}
//===---
// Misc tests.
//===---
DictionaryTestSuite.test("misc") {
do {
// Dictionary literal
var dict = ["Hello": 1, "World": 2]
// Insertion
dict["Swift"] = 3
// Access
expectEqual(1, dict["Hello"])
expectEqual(2, dict["World"])
expectEqual(3, dict["Swift"])
expectNil(dict["Universe"])
// Overwriting existing value
dict["Hello"] = 0
expectEqual(0, dict["Hello"])
expectEqual(2, dict["World"])
expectEqual(3, dict["Swift"])
expectNil(dict["Universe"])
}
do {
// Dictionaries with other types
var d = [ 1.2: 1, 2.6: 2 ]
d[3.3] = 3
expectEqual(1, d[1.2])
expectEqual(2, d[2.6])
expectEqual(3, d[3.3])
}
do {
var d = Dictionary<String, Int>(minimumCapacity: 13)
d["one"] = 1
d["two"] = 2
d["three"] = 3
d["four"] = 4
d["five"] = 5
expectEqual(1, d["one"])
expectEqual(2, d["two"])
expectEqual(3, d["three"])
expectEqual(4, d["four"])
expectEqual(5, d["five"])
// Iterate over (key, value) tuples as a silly copy
var d3 = Dictionary<String,Int>(minimumCapacity: 13)
for (k, v) in d {
d3[k] = v
}
expectEqual(1, d3["one"])
expectEqual(2, d3["two"])
expectEqual(3, d3["three"])
expectEqual(4, d3["four"])
expectEqual(5, d3["five"])
expectEqual(3, d.values[d.keys.firstIndex(of: "three")!])
expectEqual(4, d.values[d.keys.firstIndex(of: "four")!])
expectEqual(3, d3.values[d3.keys.firstIndex(of: "three")!])
expectEqual(4, d3.values[d3.keys.firstIndex(of: "four")!])
}
}
#if _runtime(_ObjC)
DictionaryTestSuite.test("dropsBridgedCache") {
// rdar://problem/18544533
// Previously this code would segfault due to a double free in the Dictionary
// implementation.
// This test will only fail in address sanitizer.
var dict = [0:10]
do {
let bridged: NSDictionary = dict as NSDictionary
expectEqual(10, bridged[0 as NSNumber] as! Int)
}
dict[0] = 11
do {
let bridged: NSDictionary = dict as NSDictionary
expectEqual(11, bridged[0 as NSNumber] as! Int)
}
}
DictionaryTestSuite.test("getObjects:andKeys:count:") {
let native = [1: "one", 2: "two"] as Dictionary<Int, String>
let d = native as NSDictionary
let keys = UnsafeMutableBufferPointer(
start: UnsafeMutablePointer<NSNumber>.allocate(capacity: 2), count: 2)
let values = UnsafeMutableBufferPointer(
start: UnsafeMutablePointer<NSString>.allocate(capacity: 2), count: 2)
let kp = AutoreleasingUnsafeMutablePointer<AnyObject?>(keys.baseAddress!)
let vp = AutoreleasingUnsafeMutablePointer<AnyObject?>(values.baseAddress!)
let null: AutoreleasingUnsafeMutablePointer<AnyObject?>? = nil
let expectedKeys: [NSNumber]
let expectedValues: [NSString]
if native.first?.key == 1 {
expectedKeys = [1, 2]
expectedValues = ["one", "two"]
} else {
expectedKeys = [2, 1]
expectedValues = ["two", "one"]
}
d.available_getObjects(null, andKeys: null, count: 2) // don't segfault
d.available_getObjects(null, andKeys: kp, count: 2)
expectEqual(expectedKeys, Array(keys))
d.available_getObjects(vp, andKeys: null, count: 2)
expectEqual(expectedValues, Array(values))
d.available_getObjects(vp, andKeys: kp, count: 2)
expectEqual(expectedKeys, Array(keys))
expectEqual(expectedValues, Array(values))
// [NSArray getObjects] does not retain the objects, so keep the dictionary alive.
withExtendedLifetime(d) {}
}
#endif
DictionaryTestSuite.test("popFirst") {
// Empty
do {
var d = [Int: Int]()
let popped = d.popFirst()
expectNil(popped)
}
do {
var popped = [(Int, Int)]()
var d: [Int: Int] = [
1010: 1010,
2020: 2020,
3030: 3030,
]
let expected = [(1010, 1010), (2020, 2020), (3030, 3030)]
while let element = d.popFirst() {
popped.append(element)
}
// Note that removing an element may reorder remaining items, so we
// can't compare ordering here.
popped.sort(by: { $0.0 < $1.0 })
expectEqualSequence(expected, popped) {
(lhs: (Int, Int), rhs: (Int, Int)) -> Bool in
lhs.0 == rhs.0 && lhs.1 == rhs.1
}
expectTrue(d.isEmpty)
}
}
DictionaryTestSuite.test("removeAt") {
// Test removing from the startIndex, the middle, and the end of a dictionary.
for i in 1...3 {
var d: [Int: Int] = [
10: 1010,
20: 2020,
30: 3030,
]
let removed = d.remove(at: d.index(forKey: i*10)!)
expectEqual(i*10, removed.0)
expectEqual(i*1010, removed.1)
expectEqual(2, d.count)
expectNil(d.index(forKey: i))
let origKeys: [Int] = [10, 20, 30]
expectEqual(origKeys.filter { $0 != (i*10) }, d.keys.sorted())
}
}
DictionaryTestSuite.test("updateValue") {
let key1 = TestKeyTy(42)
let key2 = TestKeyTy(42)
let value1 = TestValueTy(1)
let value2 = TestValueTy(2)
var d: [TestKeyTy: TestValueTy] = [:]
expectNil(d.updateValue(value1, forKey: key1))
expectEqual(d.count, 1)
let index1 = d.index(forKey: key2)
expectNotNil(index1)
expectTrue(d[index1!].key === key1)
expectTrue(d[index1!].value === value1)
expectTrue(d.updateValue(value2, forKey: key2) === value1)
expectEqual(d.count, 1)
let index2 = d.index(forKey: key2)
expectEqual(index1, index2)
// We expect updateValue to keep the original key in place.
expectTrue(d[index2!].key === key1) // Not key2
expectTrue(d[index2!].value === value2)
}
DictionaryTestSuite.test("localHashSeeds") {
// With global hashing, copying elements in hash order between hash tables
// can become quadratic. (See https://bugs.swift.org/browse/SR-3268)
//
// We defeat this by mixing the local storage capacity into the global hash
// seed, thereby breaking the correlation between bucket indices across
// hash tables with different sizes.
//
// Verify this works by copying a small sampling of elements near the
// beginning of a large Dictionary into a smaller one. If the elements end up
// in the same order in the smaller Dictionary, then that indicates we do not
// use size-dependent seeding.
let count = 100_000
// Set a large table size to reduce frequency/length of collision chains.
var large = [Int: Int](minimumCapacity: 4 * count)
for i in 1 ..< count {
large[i] = 2 * i
}
let bunch = count / 100 // 1 percent's worth of elements
// Copy two bunches of elements into another dictionary that's half the size
// of the first. We start after the initial bunch because the hash table may
// begin with collided elements wrapped over from the end, and these would be
// sorted into irregular slots in the smaller table.
let slice = large.prefix(3 * bunch).dropFirst(bunch)
var small = [Int: Int](minimumCapacity: large.capacity / 2)
expectLT(small.capacity, large.capacity)
for (key, value) in slice {
small[key] = value
}
// Compare the second halves of the new dictionary and the slice. Ignore the
// first halves; the first few elements may not be in the correct order if we
// happened to start copying from the middle of a collision chain.
let smallKeys = small.dropFirst(bunch).map { $0.key }
let sliceKeys = slice.dropFirst(bunch).map { $0.key }
// If this test fails, there is a problem with local hash seeding.
expectFalse(smallKeys.elementsEqual(sliceKeys))
}
DictionaryTestSuite.test("Hashable") {
let d1: [Dictionary<Int, String>] = [
[1: "meow", 2: "meow", 3: "meow"],
[1: "meow", 2: "meow", 3: "mooo"],
[1: "meow", 2: "meow", 4: "meow"],
[1: "meow", 2: "meow", 4: "mooo"]]
checkHashable(d1, equalityOracle: { $0 == $1 })
let d2: [Dictionary<Int, Dictionary<Int, String>>] = [
[1: [2: "meow"]],
[2: [1: "meow"]],
[2: [2: "meow"]],
[1: [1: "meow"]],
[2: [2: "mooo"]],
[2: [:]],
[:]]
checkHashable(d2, equalityOracle: { $0 == $1 })
// Dictionary should hash itself in a way that ensures instances get correctly
// delineated even when they are nested in other commutative collections.
// These are different Sets, so they should produce different hashes:
let remix: [Set<Dictionary<String, Int>>] = [
[["Blanche": 1, "Rose": 2], ["Dorothy": 3, "Sophia": 4]],
[["Blanche": 1, "Dorothy": 3], ["Rose": 2, "Sophia": 4]],
[["Blanche": 1, "Sophia": 4], ["Rose": 2, "Dorothy": 3]]
]
checkHashable(remix, equalityOracle: { $0 == $1 })
// Dictionary ordering is not guaranteed to be consistent across equal
// instances. In particular, ordering is highly sensitive to the size of the
// allocated storage buffer. Generate a few copies of the same dictionary with
// different capacities, and verify that they compare and hash the same.
var variants: [Dictionary<String, Int>] = []
for i in 4 ..< 12 {
var set: Dictionary<String, Int> = [
"one": 1, "two": 2,
"three": 3, "four": 4,
"five": 5, "six": 6]
set.reserveCapacity(1 << i)
variants.append(set)
}
checkHashable(variants, equalityOracle: { _, _ in true })
}
DictionaryTestSuite.test("Values.MutationDoesNotInvalidateIndices.Native") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d[i], (key: 20, value: 1020))
var expected = 1020
for _ in 0 ..< 100 {
expected += 1
d.values[i] += 1
expectEqual(d[i], (key: 20, value: expected))
}
}
#if _runtime(_ObjC)
DictionaryTestSuite.test("Values.MutationDoesNotInvalidateIndices.Bridged") {
let objects: [NSNumber] = [1, 2, 3, 4]
let keys: [NSString] = ["Blanche", "Rose", "Dorothy", "Sophia"]
let ns = NSDictionary(objects: objects, forKeys: keys)
var d = ns as! Dictionary<NSString, NSNumber>
let i = d.index(forKey: "Rose")!
expectEqual(d[i].key, "Rose")
expectEqual(d[i].value, 2 as NSNumber)
// Mutating a value through the Values view will convert the bridged
// NSDictionary instance to native Dictionary storage. However, Values is a
// MutableCollection, so doing so must not invalidate existing indices.
d.values[i] = 20 as NSNumber
// The old Cocoa-based index must still work with the new dictionary.
expectEqual(d.values[i], 20 as NSNumber)
let i2 = d.index(forKey: "Rose")
// You should also be able to advance Cocoa indices.
let j = d.index(after: i)
expectLT(i, j)
// Unfortunately, Cocoa and Native indices aren't comparable, so the
// Collection conformance is not quite perfect.
expectCrash() {
print(i == i2)
}
}
#endif
DictionaryTestSuite.test("Values.Subscript.Uniqueness") {
var d = getCOWSlowEquatableDictionary()
let i = d.index(forKey: TestKeyTy(20))!
expectUnique(&d.values[i])
}
DictionaryTestSuite.test("Values.Subscript.Modify") {
var d = getCOWSlowEquatableDictionary()
let i = d.index(forKey: TestKeyTy(20))!
bumpValue(&d.values[i])
expectEqual(TestEquatableValueTy(1021), d[TestKeyTy(20)])
}
DictionaryTestSuite.test("Values.Subscript.ModifyThrow") {
var d = getCOWSlowEquatableDictionary()
let i = d.index(forKey: TestKeyTy(20))!
do {
try bumpValueAndThrow(&d.values[i])
expectTrue(false, "Did not throw")
} catch {
expectTrue(error is TestError)
}
expectEqual(TestEquatableValueTy(1021), d[TestKeyTy(20)])
}
DictionaryTestSuite.test("RemoveAt.InvalidatesIndices") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let j = d.index(forKey: 10)!
d.remove(at: j)
expectCrashLater()
_ = d[i]
}
DictionaryTestSuite.test("RemoveValueForKey.InvalidatesIndices") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
d.removeValue(forKey: 10)
expectCrashLater()
_ = d[i]
}
DictionaryTestSuite.test("ResizeOnInsertion.InvalidatesIndices") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d[i], (key: 20, value: 1020))
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d[i], (key: 20, value: 1020))
d[0] = 0
expectCrashLater()
_ = d[i]
}
DictionaryTestSuite.test("ResizeOnUpdate.InvalidatesIndices") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d[i], (key: 20, value: 1020))
for i in 0 ..< (d.capacity - d.count) {
d.updateValue(100 + i, forKey: 100 + i)
}
expectEqual(d[i], (key: 20, value: 1020))
d.updateValue(0, forKey: 0)
expectCrashLater()
_ = d[i]
}
DictionaryTestSuite.test("RemoveAll.InvalidatesIndices") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d[i], (key: 20, value: 1020))
d.removeAll(keepingCapacity: true)
expectCrashLater()
_ = d[i]
}
DictionaryTestSuite.test("ReserveCapacity.InvalidatesIndices") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d[i], (key: 20, value: 1020))
d.reserveCapacity(0)
expectEqual(d[i], (key: 20, value: 1020))
d.reserveCapacity(d.capacity)
expectEqual(d[i], (key: 20, value: 1020))
d.reserveCapacity(d.capacity * 10)
expectCrashLater()
_ = d[i]
}
DictionaryTestSuite.test("IndexValidation.Subscript.Getter.AcrossInstances") {
// The mutation count may happen to be the same across any two dictionaries.
// The probability of this is low, but it could happen -- so check a bunch of
// these cases at once; a trap will definitely occur at least once.
let dicts = (0 ..< 10).map { _ in getCOWFastDictionary() }
let indices = dicts.map { $0.index(forKey: 20)! }
let d = getCOWFastDictionary()
expectCrashLater()
for i in indices {
_ = d[i]
}
_fixLifetime(dicts)
}
DictionaryTestSuite.test("IndexValidation.Subscript.Getter.AfterRemoval") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d[i], (key: 20, value: 1020))
d.removeValue(forKey: 10)
expectCrashLater()
_ = d[i]
}
DictionaryTestSuite.test("IndexValidation.Subscript.Getter.AfterGrow") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let identifier = d._rawIdentifier()
expectEqual(d[i], (key: 20, value: 1020))
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d._rawIdentifier(), identifier)
expectEqual(d.count, d.capacity)
expectEqual(d[i], (key: 20, value: 1020))
d[0] = 0
expectNotEqual(d._rawIdentifier(), identifier)
expectCrashLater()
_ = d[i]
}
DictionaryTestSuite.test("IndexValidation.KeysSubscript.Getter.AfterRemoval") {
var d = getCOWFastDictionary()
let i = d.keys.firstIndex(of: 20)!
expectEqual(d.keys[i], 20)
expectEqual(d[i], (key: 20, value: 1020))
d.removeValue(forKey: 10)
expectCrashLater()
_ = d.keys[i]
}
DictionaryTestSuite.test("IndexValidation.KeysSubscript.Getter.AfterGrow") {
var d = getCOWFastDictionary()
let i = d.keys.firstIndex(of: 20)!
let identifier = d._rawIdentifier()
expectEqual(d.keys[i], 20)
expectEqual(d[i], (key: 20, value: 1020))
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d._rawIdentifier(), identifier)
expectEqual(d.count, d.capacity)
expectEqual(d.keys[i], 20)
expectEqual(d[i], (key: 20, value: 1020))
d[0] = 0
expectNotEqual(d._rawIdentifier(), identifier)
expectCrashLater()
_ = d.keys[i]
}
DictionaryTestSuite.test("IndexValidation.ValuesSubscript.Getter.AfterRemoval") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d.values[i], 1020)
expectEqual(d[i], (key: 20, value: 1020))
d.removeValue(forKey: 10)
expectCrashLater()
_ = d.values[i]
}
DictionaryTestSuite.test("IndexValidation.ValuesSubscript.Getter.AfterGrow") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let identifier = d._rawIdentifier()
expectEqual(d.values[i], 1020)
expectEqual(d[i], (key: 20, value: 1020))
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d._rawIdentifier(), identifier)
expectEqual(d.count, d.capacity)
expectEqual(d.values[i], 1020)
expectEqual(d[i], (key: 20, value: 1020))
d[0] = 0
expectNotEqual(d._rawIdentifier(), identifier)
expectCrashLater()
_ = d.values[i]
}
DictionaryTestSuite.test("IndexValidation.ValuesSubscript.Setter.AfterRemoval") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d.values[i], 1020)
expectEqual(d[i], (key: 20, value: 1020))
d.values[i] = 1021
expectEqual(d.values[i], 1021)
expectEqual(d[i], (key: 20, value: 1021))
d.removeValue(forKey: 10)
expectCrashLater()
d.values[i] = 1022
}
DictionaryTestSuite.test("IndexValidation.ValuesSubscript.Setter.AfterGrow") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let identifier = d._rawIdentifier()
expectEqual(d.values[i], 1020)
expectEqual(d[i], (key: 20, value: 1020))
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d._rawIdentifier(), identifier)
expectEqual(d.count, d.capacity)
d.values[i] = 1021
expectEqual(d.values[i], 1021)
expectEqual(d[i], (key: 20, value: 1021))
d[0] = 0
expectNotEqual(d._rawIdentifier(), identifier)
expectCrashLater()
d.values[i] = 1022
}
DictionaryTestSuite.test("IndexValidation.ValuesSubscript.Modify.AfterRemoval") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d.values[i], 1020)
expectEqual(d[i], (key: 20, value: 1020))
d.values[i] += 1
expectEqual(d.values[i], 1021)
expectEqual(d[i], (key: 20, value: 1021))
d.removeValue(forKey: 10)
expectCrashLater()
d.values[i] += 1
}
DictionaryTestSuite.test("IndexValidation.ValuesSubscript.Modify.AfterGrow") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let identifier = d._rawIdentifier()
expectEqual(d.values[i], 1020)
expectEqual(d[i], (key: 20, value: 1020))
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d._rawIdentifier(), identifier)
expectEqual(d.count, d.capacity)
d.values[i] += 1
expectEqual(d.values[i], 1021)
expectEqual(d[i], (key: 20, value: 1021))
d[0] = 0
expectNotEqual(d._rawIdentifier(), identifier)
expectCrashLater()
d.values[i] += 1
}
DictionaryTestSuite.test("IndexValidation.RangeSubscript.AfterRemoval") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let j = d.index(after: i)
expectTrue(i < j)
d.removeValue(forKey: 10)
expectTrue(i < j)
expectCrashLater()
_ = d[i..<j]
}
DictionaryTestSuite.test("IndexValidation.RangeSubscript.AfterGrow") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let j = d.index(after: i)
expectTrue(i < j)
let identifier = d._rawIdentifier()
expectEqual(d[i], (key: 20, value: 1020))
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d._rawIdentifier(), identifier)
expectEqual(d.count, d.capacity)
expectTrue(i < j)
d[0] = 0
expectNotEqual(d._rawIdentifier(), identifier)
expectTrue(i < j)
expectCrashLater()
_ = d[i..<j]
}
DictionaryTestSuite.test("IndexValidation.KeysRangeSubscript.AfterRemoval") {
var d = getCOWFastDictionary()
let i = d.keys.firstIndex(of: 20)!
let j = d.index(after: i)
expectTrue(i < j)
d.removeValue(forKey: 10)
expectTrue(i < j)
expectCrashLater()
_ = d.keys[i..<j]
}
DictionaryTestSuite.test("IndexValidation.KeysRangeSubscript.AfterGrow") {
var d = getCOWFastDictionary()
let i = d.keys.firstIndex(of: 20)!
let j = d.index(after: i)
let identifier = d._rawIdentifier()
expectTrue(i < j)
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d._rawIdentifier(), identifier)
expectEqual(d.count, d.capacity)
expectTrue(i < j)
d[0] = 0
expectNotEqual(d._rawIdentifier(), identifier)
expectTrue(i < j)
expectCrashLater()
_ = d.keys[i..<j]
}
DictionaryTestSuite.test("IndexValidation.ValuesRangeSubscript.AfterRemoval") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let j = d.index(after: i)
expectTrue(i < j)
d.removeValue(forKey: 10)
expectTrue(i < j)
expectCrashLater()
_ = d.values[i..<j]
}
DictionaryTestSuite.test("IndexValidation.ValuesRangeSubscript.AfterGrow") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let j = d.index(after: i)
let identifier = d._rawIdentifier()
expectTrue(i < j)
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d._rawIdentifier(), identifier)
expectEqual(d.count, d.capacity)
expectTrue(i < j)
d[0] = 0
expectNotEqual(d._rawIdentifier(), identifier)
expectTrue(i < j)
expectCrashLater()
_ = d.values[i..<j]
}
DictionaryTestSuite.test("IndexValidation.RemoveAt.AfterRemoval") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
expectEqual(d[i], (key: 20, value: 1020))
d.removeValue(forKey: 10)
expectCrashLater()
d.remove(at: i)
}
DictionaryTestSuite.test("IndexValidation.RemoveAt.AfterGrow") {
var d = getCOWFastDictionary()
let i = d.index(forKey: 20)!
let identifier = d._rawIdentifier()
expectEqual(d[i], (key: 20, value: 1020))
for i in 0 ..< (d.capacity - d.count) {
d[100 + i] = 100 + i
}
expectEqual(d._rawIdentifier(), identifier)
expectEqual(d.count, d.capacity)
d[0] = 0
expectNotEqual(d._rawIdentifier(), identifier)
expectCrashLater()
d.remove(at: i)
}
DictionaryTestSuite.test("BulkLoadingInitializer.Unique") {
for c in [0, 1, 2, 3, 5, 10, 25, 150] {
let d1 = Dictionary<TestKeyTy, TestEquatableValueTy>(
_unsafeUninitializedCapacity: c,
allowingDuplicates: false
) { keys, values in
let k = keys.baseAddress!
let v = values.baseAddress!
for i in 0 ..< c {
(k + i).initialize(to: TestKeyTy(i))
(v + i).initialize(to: TestEquatableValueTy(i))
}
return c
}
let d2 = Dictionary(
uniqueKeysWithValues: (0..<c).map {
(TestKeyTy($0), TestEquatableValueTy($0))
})
for i in 0 ..< c {
expectEqual(TestEquatableValueTy(i), d1[TestKeyTy(i)])
}
expectEqual(d2, d1)
}
}
DictionaryTestSuite.test("BulkLoadingInitializer.Nonunique") {
for c in [0, 1, 2, 3, 5, 10, 25, 150] {
let d1 = Dictionary<TestKeyTy, TestEquatableValueTy>(
_unsafeUninitializedCapacity: c,
allowingDuplicates: true
) { keys, values in
let k = keys.baseAddress!
let v = values.baseAddress!
for i in 0 ..< c {
(k + i).initialize(to: TestKeyTy(i / 2))
(v + i).initialize(to: TestEquatableValueTy(i / 2))
}
return c
}
let d2 = Dictionary(
(0 ..< c).map {
(TestKeyTy($0 / 2), TestEquatableValueTy($0 / 2))
},
uniquingKeysWith: { a, b in a })
expectEqual(d1.count, d2.count)
for i in 0 ..< c / 2 {
expectEqual(TestEquatableValueTy(i), d1[TestKeyTy(i)])
}
expectEqual(d2, d1)
}
}
DictionaryTestSuite.setUp {
#if _runtime(_ObjC)
// Exercise ARC's autoreleased return value optimization in Foundation.
//
// On some platforms, when a new process is started, the optimization is
// expected to fail the first time it is used in each linked
// dylib. StdlibUnittest takes care of warming up ARC for the stdlib
// (libswiftCore.dylib), but for this particular test we also need to do it
// for Foundation, or there will be spurious leaks reported for tests
// immediately following a crash test.
//
// <rdar://problem/42069800> stdlib tests: expectCrashLater() interferes with
// counting autoreleased live objects
let d = NSDictionary(objects: [1 as NSNumber], forKeys: [1 as NSNumber])
_ = d.object(forKey: 1 as NSNumber)
#endif
resetLeaksOfDictionaryKeysValues()
#if _runtime(_ObjC)
resetLeaksOfObjCDictionaryKeysValues()
#endif
}
DictionaryTestSuite.tearDown {
expectNoLeaksOfDictionaryKeysValues()
#if _runtime(_ObjC)
expectNoLeaksOfObjCDictionaryKeysValues()
#endif
}
runAllTests()
| apache-2.0 | 9fcb3b1ec190cbe61695910d422cb19a | 28.276438 | 280 | 0.678543 | 3.932878 | false | true | false | false |
emilstahl/swift | test/attr/attr_ibaction.swift | 17 | 4848 | // RUN: %target-parse-verify-swift
// REQUIRES: objc_interop
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}}
var iboutlet_global: Int
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}}
class IBOutletClassTy {}
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{1-11=}}
struct IBStructTy {}
@IBAction // expected-error {{only instance methods can be declared @IBAction}} {{1-11=}}
func IBFunction() -> () {}
class IBActionWrapperTy {
@IBAction
func click(_: AnyObject) -> () {} // no-warning
func outer(_: AnyObject) -> () {
@IBAction // expected-error {{only instance methods can be declared @IBAction}} {{5-15=}}
func inner(_: AnyObject) -> () {}
}
@IBAction // expected-error {{@IBAction may only be used on 'func' declarations}} {{3-13=}}
var value : Void = ()
@IBAction
func process(x: AnyObject) -> Int {} // expected-error {{methods declared @IBAction must return 'Void' (not 'Int')}}
// @IBAction does /not/ semantically imply @objc.
@IBAction // expected-note {{attribute already specified here}}
@IBAction // expected-error {{duplicate attribute}}
func doMagic(_: AnyObject) -> () {}
@IBAction @objc
func moreMagic(_: AnyObject) -> () {} // no-warning
@objc @IBAction
func evenMoreMagic(_: AnyObject) -> () {} // no-warning
}
struct S { }
enum E { }
protocol P1 { }
protocol P2 { }
protocol CP1 : class { }
protocol CP2 : class { }
@objc protocol OP1 { }
@objc protocol OP2 { }
// Check which argument types @IBAction can take.
@objc class X {
// Class type
@IBAction func action1(_: X) {}
@IBAction func action2(_: X?) {}
@IBAction func action3(_: X!) {}
// AnyObject
@IBAction func action4(_: AnyObject) {}
@IBAction func action5(_: AnyObject?) {}
@IBAction func action6(_: AnyObject!) {}
// Protocol types
@IBAction func action7(_: P1) {} // expected-error{{argument to @IBAction method cannot have non-object type 'P1'}}
@IBAction func action8(_: CP1) {} // expected-error{{argument to @IBAction method cannot have non-object type 'CP1'}}
@IBAction func action9(_: OP1) {}
@IBAction func action10(_: P1?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action11(_: CP1?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action12(_: OP1?) {}
@IBAction func action13(_: P1!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action14(_: CP1!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action15(_: OP1!) {}
// Class metatype
@IBAction func action15b(_: X.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action16(_: X.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action17(_: X.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// AnyClass
@IBAction func action18(_: AnyClass) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action19(_: AnyClass?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action20(_: AnyClass!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// Protocol types
@IBAction func action21(_: P1.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action22(_: CP1.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action23(_: OP1.Type) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action24(_: P1.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action25(_: CP1.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action26(_: OP1.Type?) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action27(_: P1.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action28(_: CP1.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action29(_: OP1.Type!) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
// Other bad cases
@IBAction func action30(_: S) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
@IBAction func action31(_: E) {} // expected-error{{argument to @IBAction method cannot have non-object type}}
init() { }
}
| apache-2.0 | be37cd3e892fdcd564facee12c67d151 | 46.067961 | 120 | 0.6842 | 3.92233 | false | false | false | false |
shadanan/mado | Antlr4Runtime/Sources/Antlr4/misc/ArrayWrapper.swift | 1 | 1983 | /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
//
// ArrayWrapper.swift
// Antlr4
//
// Created by janyou on 16/6/21.
//
import Foundation
public final class ArrayWrapper<T: Hashable>: ExpressibleByArrayLiteral, Hashable {
public var array: Array<T>
public init(slice: ArraySlice<T>) {
array = Array<T>()
for element in slice {
array.append(element)
}
}
public init(_ elements: T...) {
array = Array<T>()
for element in elements {
array.append(element)
}
}
public init(_ elements: [T]) {
array = elements
}
public init(count: Int, repeatedValue: T) {
array = Array<T>(repeating: repeatedValue, count: count)
}
public init(arrayLiteral elements: T...) {
array = Array<T>()
for element in elements {
array.append(element)
}
}
public subscript(index: Int) -> T {
get {
return array[index]
}
set {
array[index] = newValue
}
}
public subscript(subRange: Range<Int>) -> ArrayWrapper<T> {
return ArrayWrapper<T>(slice: array[subRange])
}
public var count: Int { return array.count }
public var hashValue: Int {
if count == 0 {
return 0
}
var result = 1
for element in array {
result = 31 &* result &+ element.hashValue
}
return result
}
}
public func == <Element: Equatable>(lhs: ArrayWrapper<Element>, rhs: ArrayWrapper<Element>) -> Bool {
if lhs === rhs {
return true
}
if lhs.count != rhs.count {
return false
}
let length = lhs.count
for i in 0..<length {
if lhs[i] != rhs[i] {
return false
}
}
return true
}
| mit | 07ceb14a61657b91e31fefd83d7b5ed5 | 21.280899 | 101 | 0.548159 | 4.157233 | false | false | false | false |
litecoin-association/LoafWallet | fastlane/SnapshotHelper.swift | 7 | 4072 | //
// SnapshotHelper.swift
// Example
//
// Created by Felix Krause on 10/8/15.
// Copyright (c) 2015 Felix Krause
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import XCTest
var deviceLanguage = ""
@available(*, deprecated, message: "use setupSnapshot: instead")
func setLanguage(_ app: XCUIApplication) {
setupSnapshot(app)
}
func setupSnapshot(_ app: XCUIApplication) {
Snapshot.setLanguage(app)
Snapshot.setLaunchArguments(app)
}
func snapshot(_ name: String, waitForLoadingIndicator: Bool = false) {
Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator)
}
class Snapshot: NSObject {
class func setLanguage(_ app: XCUIApplication) {
let path = "/tmp/language.txt"
do {
let locale = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String
deviceLanguage = locale.substring(to: locale.characters.index(locale.startIndex, offsetBy: 2, limitedBy:locale.endIndex)!)
app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))", "-AppleLocale", "\"\(locale)\"", "-ui_testing"]
} catch {
print("Couldn't detect/set language...")
}
}
class func setLaunchArguments(_ app: XCUIApplication) {
let path = "/tmp/snapshot-launch_arguments.txt"
app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES"]
do {
let launchArguments = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String
let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: [])
let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count))
let results = matches.map { result -> String in
(launchArguments as NSString).substring(with: result.range)
}
app.launchArguments += results
} catch {
print("Couldn't detect/set launch_arguments...")
}
}
class func snapshot(_ name: String, waitForLoadingIndicator: Bool = false) {
if waitForLoadingIndicator {
waitForLoadingIndicatorToDisappear()
}
print("snapshot: \(name)") // more information about this, check out https://github.com/krausefx/snapshot
sleep(1) // Waiting for the animation to be finished (kind of)
XCUIDevice.shared().orientation = .unknown
}
class func waitForLoadingIndicatorToDisappear() {
let query = XCUIApplication().statusBars.children(matching: .other).element(boundBy: 1).children(matching: .other)
while query.count > 4 {
sleep(1)
print("Number of Elements in Status Bar: \(query.count)... waiting for status bar to disappear")
}
}
}
// Please don't remove the lines below
// They are used to detect outdated configuration files
// SnapshotHelperVersion [[1.0]]
| mit | 9831b06eaa01e0e0614358c30455d4e9 | 39.72 | 142 | 0.669941 | 4.734884 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01858-llvm-densemap-swift-valuedecl.swift | 1 | 1085 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct d<T where g: A where g, f<T) -> T -> String {
let c {
class p == {
protocol f {
return self["
}
class k , b {
(Any, m.init(j, i l, b class B, AnyObject) -> T {
u m h: k<T> String {
}
}
}
func b> String = T> d<T where T: Int = [1
j : A> Any) + seq
struct C<T) -> {
}
func b() -> i<l y ed) -> {
f : A {
func f.m)
func a
typealias B == g.E
()-> {
}
protocol f d{ se
}
)
func d<T
return d.i : Array<T>)
}
protocol d = b.C<T.Type) -> U) -> Any) {
}
case .c(() -> t.f = g, o>>(b
func g<l p : ()
func a: b
}
return { enum a!)) -> {
enum A {
let n1: (p: P> T {
struct c(r: c, l lk: NSObject {
enum g : Array<h == [u, (n<h {
}
typealias e = [q(()
func f: (x: B) -> : c> (g.p, d<q ")))
}
o
| apache-2.0 | 3f1cc2ebe1132ed08752838af4139530 | 19.471698 | 79 | 0.588018 | 2.552941 | false | false | false | false |
ben-ng/swift | test/Generics/requirement_inference.swift | 2 | 4554 | // RUN: %target-typecheck-verify-swift -typecheck %s -verify
// RUN: %target-typecheck-verify-swift -typecheck -debug-generic-signatures %s > %t.dump 2>&1
// RUN: %FileCheck %s < %t.dump
protocol P1 {
func p1()
}
protocol P2 : P1 { }
struct X1<T : P1> {
func getT() -> T { }
}
class X2<T : P1> {
func getT() -> T { }
}
class X3 { }
struct X4<T : X3> {
func getT() -> T { }
}
struct X5<T : P2> { }
// Infer protocol requirements from the parameter type of a generic function.
func inferFromParameterType<T>(_ x: X1<T>) {
x.getT().p1()
}
// Infer protocol requirements from the return type of a generic function.
func inferFromReturnType<T>(_ x: T) -> X1<T> {
x.p1()
}
// Infer protocol requirements from the superclass of a generic parameter.
func inferFromSuperclass<T, U : X2<T>>(_ t: T, u: U) -> T {
t.p1()
}
// Infer protocol requirements from the parameter type of a constructor.
struct InferFromConstructor {
init<T> (x : X1<T>) {
x.getT().p1()
}
}
// Don't infer requirements for outer generic parameters.
class Fox : P1 {
func p1() {}
}
class Box<T : Fox> {
// CHECK-LABEL: .unpack@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: T : Fox [explicit]
func unpack(_ x: X1<T>) {}
}
// ----------------------------------------------------------------------------
// Superclass requirements
// ----------------------------------------------------------------------------
// Compute meet of two superclass requirements correctly.
class Carnivora {}
class Canidae : Carnivora {}
struct U<T : Carnivora> {}
struct V<T : Canidae> {}
// CHECK-LABEL: .inferSuperclassRequirement1@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: T : Canidae
func inferSuperclassRequirement1<T : Carnivora>(_ v: V<T>) {}
// CHECK-LABEL: .inferSuperclassRequirement2@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: T : Canidae
func inferSuperclassRequirement2<T : Canidae>(_ v: U<T>) {}
// ----------------------------------------------------------------------------
// Same-type requirements
// ----------------------------------------------------------------------------
protocol P3 {
associatedtype P3Assoc : P2
}
protocol P4 {
associatedtype P4Assoc : P1
}
protocol PCommonAssoc1 {
associatedtype CommonAssoc
}
protocol PCommonAssoc2 {
associatedtype CommonAssoc
}
protocol PAssoc {
associatedtype Assoc
}
struct Model_P3_P4_Eq<T : P3, U : P4> where T.P3Assoc == U.P4Assoc {}
// CHECK-LABEL: .inferSameType1@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: T : P3 [inferred @ {{.*}}:32]
// CHECK-NEXT: U : P4 [inferred @ {{.*}}:32]
// CHECK-NEXT: T[.P3].P3Assoc : P1 [redundant @ {{.*}}:18]
// CHECK-NEXT: T[.P3].P3Assoc : P2 [protocol @ {{.*}}:18]
// CHECK-NEXT: T[.P3].P3Assoc == U[.P4].P4Assoc [inferred @ {{.*}}32]
func inferSameType1<T, U>(_ x: Model_P3_P4_Eq<T, U>) { }
// CHECK-LABEL: .inferSameType2@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: T : P3 [explicit @ {{.*}}requirement_inference.swift:{{.*}}:25]
// CHECK-NEXT: U : P4 [explicit @ {{.*}}requirement_inference.swift:{{.*}}:33]
// CHECK-NEXT: T[.P3].P3Assoc : P1 [redundant @ {{.*}}requirement_inference.swift:{{.*}}:18]
// CHECK-NEXT: T[.P3].P3Assoc : P2 [protocol @ {{.*}}requirement_inference.swift:{{.*}}:18]
// CHECK-NEXT: T[.P3].P3Assoc == U[.P4].P4Assoc [explicit @ {{.*}}requirement_inference.swift:{{.*}}:75]
func inferSameType2<T : P3, U : P4>(_: T) where U.P4Assoc : P2, T.P3Assoc == U.P4Assoc {}
// CHECK-LABEL: .inferSameType3@
// CHECK-NEXT: Requirements:
// CHECK-NEXT: T : PCommonAssoc1 [explicit @ {{.*}}requirement_inference.swift:{{.*}}:25]
// CHECK-NEXT: T : PCommonAssoc2 [explicit @ {{.*}}requirement_inference.swift:{{.*}}:76]
// CHECK-NEXT: T[.PCommonAssoc1].CommonAssoc : P1 [explicit @ {{.*}}requirement_inference.swift:{{.*}}:68]
// CHECK-NEXT: T[.PCommonAssoc1].CommonAssoc == T[.PCommonAssoc2].CommonAssoc [redundant @ {{.*}}requirement_inference.swift:{{.*}}:76]
// CHECK-NEXT: Generic signature
func inferSameType3<T : PCommonAssoc1>(_: T) where T.CommonAssoc : P1, T : PCommonAssoc2 {}
protocol P5 {
associatedtype Element
}
protocol P6 {
associatedtype AssocP6 : P5
}
protocol P7 : P6 {
associatedtype AssocP7: P6
}
// CHECK-LABEL: P7.nestedSameType1()@
// CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P7, τ_0_0.AssocP6.Element : P6, τ_0_0.AssocP6.Element == τ_0_0.AssocP7.AssocP6.Element>
extension P7 where AssocP6.Element : P6,
AssocP7.AssocP6.Element : P6,
AssocP6.Element == AssocP7.AssocP6.Element {
func nestedSameType1() { }
}
| apache-2.0 | 3172a68c5ed565ab77efacfc6f78f78b | 27.974522 | 147 | 0.605188 | 3.28685 | false | false | false | false |
FoodForTech/Handy-Man | HandyMan/HandyMan/HandyManCore/Spring/DesignableTextView.swift | 1 | 2422 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@IBDesignable open class DesignableTextView: SpringTextView {
@IBInspectable open var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable open var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable open var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable open var lineHeight: CGFloat = 1.5 {
didSet {
let font = UIFont(name: self.font!.fontName, size: self.font!.pointSize)
let text = self.text
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
let attributedString = NSMutableAttributedString(string: text!)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
}
| mit | 7dc25e9f9f77b6e9ebe963fa9582ebba | 38.704918 | 143 | 0.687861 | 5.164179 | false | false | false | false |
luanlzsn/pos | pos/Carthage/Checkouts/IQKeyboardManager/Demo/Swift_Demo/ViewController/SettingsViewController.swift | 2 | 26236 | //
// SettingsViewController.swift
// Demo
//
// Created by Iftekhar on 26/08/15.
// Copyright (c) 2015 Iftekhar. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
class SettingsViewController: UITableViewController, OptionsViewControllerDelegate, ColorPickerTextFieldDelegate {
let sectionTitles = ["UIKeyboard handling",
"IQToolbar handling",
"UIKeyboard appearance overriding",
"Resign first responder handling",
"UISound handling",
"IQKeyboardManager Debug"]
let keyboardManagerProperties = [["Enable", "Keyboard Distance From TextField", "Prevent Showing Bottom Blank Space"],
["Enable AutoToolbar","Toolbar Manage Behaviour","Should Toolbar Uses TextField TintColor","Should Show TextField Placeholder","Placeholder Font","Toolbar Tint Color","Toolbar Done BarButtonItem Image","Toolbar Done Button Text"],
["Override Keyboard Appearance","UIKeyboard Appearance"],
["Should Resign On Touch Outside"],
["Should Play Input Clicks"],
["Debugging logs in Console"]]
let keyboardManagerPropertyDetails = [["Enable/Disable IQKeyboardManager","Set keyboard distance from textField","Prevent to show blank space between UIKeyboard and View"],
["Automatic add the IQToolbar on UIKeyboard","AutoToolbar previous/next button managing behaviour","Uses textField's tintColor property for IQToolbar","Add the textField's placeholder text on IQToolbar","UIFont for IQToolbar placeholder text","Override toolbar tintColor property","Replace toolbar done button text with provided image","Override toolbar done button text"],
["Override the keyboardAppearance for all UITextField/UITextView","All the UITextField keyboardAppearance is set using this property"],
["Resigns Keyboard on touching outside of UITextField/View"],
["Plays inputClick sound on next/previous/done click"],
["Setting enableDebugging to YES/No to turn on/off debugging mode"]]
var selectedIndexPathForOptions : IndexPath?
@IBAction func doneAction (_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
/** UIKeyboard Handling */
func enableAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().enable = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 0), with: UITableViewRowAnimation.fade)
}
func keyboardDistanceFromTextFieldAction (_ sender: UIStepper) {
IQKeyboardManager.sharedManager().keyboardDistanceFromTextField = CGFloat(sender.value)
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: UITableViewRowAnimation.none)
}
func preventShowingBottomBlankSpaceAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 0), with: UITableViewRowAnimation.fade)
}
/** IQToolbar handling */
func enableAutoToolbarAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().enableAutoToolbar = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 1), with: UITableViewRowAnimation.fade)
}
func shouldToolbarUsesTextFieldTintColorAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = sender.isOn
}
func shouldShowTextFieldPlaceholder (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 1), with: UITableViewRowAnimation.fade)
}
func toolbarDoneBarButtonItemImage (_ sender: UISwitch) {
if sender.isOn {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage = UIImage(named:"IQButtonBarArrowDown")
} else {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage = nil
}
self.tableView.reloadSections(IndexSet(integer: 1), with: UITableViewRowAnimation.fade)
}
/** "Keyboard appearance overriding */
func overrideKeyboardAppearanceAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().overrideKeyboardAppearance = sender.isOn
self.tableView.reloadSections(IndexSet(integer: 2), with: UITableViewRowAnimation.fade)
}
/** Resign first responder handling */
func shouldResignOnTouchOutsideAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = sender.isOn
}
/** Sound handling */
func shouldPlayInputClicksAction (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().shouldPlayInputClicks = sender.isOn
}
/** Debugging */
func enableDebugging (_ sender: UISwitch) {
IQKeyboardManager.sharedManager().enableDebugging = sender.isOn
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch (section)
{
case 0:
if IQKeyboardManager.sharedManager().enable == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 1:
if IQKeyboardManager.sharedManager().enableAutoToolbar == false {
return 1
} else if IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder == false {
return 4
} else {
let properties = keyboardManagerProperties[section]
return properties.count
}
case 2:
if IQKeyboardManager.sharedManager().overrideKeyboardAppearance == true {
let properties = keyboardManagerProperties[section]
return properties.count
} else {
return 1
}
case 3,4,5:
let properties = keyboardManagerProperties[section]
return properties.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch ((indexPath as NSIndexPath).section) {
case 0:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().enable
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "StepperTableViewCell") as! StepperTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.stepper.value = Double(IQKeyboardManager.sharedManager().keyboardDistanceFromTextField)
cell.labelStepperValue.text = NSString(format: "%.0f", IQKeyboardManager.sharedManager().keyboardDistanceFromTextField) as String
cell.stepper.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.stepper.addTarget(self, action: #selector(self.keyboardDistanceFromTextFieldAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().preventShowingBottomBlankSpace
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.preventShowingBottomBlankSpaceAction(_:)), for: UIControlEvents.valueChanged)
return cell
default:
break
}
case 1:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().enableAutoToolbar
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableAutoToolbarAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldToolbarUsesTextFieldTintColorAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldShowTextFieldPlaceholder(_:)), for: UIControlEvents.valueChanged)
return cell
case 4:
let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
case 5:
let cell = tableView.dequeueReusableCell(withIdentifier: "ColorTableViewCell") as! ColorTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.colorPickerTextField.selectedColor = IQKeyboardManager.sharedManager().toolbarTintColor
cell.colorPickerTextField.tag = 15
cell.colorPickerTextField.delegate = self
return cell
case 6:
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageSwitchTableViewCell") as! ImageSwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.arrowImageView.image = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemImage != nil
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.toolbarDoneBarButtonItemImage(_:)), for: UIControlEvents.valueChanged)
return cell
case 7:
let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldTableViewCell") as! TextFieldTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.textField.text = IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText
cell.textField.tag = 17
cell.textField.delegate = self
return cell
default:
break
}
case 2:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().overrideKeyboardAppearance
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.overrideKeyboardAppearanceAction(_:)), for: UIControlEvents.valueChanged)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "NavigationTableViewCell") as! NavigationTableViewCell
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
default:
break
}
case 3:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().shouldResignOnTouchOutside
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldResignOnTouchOutsideAction(_:)), for: UIControlEvents.valueChanged)
return cell
default:
break
}
case 4:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().shouldPlayInputClicks
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.shouldPlayInputClicksAction(_:)), for: UIControlEvents.valueChanged)
return cell
default:
break
}
case 5:
switch ((indexPath as NSIndexPath).row) {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell") as! SwitchTableViewCell
cell.switchEnable.isEnabled = true
cell.labelTitle.text = keyboardManagerProperties[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.labelSubtitle.text = keyboardManagerPropertyDetails[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
cell.switchEnable.isOn = IQKeyboardManager.sharedManager().enableDebugging
cell.switchEnable.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
cell.switchEnable.addTarget(self, action: #selector(self.enableDebugging(_:)), for: UIControlEvents.valueChanged)
return cell
default:
break
}
default:
break
}
return UITableViewCell()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
fileprivate func colorPickerTextField(_ textField: ColorPickerTextField, selectedColorAttributes colorAttributes: [String : AnyObject]) {
if textField.tag == 15 {
let color = colorAttributes["color"] as! UIColor
if color.isEqual(UIColor.clear) {
IQKeyboardManager.sharedManager().toolbarTintColor = nil
} else {
IQKeyboardManager.sharedManager().toolbarTintColor = color
}
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.tag == 17 {
IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText = textField.text?.characters.count != 0 ? textField.text : nil
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
if identifier == "OptionsViewController" {
let controller = segue.destination as! OptionsViewController
controller.delegate = self
let cell = sender as! UITableViewCell
selectedIndexPathForOptions = self.tableView.indexPath(for: cell)
if let selectedIndexPath = selectedIndexPathForOptions {
if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 1 {
controller.title = "Toolbar Manage Behaviour"
controller.options = ["IQAutoToolbar By Subviews","IQAutoToolbar By Tag","IQAutoToolbar By Position"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
} else if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 4 {
controller.title = "Fonts"
controller.options = ["Bold System Font","Italic system font","Regular"]
controller.selectedIndex = IQKeyboardManager.sharedManager().toolbarManageBehaviour.hashValue
let fonts = [UIFont.boldSystemFont(ofSize: 12),UIFont.italicSystemFont(ofSize: 12),UIFont.systemFont(ofSize: 12)]
if let placeholderFont = IQKeyboardManager.sharedManager().placeholderFont {
if let index = fonts.index(of: placeholderFont) {
controller.selectedIndex = index
}
}
} else if (selectedIndexPath as NSIndexPath).section == 2 && (selectedIndexPath as NSIndexPath).row == 1 {
controller.title = "Keyboard Appearance"
controller.options = ["UIKeyboardAppearance Default","UIKeyboardAppearance Dark","UIKeyboardAppearance Light"]
controller.selectedIndex = IQKeyboardManager.sharedManager().keyboardAppearance.hashValue
}
}
}
}
}
func optionsViewController(_ controller: OptionsViewController, index: NSInteger) {
if let selectedIndexPath = selectedIndexPathForOptions {
if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 1 {
IQKeyboardManager.sharedManager().toolbarManageBehaviour = IQAutoToolbarManageBehaviour(rawValue: index)!
} else if (selectedIndexPath as NSIndexPath).section == 1 && (selectedIndexPath as NSIndexPath).row == 4 {
let fonts = [UIFont.boldSystemFont(ofSize: 12),UIFont.italicSystemFont(ofSize: 12),UIFont.systemFont(ofSize: 12)]
IQKeyboardManager.sharedManager().placeholderFont = fonts[index]
} else if (selectedIndexPath as NSIndexPath).section == 2 && (selectedIndexPath as NSIndexPath).row == 1 {
IQKeyboardManager.sharedManager().keyboardAppearance = UIKeyboardAppearance(rawValue: index)!
}
}
}
}
| mit | a1884046d065e8ab5c4d55b22c71ae6b | 46.788707 | 377 | 0.610993 | 7.03378 | false | false | false | false |
adrfer/swift | test/1_stdlib/FloatingPointIR.swift | 4 | 2132 | // RUN: %target-build-swift -emit-ir %s | FileCheck -check-prefix=%target-cpu %s
// REQUIRES: executable_test
var globalFloat32 : Float32 = 0.0
var globalFloat64 : Float64 = 0.0
#if arch(i386) || arch(x86_64)
var globalFloat80 : Float80 = 0.0
#endif
@inline(never)
func acceptFloat32(a: Float32) {
globalFloat32 = a
}
@inline(never)
func acceptFloat64(a: Float64) {
globalFloat64 = a
}
#if arch(i386) || arch(x86_64)
@inline(never)
func acceptFloat80(a: Float80) {
globalFloat80 = a
}
#endif
func testConstantFoldFloatLiterals() {
acceptFloat32(1.0)
acceptFloat64(1.0)
#if arch(i386) || arch(x86_64)
acceptFloat80(1.0)
#endif
}
// i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat80FVs7Float80T_(x86_fp80 0xK3FFF8000000000000000)
// x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat80FVs7Float80T_(x86_fp80 0xK3FFF8000000000000000)
// armv7: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// armv7: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// armv7k: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// armv7k: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// arm64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// arm64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// powerpc64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// powerpc64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// powerpc64le: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// powerpc64le: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
| apache-2.0 | 63f44d749430acb984bbd5004f8ddef4 | 37.763636 | 110 | 0.741557 | 3.259939 | false | false | false | false |
fschneider1509/RuleBasedXMLParserDelegate | RuleBasedXMLParserDelegateKitTests/DataModelMockObjects.swift | 1 | 3137 | //
// DataModelMockObjects.swift
// RuleBasedXMLParserDelegate
//
// Created by Fabian Schneider
// fabian(at)fabianschneider.org
// MIT License
//
import Foundation
import RuleBasedXMLParserDelegate
class ShoppingListModel : NSObject, XMLParserNodeProtocol {
var userName: String?
var numberOfItems: Int?
var date: Date?
var total: Float?
var currency: String?
var childNodes: [XMLParserNodeProtocol]
override required init() {
childNodes = [XMLParserNodeProtocol]()
}
func setPropertyValue(propertyName: String, propertyValue: Any?) throws {
if let propertyValue = propertyValue {
switch propertyName {
case "userName":
userName = propertyValue as? String
break
case "numberOfItems":
numberOfItems = Int(propertyValue as! String)!
break
case "date":
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
let stringValue: String = propertyValue as!String
let d: Date? = dateFormatter.date(from: stringValue)
if let d = d {
date = d
}
break
case "total":
total = Float(propertyValue as! String)!
break
case "currency":
currency = propertyValue as? String
break
default:
break
}
}
}
}
class ShoppingItemModel : NSObject, XMLParserNodeProtocol {
var itemDescription: String?
var price: Float?
var quantity: Int?
var deliveryDate: Date?
var childNodes: [XMLParserNodeProtocol]
override required init() {
childNodes = [XMLParserNodeProtocol]()
}
func setPropertyValue(propertyName: String, propertyValue: Any?) throws {
if let propertyValue = propertyValue {
switch propertyName {
case "itemDescription":
itemDescription = propertyValue as? String
break
case "price":
price = Float(propertyValue as! String)!
break
case "quantity":
quantity = Int(propertyValue as! String)!
break
case "deliveryDate":
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
let stringValue: String = propertyValue as!String
let d: Date? = dateFormatter.date(from: stringValue)
if let d = d {
deliveryDate = d
}
break
default:
break
}
}
}
}
| mit | b9309a8e4ef638899ec9310d84bf5e5d | 31.340206 | 77 | 0.511954 | 5.963878 | false | false | false | false |
V1C0D3R/KubiServerApp | KubiServer/ViewController.swift | 2 | 15633 | /*
* Software License Agreement(New BSD License)
* Copyright © 2017, Victor Nouvellet
* 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.
*/
//
// ViewController.swift
// KubiServer
//
// Created by Victor Nouvellet on 1/23/17.
// Copyright © 2017 Victor Nouvellet Inc. All rights reserved.
//
import UIKit
import AVFoundation
import lf
import VideoToolbox
class ViewController: UIViewController {
@IBOutlet weak var scanIndicator: UIActivityIndicatorView?
@IBOutlet weak var scanButton: UIButton!
@IBOutlet weak var connectionView: UIView?
@IBOutlet weak var autoConnectSwitch: UISwitch!
@IBOutlet weak var controlView: UIView?
@IBOutlet weak var topConstraint: NSLayoutConstraint?
@IBOutlet weak var logViewContainer: UIView!
@IBOutlet weak var webServerLog: UITextView!
@IBOutlet weak var liveView: UIView!
fileprivate var connectionAlert: UIAlertController = UIAlertController()
fileprivate var isScanning: Bool = false
fileprivate var kubiManager: KubiManager = KubiManager.sharedInstance
fileprivate var serverHelper: ServerHelper = ServerHelper.sharedInstance
fileprivate var visualSaver: VisualSaver = VisualSaver()
fileprivate var cameraPosition:AVCaptureDevicePosition = .front
fileprivate var autoConnect: Bool {
get {
return UserDefaults.standard.bool(forKey: "autoconnect")
}
set(value) {
UserDefaults.standard.set(value, forKey: "autoconnect")
}
}
//TODO: Move Streaming var/func to helper
fileprivate var camera = DeviceUtil.device(withPosition: .front)
var httpStream:HTTPStream? = nil
var streamingHttpService:HTTPService? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.autoConnectSwitch.isOn = self.autoConnect
self.configureKubiManagerCallbacks()
self.updateControlButtons()
// Start searching for Kubis
self.startScanning()
// Init web server
self.configureWebServer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func scanButtonPressed(sender: UIButton) {
self.updateControlButtons()
self.kubiManager.disconnectDevice()
self.startScanning()
}
@IBAction func disconnectButtonPressed(sender: UIButton) {
self.kubiManager.disconnectDevice()
}
@IBAction func shareButtonPressed(sender: UIButton) {
if let kubi = self.kubiManager.connectedDevice as? RRKubi {
// shareControlWithAppData method seems to be broken
// [self.sdk shareControlWithAppData:nil success:^{
// NSLog(@"SUCCESS");
// } fail:^(NSError * _Nullable error) {
// NSLog(@"FAIL");
// }];
print("Identifier : %@ \n Type : %@", kubi.identifier, kubi.type)
}
}
@IBAction func autoconnectSwitchValueChanged(_ sender: Any) {
self.autoConnect = self.autoConnectSwitch.isOn
}
@IBAction func streamButtonPressed(sender: UIButton) {
self.configureStreaming()
}
@IBAction func liveViewDoubleTapped(_ sender: Any) {
let newCameraPosition: AVCaptureDevicePosition = ((self.cameraPosition == .front) ? .back : .front)
self.httpStream?.attachCamera(DeviceUtil.device(withPosition: newCameraPosition))
self.cameraPosition = newCameraPosition
self.addMessageToLog(message: "Camera changed to \(newCameraPosition == .back ? "back" : "front")")
}
// MARK: Private methods
private func configureWebServer() {
self.configureServerHelperDelegate()
self.serverHelper.kubiManager = self.kubiManager
self.serverHelper.lastImageCallback = { (compressionQuality: CGFloat, filterName: String?)->Data? in
self.visualSaver.filterName = filterName
if let ciimage = self.visualSaver.lastImage, let cgImage:CGImage = CIContext(options: nil).createCGImage(ciimage, from: ciimage.extent) {
let image:UIImage = UIImage.init(cgImage: cgImage)
if let data: Data = UIImageJPEGRepresentation(image, compressionQuality) {
return data
}
}
return nil
}
if self.serverHelper.initServer(), let safeServerUrl = self.serverHelper.serverUrl?.absoluteString {
let successMessage = "Visit \(safeServerUrl) in your web browser"
print(successMessage)
self.addMessageToLog(message: successMessage)
} else {
let failMessage = "Web server failed to initialize correctly. Are you connected to a Wifi network?"
print(failMessage)
self.addMessageToLog(message: failMessage)
}
}
private func configureStreaming() {
if self.initHLS() {
let relativeUrl = "\((self.serverHelper.serverUrl?.host ?? "")!)/kubi/playlist.m3u8"
self.addMessageToLog(message: "Streaming initialized with success. Here is the streaming url : \(relativeUrl)")
} else {
self.addMessageToLog(message: "Streaming failed to initialize. Check your Wifi connection and try again!")
}
}
private func configureKubiManagerCallbacks() {
self.kubiManager.deviceDidUpdateDeviceListCallback = { (deviceList: [Any]) in
print("device SDK didUpdateDeviceList")
if self.kubiManager.deviceConnectionState == .connecting || self.kubiManager.deviceConnectionState == .connected {
self.stopScanning()
return
}
self.connectionAlert = UIAlertController(title: "Choose your device", message: "Here is the list of available devices", preferredStyle: .actionSheet)
self.connectionAlert.popoverPresentationController?.sourceRect = self.scanButton.bounds
self.connectionAlert.popoverPresentationController?.sourceView = self.scanButton
for (index, device) in deviceList.enumerated() {
guard let safeDevice = device as? RRKubi else {
continue
}
//Auto connect
if index == 0 && self.autoConnect { self.kubiManager.kubiSdk.connect(safeDevice) }
let defaultAction: UIAlertAction = UIAlertAction(title: safeDevice.name(), style: .default, handler: { (action: UIAlertAction) in
self.stopScanning()
self.kubiManager.kubiSdk.connect(safeDevice)
})
self.connectionAlert.addAction(defaultAction)
}
let defaultAction: UIAlertAction = UIAlertAction(title: "Wait...", style: .destructive, handler: nil)
self.connectionAlert.addAction(defaultAction)
let cancelAction: UIAlertAction = UIAlertAction(title: "Stop scanning", style: .cancel, handler: {
(action: UIAlertAction) in
self.stopScanning()
})
self.connectionAlert.addAction(cancelAction)
if !self.connectionAlert.isBeingPresented && self.isScanning == true {
self.present(self.connectionAlert, animated: true, completion: nil)
}
}
self.kubiManager.deviceDidChangeConnectionCallback = { (connectionState: RRDeviceConnectionState) in
print("device SDK didChangeConnectionState")
self.updateControlButtons()
switch connectionState {
case .connected:
self.connectionAlert.dismiss(animated: true, completion: nil)
if let kubi = self.kubiManager.connectedDevice as? RRKubi {
do {
try kubi.setPanEnabled(true)
try kubi.setTiltEnabled(true)
} catch {
print("[WARNING] Tilt or Pan not enabled properly")
}
}
if self.autoConnect { self.configureStreaming() }
break
case .connecting:
self.connectionAlert.dismiss(animated: true, completion: nil)
break
case .disconnected:
break
case .connectionLost:
break
}
}
}
func addMessageToLog(message: String) {
print(message)
self.webServerLog.text = self.webServerLog.text.appending("\(message)\n")
}
// MARK: - Scan functions
@discardableResult func startScanning() -> Bool {
self.isScanning = true
self.scanButton?.isEnabled = false
self.scanIndicator?.startAnimating()
return self.kubiManager.startScan()
}
func stopScanning() {
self.kubiManager.endScan()
self.scanIndicator?.stopAnimating()
self.scanButton?.isEnabled = true
self.isScanning = false
}
// MARK: - Remote Control
private func updateControlButtons() {
if self.kubiManager.deviceConnectionState == .connected {
UIView.animate(withDuration: 1.5,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 0.5,
options: .curveEaseInOut,
animations: {
self.topConstraint?.constant = 20
self.view.layoutIfNeeded()
}, completion: { (complete: Bool) in
//What to do after completion
})
self.controlView?.isHidden = false
self.logViewContainer?.isHidden = false
} else {
UIView.animate(withDuration: 1.5,
delay: 0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 0.5,
options: .curveEaseInOut,
animations: {
self.topConstraint?.constant = 250
self.view.layoutIfNeeded()
}, completion: { (complete: Bool) in
//What to do after completion
})
self.controlView?.isHidden = true
self.logViewContainer?.isHidden = true
}
}
@IBAction func tiltUpButtonPressed(sender: UIButton) {
self.kubiManager.tiltUp()
}
@IBAction func tiltDownButtonPressed(sender: UIButton) {
self.kubiManager.tiltDown()
}
@IBAction func panLeftButtonPressed(sender: UIButton) {
self.kubiManager.panLeft()
}
@IBAction func panRightButtonPressed(sender: UIButton) {
self.kubiManager.panRight()
}
}
// MARK: - ServerHelper delegate extension
extension ViewController: ServerHelperDelegate {
func configureServerHelperDelegate() {
self.serverHelper.delegate = self
}
func serverHelperSucceededToSatisfyRequestCommand(url: URL?, path: String?, query: [AnyHashable : Any]?) {
DispatchQueue.main.async {
self.addMessageToLog(message: "[Request satisfied] URL: \((url?.absoluteString ?? "Hidden")!). Query : \((query?.description ?? "Hidden")!)")
}
}
func serverHelperFailedToSatisfyRequestCommand(error: NSError) {
DispatchQueue.main.async {
self.addMessageToLog(message:"Request failed : \(error.description)")
}
}
func serverHelperHaveNewClientConnected(url: URL?) {
DispatchQueue.main.async {
self.addMessageToLog(message:"New client connection. URL : \(url?.absoluteString ?? "Unknown url")")
}
}
}
// MARK: - Streaming methods extension
extension ViewController {
func initHLS() -> Bool {
self.httpStream = HTTPStream()
self.httpStream?.attachCamera(self.camera)
self.httpStream?.attachAudio(AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio))
// self.httpStream?.videoSettings = [
//// "bitrate": 160 * 1024, // video output bitrate
//// "width": 272,
//// "height": 480,
//// // "dataRateLimits": [160 * 1024 / 8, 1], //optional kVTCompressionPropertyKey_DataRateLimits property
//// "profileLevel": kVTProfileLevel_H264_Baseline_5_1, // H264 Profile require "import VideoToolbox"
//// "maxKeyFrameIntervalDuration": 0.2, // key frame / sec
//
// "width": 272, // video output width
// "height": 480, // video output height
// "bitrate": 4 * 1024 * 1024, // video output bitrate
// //"dataRateLimits": [1024 * 1024 / 8, 1], optional kVTCompressionPropertyKey_DataRateLimits property
// "profileLevel": kVTProfileLevel_H264_Baseline_AutoLevel, // H264 Profile require "import VideoToolbox"
// "maxKeyFrameIntervalDuration": 2, // key frame / sec
// ]
self.httpStream?.publish("kubi")
if let safeHttpStream = self.httpStream {
let lfView:LFView = LFView(frame: self.liveView.bounds)
lfView.attachStream(httpStream)
//Last image output setup
if httpStream?.registerEffect(video: self.visualSaver) ?? false {
print("lastImage configured successfully")
}
// Streaming HTTP Service setup
self.streamingHttpService = HTTPService(domain: "", type: "_http._tcp", name: "lf", port: 80)
self.streamingHttpService?.startRunning()
self.streamingHttpService?.addHTTPStream(safeHttpStream)
self.liveView.addSubview(lfView)
return true
}
return false
}
}
| bsd-3-clause | c804a2bcc3378f707691461ebd97e166 | 41.360434 | 758 | 0.610646 | 5.349418 | false | false | false | false |
danielgindi/ios-charts | ChartsDemo-macOS/ChartsDemo-macOS/Demos/BarDemoViewController.swift | 1 | 2520 | //
// BarDemoViewController.swift
// ChartsDemo-OSX
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
import Foundation
import Cocoa
import Charts
open class BarDemoViewController: NSViewController
{
@IBOutlet var barChartView: BarChartView!
override open func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
let xArray = Array(1..<10)
let ys1 = xArray.map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) }
let ys2 = xArray.map { x in return cos(Double(x) / 2.0 / 3.141) }
let yse1 = ys1.enumerated().map { x, y in return BarChartDataEntry(x: Double(x), y: y) }
let yse2 = ys2.enumerated().map { x, y in return BarChartDataEntry(x: Double(x), y: y) }
let data = BarChartData()
let ds1 = BarChartDataSet(entries: yse1, label: "Hello")
ds1.colors = [NSUIColor.red]
data.append(ds1)
let ds2 = BarChartDataSet(entries: yse2, label: "World")
ds2.colors = [NSUIColor.blue]
data.append(ds2)
let barWidth = 0.4
let barSpace = 0.05
let groupSpace = 0.1
data.barWidth = barWidth
self.barChartView.xAxis.axisMinimum = Double(xArray[0])
self.barChartView.xAxis.axisMaximum = Double(xArray[0]) + data.groupWidth(groupSpace: groupSpace, barSpace: barSpace) * Double(xArray.count)
// (0.4 + 0.05) * 2 (data set count) + 0.1 = 1
data.groupBars(fromX: Double(xArray[0]), groupSpace: groupSpace, barSpace: barSpace)
self.barChartView.data = data
self.barChartView.gridBackgroundColor = NSUIColor.white
self.barChartView.chartDescription.text = "Barchart Demo"
}
@IBAction func save(_ sender: Any)
{
let panel = NSSavePanel()
panel.allowedFileTypes = ["png"]
panel.beginSheetModal(for: self.view.window!) { (result) -> Void in
if result.rawValue == NSFileHandlingPanelOKButton
{
if let path = panel.url?.path
{
let _ = self.barChartView.save(to: path, format: .png, compressionQuality: 1.0)
}
}
}
}
override open func viewWillAppear()
{
self.barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
}
}
| apache-2.0 | 41a6022fc178d7c737f408f068bfb933 | 32.157895 | 148 | 0.600397 | 4.11093 | false | false | false | false |
Beaver/BeaverCodeGen | Pods/Diff/Sources/Patch+Apply.swift | 1 | 1336 |
public extension RangeReplaceableCollection where Self.Iterator.Element: Equatable {
public func apply(_ patch: [Patch<Iterator.Element>]) -> Self {
var mutableSelf = self
for change in patch {
switch change {
case let .insertion(i, element):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(i))
mutableSelf.insert(element, at: target)
case let .deletion(i):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(i))
mutableSelf.remove(at: target)
}
}
return mutableSelf
}
}
public extension String {
public func apply(_ patch: [Patch<String.CharacterView.Iterator.Element>]) -> String {
var mutableSelf = self
for change in patch {
switch change {
case let .insertion(i, element):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(i))
mutableSelf.insert(element, at: target)
case let .deletion(i):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(i))
mutableSelf.remove(at: target)
}
}
return mutableSelf
}
}
| mit | 592dd9586e6f5cad1ca728fcd75ceb0b | 32.4 | 98 | 0.595808 | 5.099237 | false | false | false | false |
yuezaixz/UPillow | UPillow/Classes/Utils/PNoticeHUD.swift | 1 | 14380 | //
// PNoticeHUD.swift
// UPillow
//
// Created by 吴迪玮 on 2017/8/7.
// Copyright © 2017年 Podoon. All rights reserved.
//
import UIKit
private let sn_topBar: Int = 1001
extension UIResponder {
/// wait with your own animated images
@discardableResult
func pleaseWaitWithImages(_ imageNames: Array<UIImage>, timeInterval: Int) -> UIWindow{
return SwiftNotice.wait(imageNames, timeInterval: timeInterval)
}
// api changed from v3.3
@discardableResult
func noticeTop(_ text: String, autoClear: Bool = true, autoClearTime: Int = 1) -> UIWindow{
return SwiftNotice.noticeOnStatusBar(text, autoClear: autoClear, autoClearTime: autoClearTime)
}
// new apis from v3.3
@discardableResult
func noticeSuccess(_ text: String, autoClear: Bool = false, autoClearTime: Int = 3) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.success, text: text, autoClear: autoClear, autoClearTime: autoClearTime)
}
@discardableResult
func noticeError(_ text: String, autoClear: Bool = false, autoClearTime: Int = 3) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.error, text: text, autoClear: autoClear, autoClearTime: autoClearTime)
}
@discardableResult
func noticeInfo(_ text: String, autoClear: Bool = false, autoClearTime: Int = 3) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.info, text: text, autoClear: autoClear, autoClearTime: autoClearTime)
}
// old apis
@discardableResult
func successNotice(_ text: String, autoClear: Bool = true) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.success, text: text, autoClear: autoClear, autoClearTime: 3)
}
@discardableResult
func errorNotice(_ text: String, autoClear: Bool = true) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.error, text: text, autoClear: autoClear, autoClearTime: 3)
}
@discardableResult
func infoNotice(_ text: String, autoClear: Bool = true) -> UIWindow{
return SwiftNotice.showNoticeWithText(NoticeType.info, text: text, autoClear: autoClear, autoClearTime: 3)
}
@discardableResult
func notice(_ text: String, type: NoticeType, autoClear: Bool, autoClearTime: Int = 3) -> UIWindow{
return SwiftNotice.showNoticeWithText(type, text: text, autoClear: autoClear, autoClearTime: autoClearTime)
}
@discardableResult
func pleaseWait(txt:String) -> UIWindow{
return SwiftNotice.wait(txt:txt)
}
@discardableResult
func pleaseWait() -> UIWindow{
return SwiftNotice.wait()
}
@discardableResult
func noticeOnlyText(_ text: String) -> UIWindow{
return SwiftNotice.showText(text)
}
func clearAllNotice() {
SwiftNotice.clear()
}
}
enum NoticeType{
case success
case error
case info
}
class SwiftNotice: NSObject {
static var windows = Array<UIWindow!>()
static let rv = UIApplication.shared.keyWindow?.subviews.first as UIView!
static var timer: DispatchSource!
static var timerTimes = 0
/* just for iOS 8
*/
static var degree: Double {
get {
return [0, 0, 180, 270, 90][UIApplication.shared.statusBarOrientation.hashValue] as Double
}
}
// fix https://github.com/johnlui/SwiftNotice/issues/2
// thanks broccolii(https://github.com/broccolii) and his PR https://github.com/johnlui/SwiftNotice/pull/5
static func clear() {
self.cancelPreviousPerformRequests(withTarget: self)
if let _ = timer {
timer.cancel()
timer = nil
timerTimes = 0
}
windows.removeAll(keepingCapacity: false)
}
@discardableResult
static func noticeOnStatusBar(_ text: String, autoClear: Bool, autoClearTime: Int) -> UIWindow{
let frame = UIApplication.shared.statusBarFrame
let window = UIWindow()
window.backgroundColor = UIColor.clear
let view = UIView()
view.backgroundColor = UIColor(red: 0x6a/0x100, green: 0xb4/0x100, blue: 0x9f/0x100, alpha: 1)
let label = UILabel(frame: frame)
label.textAlignment = NSTextAlignment.center
label.font = UIFont.systemFont(ofSize: 12)
label.textColor = UIColor.white
label.text = text
view.addSubview(label)
window.frame = frame
view.frame = frame
if let version = Double(UIDevice.current.systemVersion),
version < 9.0 {
// change center
var array = [UIScreen.main.bounds.width, UIScreen.main.bounds.height]
array = array.sorted(by: <)
let screenWidth = array[0]
let screenHeight = array[1]
let x = [0, screenWidth/2, screenWidth/2, 10, screenWidth-10][UIApplication.shared.statusBarOrientation.hashValue] as CGFloat
let y = [0, 10, screenHeight-10, screenHeight/2, screenHeight/2][UIApplication.shared.statusBarOrientation.hashValue] as CGFloat
window.center = CGPoint(x: x, y: y)
// change direction
window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180))
}
window.windowLevel = UIWindowLevelStatusBar
window.isHidden = false
window.addSubview(view)
windows.append(window)
var origPoint = view.frame.origin
origPoint.y = -(view.frame.size.height)
let destPoint = view.frame.origin
view.tag = sn_topBar
view.frame = CGRect(origin: origPoint, size: view.frame.size)
UIView.animate(withDuration: 0.3, animations: {
view.frame = CGRect(origin: destPoint, size: view.frame.size)
}, completion: { b in
if autoClear {
let selector = #selector(SwiftNotice.hideNotice(_:))
self.perform(selector, with: window, afterDelay: TimeInterval(autoClearTime))
}
})
return window
}
@discardableResult
static func wait(_ imageNames: Array<UIImage> = Array<UIImage>(), timeInterval: Int = 0, txt: String = "") -> UIWindow {
let frame = CGRect(x: (UIScreen.main.bounds.width-78)/2, y: (UIScreen.main.bounds.height-78)/2, width: 78, height: 78)
let window = UIWindow()
window.backgroundColor = UIColor.clear
window.isUserInteractionEnabled = true
let mainView = UIView()
mainView.layer.cornerRadius = 12
mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8)
if imageNames.count > 0 {
if imageNames.count > timerTimes {
let iv = UIImageView(frame: frame)
iv.image = imageNames.first!
iv.contentMode = UIViewContentMode.scaleAspectFit
mainView.addSubview(iv)
timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: DispatchQueue.main) as! DispatchSource
timer.scheduleRepeating(deadline: DispatchTime.now(), interval: DispatchTimeInterval.milliseconds(timeInterval))
timer.setEventHandler(handler: { () -> Void in
let name = imageNames[timerTimes % imageNames.count]
iv.image = name
timerTimes += 1
})
timer.resume()
}
} else {
if txt == "" {
let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
ai.frame = CGRect(x: 21, y: 21, width: 36, height: 36)
ai.startAnimating()
mainView.addSubview(ai)
} else {
let ai = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
ai.frame = CGRect(x: 21, y: 15, width: 36, height: 36)
ai.startAnimating()
mainView.addSubview(ai)
let txtLabel = UILabel.init(frame: CGRect(x: 0, y: 55, width: 78, height: 23))
txtLabel.textAlignment = .center
txtLabel.text = txt
txtLabel.textColor = UIColor.white
txtLabel.font = Specs.font.regular
mainView.addSubview(txtLabel)
}
}
window.frame = UIScreen.main.bounds
mainView.frame = frame
window.center = rv!.center
if let version = Double(UIDevice.current.systemVersion),
version < 9.0 {
// change center
window.center = getRealCenter()
// change direction
window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180))
}
window.windowLevel = UIWindowLevelAlert
window.isHidden = false
window.addSubview(mainView)
windows.append(window)
mainView.alpha = 0.0
UIView.animate(withDuration: 0.2, animations: {
mainView.alpha = 1
})
return window
}
@discardableResult
static func showText(_ text: String, autoClear: Bool=true, autoClearTime: Int=2) -> UIWindow {
let window = UIWindow()
window.backgroundColor = UIColor.clear
let mainView = UIView()
mainView.layer.cornerRadius = 12
mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8)
let label = UILabel()
label.text = text
label.numberOfLines = 0
label.font = Specs.font.regular
label.textAlignment = NSTextAlignment.center
label.textColor = UIColor.white
let size = label.sizeThatFits(CGSize(width: UIScreen.main.bounds.width-82, height: CGFloat.greatestFiniteMagnitude))
label.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
mainView.addSubview(label)
let superFrame = CGRect(x: 0, y: 0, width: label.frame.width + 50 , height: label.frame.height + 30)
window.frame = superFrame
mainView.frame = superFrame
label.center = mainView.center
window.center = rv!.center
if let version = Double(UIDevice.current.systemVersion),
version < 9.0 {
// change center
window.center = getRealCenter()
// change direction
window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180))
}
window.windowLevel = UIWindowLevelAlert
window.isHidden = false
window.addSubview(mainView)
windows.append(window)
if autoClear {
let selector = #selector(SwiftNotice.hideNotice(_:))
self.perform(selector, with: window, afterDelay: TimeInterval(autoClearTime))
}
return window
}
@discardableResult
static func showNoticeWithText(_ type: NoticeType,text: String, autoClear: Bool, autoClearTime: Int) -> UIWindow {
let frame = CGRect(x: 0, y: 0, width: 90, height: 90)
let window = UIWindow()
window.backgroundColor = UIColor.clear
let mainView = UIView()
mainView.layer.cornerRadius = 10
mainView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.7)
var image = UIImage()
switch type {
case .success:
image = PImageDrawUtil.imageOfCheckmark
case .error:
image = PImageDrawUtil.imageOfCross
case .info:
image = PImageDrawUtil.imageOfInfo
}
let checkmarkView = UIImageView(image: image)
checkmarkView.frame = CGRect(x: 27, y: 15, width: 36, height: 36)
mainView.addSubview(checkmarkView)
let label = UILabel(frame: CGRect(x: 0, y: 60, width: 90, height: 16))
label.font = Specs.font.regular
label.textColor = UIColor.white
label.text = text
label.textAlignment = NSTextAlignment.center
mainView.addSubview(label)
window.frame = frame
mainView.frame = frame
window.center = rv!.center
if let version = Double(UIDevice.current.systemVersion),
version < 9.0 {
// change center
window.center = getRealCenter()
// change direction
window.transform = CGAffineTransform(rotationAngle: CGFloat(degree * Double.pi / 180))
}
window.windowLevel = UIWindowLevelAlert
window.center = rv!.center
window.isHidden = false
window.addSubview(mainView)
windows.append(window)
mainView.alpha = 0.0
UIView.animate(withDuration: 0.2, animations: {
mainView.alpha = 1
})
if autoClear {
let selector = #selector(SwiftNotice.hideNotice(_:))
self.perform(selector, with: window, afterDelay: TimeInterval(autoClearTime))
}
return window
}
// fix https://github.com/johnlui/SwiftNotice/issues/2
@objc static func hideNotice(_ sender: AnyObject) {
if let window = sender as? UIWindow {
if let v = window.subviews.first {
UIView.animate(withDuration: 0.2, animations: {
if v.tag == sn_topBar {
v.frame = CGRect(x: 0, y: -v.frame.height, width: v.frame.width, height: v.frame.height)
}
v.alpha = 0
}, completion: { b in
if let index = windows.index(where: { (item) -> Bool in
return item == window
}) {
windows.remove(at: index)
}
})
}
}
}
// just for iOS 8
static func getRealCenter() -> CGPoint {
if UIApplication.shared.statusBarOrientation.hashValue >= 3 {
return CGPoint(x: rv!.center.y, y: rv!.center.x)
} else {
return rv!.center
}
}
}
extension UIWindow{
func hide(){
SwiftNotice.hideNotice(self)
}
}
| gpl-3.0 | 312118fedc5345798e0f674228c601a0 | 37.425134 | 153 | 0.598984 | 4.783955 | false | false | false | false |
yeahdongcn/RSBarcodes_Swift | Source/RSITFGenerator.swift | 1 | 1830 | //
// RSITFGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
// http://www.barcodeisland.com/int2of5.phtml
@available(macCatalyst 14.0, *)
open class RSITFGenerator: RSAbstractCodeGenerator {
let ITF_CHARACTER_ENCODINGS = [
"00110",
"10001",
"01001",
"11000",
"00101",
"10100",
"01100",
"00011",
"10010",
"01010",
]
override open func isValid(_ contents: String) -> Bool {
return super.isValid(contents) && contents.length() % 2 == 0
}
override open func initiator() -> String {
return "1010"
}
override open func terminator() -> String {
return "1101"
}
override open func barcode(_ contents: String) -> String {
var barcode = ""
for i in 0..<contents.length() / 2 {
if let pair = contents.substring(i * 2, length: 2) {
let bars = ITF_CHARACTER_ENCODINGS[Int(pair[0])!]
let spaces = ITF_CHARACTER_ENCODINGS[Int(pair[1])!]
for j in 0..<10 {
if j % 2 == 0 {
let bar = Int(bars[j / 2])
if bar == 1 {
barcode += "11"
} else {
barcode += "1"
}
} else {
let space = Int(spaces[j / 2])
if space == 1 {
barcode += "00"
} else {
barcode += "0"
}
}
}
}
}
return barcode
}
}
| mit | 8070b9b19b0dbb2c07934bea30510ba6 | 26.313433 | 68 | 0.411475 | 4.518519 | false | false | false | false |
aschwaighofer/swift | test/type/protocol_composition.swift | 2 | 9498 | // RUN: %target-typecheck-verify-swift -swift-version 4
func canonical_empty_protocol() -> Any {
return 1
}
protocol P1 {
func p1()
func f(_: Int) -> Int
}
protocol P2 : P1 {
func p2()
}
protocol P3 {
func p3()
}
protocol P4 : P3 {
func p4()
func f(_: Double) -> Double
}
typealias Any1 = protocol<> // expected-error {{'protocol<>' syntax has been removed; use 'Any' instead}}
typealias Any2 = protocol< > // expected-error {{'protocol<>' syntax has been removed; use 'Any' instead}}
// Okay to inherit a typealias for Any type.
protocol P5 : Any { }
protocol P6 : protocol<> { } // expected-error {{'protocol<>' syntax has been removed; use 'Any' instead}}
typealias P7 = Any & Any1
extension Int : P5 { }
typealias Bogus = P1 & Int // expected-error{{non-protocol, non-class type 'Int' cannot be used within a protocol-constrained type}}
func testEquality() {
// Remove duplicates from protocol-conformance types.
let x1 : (_ : P2 & P4) -> ()
let x2 : (_ : P3 & P4 & P2 & P1) -> ()
x1 = x2
_ = x1
// Singleton protocol-conformance types, after duplication, are the same as
// simply naming the protocol type.
let x3 : (_ : P2 & P1) -> ()
let x4 : (_ : P2) -> ()
x3 = x4
_ = x3
// Empty protocol-conformance types are empty.
let x5 : (_ : Any) -> ()
let x6 : (_ : Any2) -> ()
x5 = x6
_ = x5
let x7 : (_ : P1 & P3) -> ()
let x8 : (_ : P2) -> ()
x7 = x8 // expected-error{{cannot assign value of type '(P2) -> ()' to type '(P1 & P3) -> ()'}}
_ = x7
}
// Name lookup into protocol-conformance types
func testLookup() {
let x1 : P2 & P1 & P4
x1.p1()
x1.p2()
x1.p3()
x1.p4()
var _ : Int = x1.f(1)
var _ : Double = x1.f(1.0)
}
protocol REPLPrintable {
func replPrint()
}
protocol SuperREPLPrintable : REPLPrintable {
func superReplPrint()
}
protocol FooProtocol {
func format(_ kind: Unicode.Scalar, layout: String) -> String
}
struct SuperPrint : REPLPrintable, FooProtocol, SuperREPLPrintable {
func replPrint() {}
func superReplPrint() {}
func format(_ kind: Unicode.Scalar, layout: String) -> String {}
}
struct Struct1 {}
extension Struct1 : REPLPrintable, FooProtocol {
func replPrint() {}
func format(_ kind: Unicode.Scalar, layout: String) -> String {}
}
func accept_manyPrintable(_: REPLPrintable & FooProtocol) {}
func return_superPrintable() -> FooProtocol & SuperREPLPrintable {}
func testConversion() {
// Conversions for literals.
var x : REPLPrintable & FooProtocol = Struct1()
accept_manyPrintable(Struct1())
// Conversions for nominal types that conform to a number of protocols.
let sp : SuperPrint
x = sp
accept_manyPrintable(sp)
// Conversions among existential types.
var x2 : protocol<SuperREPLPrintable, FooProtocol> // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{12-53=SuperREPLPrintable & FooProtocol}}
x2 = x // expected-error{{value of type 'FooProtocol & REPLPrintable' does not conform to 'SuperREPLPrintable' in assignment}}
x = x2
// Subtyping
var _ : () -> FooProtocol & SuperREPLPrintable = return_superPrintable
// FIXME: closures make ABI conversions explicit. rdar://problem/19517003
var _ : () -> protocol<FooProtocol, REPLPrintable> = { return_superPrintable() } // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{17-53=FooProtocol & REPLPrintable}}
}
// Test the parser's splitting of >= into > and =.
var x : protocol<P5>= 17 // expected-error {{'protocol<...>' composition syntax has been removed and is not needed here}} {{9-22=P5=}} expected-error {{'=' must have consistent whitespace on both sides}}
var y : protocol<P5, P7>= 17 // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{9-26=P5 & P7=}} expected-error {{'=' must have consistent whitespace on both sides}}
var z : protocol<P5, P7>?=17 // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{9-27=(P5 & P7)?=}}
typealias A1 = protocol<> // expected-error {{'protocol<>' syntax has been removed; use 'Any' instead}} {{16-26=Any}}
typealias A2 = protocol<>? // expected-error {{'protocol<>' syntax has been removed; use 'Any' instead}} {{16-27=Any?}}
typealias B1 = protocol<P1,P2> // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{16-31=P1 & P2}}
typealias B2 = protocol<P1, P2> // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{16-32=P1 & P2}}
typealias B3 = protocol<P1 ,P2> // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{16-32=P1 & P2}}
typealias B4 = protocol<P1 , P2> // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{16-33=P1 & P2}}
typealias C1 = protocol<Any, P1> // expected-error {{'protocol<...>' composition syntax has been removed and is not needed here}} {{16-33=P1}}
typealias C2 = protocol<P1, Any> // expected-error {{'protocol<...>' composition syntax has been removed and is not needed here}} {{16-33=P1}}
typealias D = protocol<P1> // expected-error {{'protocol<...>' composition syntax has been removed and is not needed here}} {{15-27=P1}}
typealias E = protocol<Any> // expected-error {{'protocol<...>' composition syntax has been removed and is not needed here}} {{15-28=Any}}
typealias F = protocol<Any, Any> // expected-error {{'protocol<...>' composition syntax has been removed and is not needed here}} {{15-33=Any}}
typealias G = protocol<P1>.Type // expected-error {{'protocol<...>' composition syntax has been removed and is not needed here}} {{15-27=P1}}
typealias H = protocol<P1>! // expected-error {{'protocol<...>' composition syntax has been removed and is not needed here}} {{15-28=P1!}}
// expected-warning@-1 {{using '!' is not allowed here; treating this as '?' instead}}
typealias J = protocol<P1, P2>.Protocol // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{15-31=(P1 & P2)}}
typealias K = protocol<P1, P2>? // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{15-32=(P1 & P2)?}}
typealias T01 = P1.Protocol & P2 // expected-error {{non-protocol, non-class type 'P1.Protocol' cannot be used within a protocol-constrained type}}
typealias T02 = P1.Type & P2 // expected-error {{non-protocol, non-class type 'P1.Type' cannot be used within a protocol-constrained type}}
typealias T03 = P1? & P2 // expected-error {{non-protocol, non-class type 'P1?' cannot be used within a protocol-constrained type}}
typealias T04 = P1 & P2! // expected-error {{non-protocol, non-class type 'P2?' cannot be used within a protocol-constrained type}}
// expected-warning@-1 {{using '!' is not allowed here; treating this as '?' instead}}
typealias T05 = P1 & P2 -> P3 // expected-error {{single argument function types require parentheses}} {{17-17=(}} {{24-24=)}}
typealias T06 = P1 -> P2 & P3 // expected-error {{single argument function types require parentheses}} {{17-17=(}} {{19-19=)}}
typealias T07 = P1 & protocol<P2, P3> // expected-error {{protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{22-38=P2 & P3}}
func fT07(x: T07) -> P1 & P2 & P3 { return x } // OK, 'P1 & protocol<P2, P3>' is parsed as 'P1 & P2 & P3'.
let _: P1 & P2 & P3 -> P1 & P2 & P3 = fT07 // expected-error {{single argument function types require parentheses}} {{8-8=(}} {{20-20=)}}
struct S01: P5 & P6 {}
struct S02: P5? & P6 {} // expected-error {{non-protocol, non-class type 'P5?' cannot be used within a protocol-constrained type}}
struct S03: Optional<P5> & P6 {} // expected-error {{non-protocol, non-class type 'Optional<P5>' cannot be used within a protocol-constrained type}}
struct S04<T : P5 & (P6)> {}
struct S05<T> where T : P5? & P6 {} // expected-error 2{{non-protocol, non-class type 'P5?' cannot be used within a protocol-constrained type}}
// SR-3124 - Protocol Composition Often Migrated Incorrectly
struct S3124<T: protocol<P1, P3>> {} // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{17-34=P1 & P3>}}
func f3124_1<U where U: protocol<P1, P3>>(x: U) {} // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}} {{25-42=P1 & P3>}} // expected-error {{'where' clause}}
func f3124_2<U : protocol<P1>>(x: U) {} // expected-error {{'protocol<...>' composition syntax has been removed and is not needed here}} {{18-31=P1>}}
// Make sure we correctly form compositions in expression context
func takesP1AndP2(_: [AnyObject & P1 & P2]) {}
takesP1AndP2([AnyObject & P1 & P2]())
takesP1AndP2([Swift.AnyObject & P1 & P2]())
takesP1AndP2([AnyObject & protocol_composition.P1 & P2]())
takesP1AndP2([AnyObject & P1 & protocol_composition.P2]())
takesP1AndP2([DoesNotExist & P1 & P2]()) // expected-error {{cannot find 'DoesNotExist' in scope}}
takesP1AndP2([Swift.DoesNotExist & P1 & P2]()) // expected-error {{module 'Swift' has no member named 'DoesNotExist'}}
typealias T08 = P1 & inout P2 // expected-error {{'inout' may only be used on parameters}}
typealias T09 = P1 & __shared P2 // expected-error {{'__shared' may only be used on parameters}}
typealias T10 = P1 & __owned P2 // expected-error {{'__owned' may only be used on parameters}}
| apache-2.0 | 90a92ff5fcdc269fd1bc3e55990991a9 | 51.766667 | 224 | 0.673194 | 3.548001 | false | false | false | false |
naokits/my-programming-marathon | iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift | 2 | 2023 | //
// UIBarButtonItem+Rx.swift
// RxCocoa
//
// Created by Daniel Tartaglia on 5/31/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
var rx_tap_key: UInt8 = 0
extension UIBarButtonItem {
/**
Bindable sink for `enabled` property.
*/
public var rx_enabled: AnyObserver<Bool> {
return UIBindingObserver(UIElement: self) { UIElement, value in
UIElement.enabled = value
}.asObserver()
}
/**
Reactive wrapper for target action pattern on `self`.
*/
public var rx_tap: ControlEvent<Void> {
let source = rx_lazyInstanceObservable(&rx_tap_key) { () -> Observable<Void> in
Observable.create { [weak self] observer in
guard let control = self else {
observer.on(.Completed)
return NopDisposable.instance
}
let target = BarButtonItemTarget(barButtonItem: control) {
observer.on(.Next())
}
return target
}
.takeUntil(self.rx_deallocated)
.share()
}
return ControlEvent(events: source)
}
}
@objc
class BarButtonItemTarget: RxTarget {
typealias Callback = () -> Void
weak var barButtonItem: UIBarButtonItem?
var callback: Callback!
init(barButtonItem: UIBarButtonItem, callback: () -> Void) {
self.barButtonItem = barButtonItem
self.callback = callback
super.init()
barButtonItem.target = self
barButtonItem.action = #selector(BarButtonItemTarget.action(_:))
}
override func dispose() {
super.dispose()
#if DEBUG
MainScheduler.ensureExecutingOnScheduler()
#endif
barButtonItem?.target = nil
barButtonItem?.action = nil
callback = nil
}
func action(sender: AnyObject) {
callback()
}
}
#endif
| mit | 7ff09c34c5bb795a229bd46db36809aa | 22.511628 | 87 | 0.582097 | 4.658986 | false | false | false | false |
naokits/my-programming-marathon | iPhoneSensorDemo/Pods/RxSwift/RxSwift/Observables/Implementations/Sample.swift | 60 | 3372 | //
// Sample.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/1/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class SamplerSink<O: ObserverType, ElementType, SampleType where O.E == ElementType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias E = SampleType
typealias Parent = SampleSequenceSink<O, SampleType>
private let _parent: Parent
var _lock: NSRecursiveLock {
return _parent._lock
}
init(parent: Parent) {
_parent = parent
}
func on(event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(event: Event<E>) {
switch event {
case .Next:
if let element = _parent._element {
if _parent._parent._onlyNew {
_parent._element = nil
}
_parent.forwardOn(.Next(element))
}
if _parent._atEnd {
_parent.forwardOn(.Completed)
_parent.dispose()
}
case .Error(let e):
_parent.forwardOn(.Error(e))
_parent.dispose()
case .Completed:
if let element = _parent._element {
_parent._element = nil
_parent.forwardOn(.Next(element))
}
if _parent._atEnd {
_parent.forwardOn(.Completed)
_parent.dispose()
}
}
}
}
class SampleSequenceSink<O: ObserverType, SampleType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias Parent = Sample<Element, SampleType>
private let _parent: Parent
let _lock = NSRecursiveLock()
// state
private var _element = nil as Element?
private var _atEnd = false
private let _sourceSubscription = SingleAssignmentDisposable()
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func run() -> Disposable {
_sourceSubscription.disposable = _parent._source.subscribe(self)
let samplerSubscription = _parent._sampler.subscribe(SamplerSink(parent: self))
return StableCompositeDisposable.create(_sourceSubscription, samplerSubscription)
}
func on(event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(event: Event<Element>) {
switch event {
case .Next(let element):
_element = element
case .Error:
forwardOn(event)
dispose()
case .Completed:
_atEnd = true
_sourceSubscription.dispose()
}
}
}
class Sample<Element, SampleType> : Producer<Element> {
private let _source: Observable<Element>
private let _sampler: Observable<SampleType>
private let _onlyNew: Bool
init(source: Observable<Element>, sampler: Observable<SampleType>, onlyNew: Bool) {
_source = source
_sampler = sampler
_onlyNew = onlyNew
}
override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable {
let sink = SampleSequenceSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
} | mit | a96f5d1641e00869d8391683db683146 | 25.139535 | 89 | 0.569861 | 4.788352 | false | false | false | false |
johnpatrickmorgan/LifecycleHooks | Sources/SwiftExtensions.swift | 1 | 2062 | //
// StableSort.swift
// Pods
//
// Created by John Morgan on 07/04/2016.
//
//
import Foundation
// Adapted from http://airspeedvelocity.net/2016/01/10/writing-a-generic-stable-sort/
// and http://sketchytech.blogspot.co.uk/2016/03/swift-sticking-together-with.html
// Enables stable sorting of arrays.
extension RangeReplaceableCollection where Index == Int {
public mutating func stableSortInPlace(
isOrderedBefore: @escaping (Iterator.Element,Iterator.Element)->Bool
) {
let N = self.count
var aux: [Iterator.Element] = []
aux.reserveCapacity(numericCast(N))
func merge(lo: Index, mid: Index, hi: Index) {
aux.removeAll(keepingCapacity: true)
var i = lo, j = mid
while i < mid && j < hi {
if isOrderedBefore(self[j],self[i]) {
aux.append(self[j])
j = j + 1
}
else {
aux.append(self[i])
i = i + 1
}
}
aux.append(contentsOf:self[i..<mid])
aux.append(contentsOf:self[j..<hi])
self.replaceSubrange(lo..<hi, with: aux)
}
var sz = 1
while sz < N {
let limit = index(endIndex, offsetBy: -sz)
for lo in stride(from:startIndex, to: limit, by: sz*2) {
if let hi = index(lo, offsetBy:sz*2, limitedBy: endIndex) {
let mid = index(lo, offsetBy: sz)
merge(lo:lo, mid: mid, hi:hi)
}
}
sz *= 2
}
}
}
// A less verbose way to remove objects from arrays by reference.
extension Array where Element: AnyObject {
mutating func removeObject(_ object: Element) {
let index = self.firstIndex { $0 === object }
guard let foundIndex = index else {
return
}
remove(at: foundIndex)
}
}
| mit | efa74b547ff5b85abc99f7a10ef74d6d | 27.246575 | 85 | 0.501455 | 4.322851 | false | false | false | false |
aleufms/JeraUtils | JeraUtils/View/BaseTableViewCell.swift | 1 | 2987 | //
// BaseTableViewCell.swift
// Jera
//
// Created by Alessandro Nakamuta on 8/25/15.
// Copyright (c) 2015 Jera. All rights reserved.
//
import UIKit
import Cartography
public class BaseTableViewCell: UITableViewCell {
public var useCustomSelectionAnimation = false
private(set) var viewLoaded = false
public weak var selectionView: UIView? {
didSet {
let selectionView = self.selectionView ?? self
selectionView.addSubview(transparencyView)
constrain(selectionView, transparencyView) { (selectionView, transparencyView) -> () in
transparencyView.edges == selectionView.edges
}
}
}
public lazy var transparencyView: UIView = {
let transparencyView = UIView()
transparencyView.userInteractionEnabled = false
return transparencyView
}()
public var selectedColor = UIColor(white: 220/255, alpha: 0.4)
public var highlightedColor = UIColor(white: 220/255, alpha: 0.6)
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
public func commonInit() {
selectionView = nil
selectionStyle = .None
backgroundColor = UIColor.clearColor()
}
override public func awakeFromNib() {
super.awakeFromNib()
viewLoaded = true
}
override public func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if !useCustomSelectionAnimation {
let selectionView = self.selectionView ?? self
selectionView.bringSubviewToFront(transparencyView)
UIView.animateWithDuration(0.15, animations: { () -> Void in
if selected {
self.transparencyView.backgroundColor = self.selectedColor
} else {
if !self.highlighted {
self.transparencyView.backgroundColor = UIColor.clearColor()
}
}
})
}
}
override public func setHighlighted(highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
if !useCustomSelectionAnimation {
let selectionView = self.selectionView ?? self
selectionView.bringSubviewToFront(transparencyView)
UIView.animateWithDuration(0.15, animations: { () -> Void in
if highlighted {
self.transparencyView.backgroundColor = self.highlightedColor
} else {
if !self.selected {
self.transparencyView.backgroundColor = UIColor.clearColor()
}
}
})
}
}
}
| mit | 3aa54e952b947367cc52f81cd121dce1 | 27.721154 | 99 | 0.60462 | 5.700382 | false | false | false | false |
jpush/aurora-imui | iOS/sample/sample/IMUIMessageCollectionView/Views/IMUIVideoMessageCell.swift | 1 | 2813 | //
// IMUIVideoMessageCell.swift
// IMUIChat
//
// Created by oshumini on 2017/4/13.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import AVFoundation
class IMUIVideoMessageCell: IMUIBaseMessageCell {
lazy var videoView = UIImageView()
lazy var playBtn = UIButton()
lazy var videoDuration = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
bubbleView.addSubview(self.videoView)
videoView.addSubview(playBtn)
videoView.addSubview(videoDuration)
playBtn.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 56, height: 56))
playBtn.setImage(UIImage.imuiImage(with: "video_play_btn"), for: .normal)
videoDuration.textColor = UIColor.white
videoDuration.font = UIFont.systemFont(ofSize: 10.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
playBtn.center = CGPoint(x: videoView.imui_width/2, y: videoView.imui_height/2)
let durationX = self.bubbleView.imui_width - 30
let durationY = self.bubbleView.imui_height - 24
videoDuration.frame = CGRect(x: durationX,
y: durationY,
width: 30,
height: 24)
}
override func presentCell(with message: IMUIMessageModelProtocol, viewCache: IMUIReuseViewCache , delegate: IMUIMessageMessageCollectionViewDelegate?) {
super.presentCell(with: message, viewCache: viewCache, delegate: delegate)
self.layoutVideo(with: message.mediaFilePath())
let layout = message.layout as! IMUIMessageCellLayout
self.videoView.frame = UIEdgeInsetsInsetRect(CGRect(origin: CGPoint.zero, size: layout.bubbleFrame.size), layout.bubbleContentInset)
}
func layoutVideo(with videoPath: String) {
let asset = AVURLAsset(url: URL(fileURLWithPath: videoPath), options: nil)
let seconds = Int (CMTimeGetSeconds(asset.duration))
if seconds/3600 > 0 {
videoDuration.text = "\(seconds/3600):\(String(format: "%02d", (seconds/3600)%60)):\(seconds%60)"
} else {
videoDuration.text = "\(seconds / 60):\(String(format: "%02d", seconds % 60))"
}
let serialQueue = DispatchQueue(label: "videoLoad")
serialQueue.async {
do {
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
DispatchQueue.main.async {
self.videoView.image = UIImage(cgImage: cgImage)
}
} catch {
DispatchQueue.main.async {
self.videoView.image = nil
}
}
}
}
}
| mit | e4715a85644b1c852f7b3e3bda45a5a7 | 32.452381 | 154 | 0.661566 | 4.376947 | false | false | false | false |
mlgoogle/viossvc | viossvc/General/Helper/CurrentUserHelper.swift | 1 | 5211 | //
// CurrentUserHelper.swift
// viossvc
//
// Created by yaowang on 2016/11/24.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
import SVProgressHUD
class CurrentUserHelper: NSObject {
static let shared = CurrentUserHelper()
private let keychainItem:OEZKeychainItemWrapper = OEZKeychainItemWrapper(identifier: "com.yundian.viossvc.account", accessGroup:nil)
private var _userInfo:UserInfoModel?
private var _password:String!
private var _deviceToken:String? = NSUserDefaults.standardUserDefaults().objectForKey("DeviceToken") as? String
private var _firstLanuch = true
var deviceToken:String! {
get {
return _deviceToken ?? ""
}
set {
_deviceToken = newValue
updateDeviceToken()
}
}
var userInfo:UserInfoModel! {
get {
return _userInfo ?? UserInfoModel()
}
}
var isLogin : Bool {
return _userInfo != nil
}
var uid : Int {
return _userInfo!.uid
}
func userLogin(phone:String,password:String,complete:CompleteBlock,error:ErrorBlock) {
let loginModel = LoginModel()
loginModel.phone_num = phone
loginModel.passwd = password
_password = password
AppAPIHelper.userAPI().login(loginModel, complete: { [weak self] (model) in
self?.loginComplete(model)
complete(model)
}, error:error)
}
func autoLogin(complete:CompleteBlock,error:ErrorBlock) -> Bool {
let account = lastLoginAccount()
if !NSString.isEmpty(account.phone) && !NSString.isEmpty(account.password) {
userLogin(account.phone!, password:account.password!, complete: complete, error: error)
return true
}
return false
}
private func loginComplete(model:AnyObject?) {
self._userInfo = model as? UserInfoModel
keychainItem.resetKeychainItem()
keychainItem.setObject(_userInfo!.phone_num, forKey: kSecAttrAccount)
keychainItem.setObject(_password, forKey: kSecValueData)
updateDeviceToken()
if _firstLanuch {
versionCheck()
_firstLanuch = false
}
requestUserCash()
checkAuthStatus()
}
//查询用户余额
func requestUserCash() {
AppAPIHelper.userAPI().userCash(CurrentUserHelper.shared.userInfo.uid, complete: { (result) in
if result == nil{
return
}
let resultDic = result as? Dictionary<String, AnyObject>
if let hasPassword = resultDic!["has_passwd_"] as? Int{
CurrentUserHelper.shared.userInfo.has_passwd_ = hasPassword
}
if let userCash = resultDic!["user_cash_"] as? Int{
CurrentUserHelper.shared.userInfo.user_cash_ = userCash
}
}, error: { (err) in
})
}
/**
查询认证状态
*/
func checkAuthStatus() {
AppAPIHelper.userAPI().anthStatus(CurrentUserHelper.shared.userInfo.uid, complete: { (result) in
if let errorReason = result?.valueForKey("failed_reason_") as? String {
if errorReason.characters.count != 0 {
SVProgressHUD.showErrorMessage(ErrorMessage: errorReason, ForDuration: 1,
completion: nil)
}
}
if let status = result?.valueForKey("review_status_") as? Int {
CurrentUserHelper.shared.userInfo.auth_status_ = status
}
}, error: { (err) in
})
}
func versionCheck() {
AppAPIHelper.commenAPI().version({ (model) in
if let verInfo = model as? [String:AnyObject] {
UpdateManager.checking4Update(verInfo["newVersion"] as! String, buildVer: verInfo["buildVersion"] as! String, forced: verInfo["mustUpdate"] as! Bool, result: { (gotoUpdate) in
if gotoUpdate {
UIApplication.sharedApplication().openURL(NSURL.init(string: verInfo["DetailedInfo"] as! String)!)
if (verInfo["mustUpdate"] as? Bool)! {
exit(0)
}
}
})
}
}, error: { (err) in
})
}
func logout() {
AppAPIHelper.userAPI().logout(_userInfo!.uid)
nodifyPassword("")
self._userInfo = nil
}
func nodifyPassword(password:String) {
keychainItem.setObject(password, forKey: kSecValueData)
}
func lastLoginAccount()->(phone:String?,password:String?){
return (keychainItem.objectForKey(kSecAttrAccount) as? String,keychainItem.objectForKey(kSecValueData) as? String)
}
private func updateDeviceToken() {
if isLogin && _deviceToken != nil {
AppAPIHelper.userAPI().updateDeviceToken(uid, deviceToken: _deviceToken!, complete: nil, error: nil)
}
}
}
| apache-2.0 | 8fe24aeb49069f6230b3180780f29b29 | 31.810127 | 191 | 0.566937 | 4.989413 | false | false | false | false |
t2421/iOS-snipet | iOS-snipets/BrowseCodeViewController.swift | 1 | 1691 | //
// BrowseCodeViewController.swift
// iOS-snipets
//
// Created by taigakiyotaki on 2015/07/28.
// Copyright (c) 2015年 taigakiyotaki. All rights reserved.
//
import UIKit
import SVProgressHUD
class BrowseCodeViewController: UIViewController,UIWebViewDelegate {
@IBOutlet weak var webview: UIWebView!
var urlString:String?
override func viewDidLoad() {
super.viewDidLoad()
self.webview.delegate = self
startLoad()
SVProgressHUD.showWithStatus("loading..." ,maskType: SVProgressHUDMaskType.Gradient)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startLoad(){
SVProgressHUD.show()
if((self.urlString) == nil){
return;
}
print("start")
let url = NSURL(string: self.urlString!)
let request = NSURLRequest(URL: url!)
self.webview.loadRequest(request)
}
func webViewDidFinishLoad(webView: UIWebView) {
SVProgressHUD.dismiss()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
SVProgressHUD.dismiss()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | eedaa12e12f4dc79b6ecdf58f49ccac5 | 26.688525 | 106 | 0.646536 | 5.011869 | false | false | false | false |
CYXiang/CYXSwift2.0 | 14-构造函数/14-构造函数/Person.swift | 1 | 1900 | //
// Person.swift
// 14-构造函数
//
// Created by xiaomage on 15/11/5.
// Copyright © 2015年 xiaomage. All rights reserved.
//
import UIKit
class Person: NSObject {
// 一个对象在初始化时必须给所有的成员变量赋值
var name: String?
// 注意点: 如果自定义一个对象, 而对象的属性如果又是基本数据类型, 那么不建议设置为可选类型
// 而是应该赋值为0, 或者-1
// 总结规律: 对象类型设置为可选类型, 基本数据类型赋值初始值
var age: Int = -1
// 如果既没有重写也没有自定义, 那么系统会给我们提供一个默认的构造方法
// 如果自定了构造方法, 并且没有重写默认构造方法, 那么系统默认的构造方法就会失效
// 重写父类构造方法
// 以后但凡看到override, 就代表是重写父类的
override init() {
name = "lnj"
age = 30
// 系统悄悄咪咪的帮我们调用了一次super.init()
// super.init()
}
// 自定义构造
init(name: String, age: Int)
{
self.name = name
self.age = age
}
init(dict: [String: AnyObject])
{
// 注意: 如果想在Swift的构造方法中使用KVC, 必须先手动调用super.init
super.init()
setValuesForKeysWithDictionary(dict)
}
// 如果利用KVC赋值, 但是字典和模型的属性不能一一对应, 就会调用下面这个方法
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
// 只要重写这个属性, 就相当于OC中重写description方法
override var description: String {
// 优化
let property = ["name", "age"]
let dict = dictionaryWithValuesForKeys(property)
return "\(dict)"
// return "name = \(self.name), age = \(self.age)"
}
}
| apache-2.0 | 9362c5842cb278f74c8711d83fb38e31 | 21.559322 | 76 | 0.592787 | 3.146572 | false | false | false | false |
lsonlee/Swift_MVVM | Swift_Project/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotate.swift | 2 | 2750 | //
// NVActivityIndicatorBallClipRotate.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class NVActivityIndicatorAnimationBallClipRotate: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let duration: CFTimeInterval = 0.75
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.6, 1]
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi]
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = NVActivityIndicatorShape.ringThirdFour.layerWith(size: CGSize(width: size.width, height: size.height), color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit | 2903d11feb7bbbb63f1da51a394539ee | 40.044776 | 137 | 0.701818 | 4.893238 | false | false | false | false |
do-my-best/SQLiteManager | SQLiteManager/Person.swift | 1 | 2630 | //
// Person.swift
// SQLiteManager
//
// Created by liuzhu on 15/11/5.
// Copyright © 2015年 liuzhu. All rights reserved.
//
import UIKit
class Person: NSObject {
//MARK: - 模型属性
///代号
var id = 0
///姓名
var name : String?
///年龄
var age = 0
///身高
var height : Double = 0
///MARK: - 构造函数
init(dict:[String:AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
///MARK: - person 对象的描述
override var description : String{
let keys = ["id", "name", "age", "height"]
return dictionaryWithValuesForKeys(keys).description
}
///从数据库中查询数据,保存在 person 数组中
///
///- returns : 从 sql中读取的数据分条转换成 person 对象并保存
class func persons() -> [Person]?{
//1.准备 sql
let sql = "select id,name,age,height from T_Person"
//2.访问数据库,获取字典数组
let dictArray = SQLiteManager.sharedManager.execRecord(sql)
//3.字典转模型
//定义person数组,保存字典
var persons : [Person] = [Person]()
for c in dictArray!{
persons.append(Person(dict: c))
}
//4.返回结果
return persons
}
///用 person 对象更新数据库中的内容
///
///- returns : 是否成功
func updatePerson() -> Bool{
//1.准备 sql
let sql = "update T_Person set name = '\(name)',age = '\(age)',height = '\(height)'"
let row = SQLiteManager.sharedManager.execUpdate(sql)
print("更新了\(row)条内容")
return row > 0
}
///删除数据库中与 person 对象的属性'name'相同的数据
///
///- returns : 是否成功
func deletePerson() -> Bool{
//1.准备 sql
let sql = "delete from T_Person where name = '\(name)'"
let row = SQLiteManager.sharedManager.execUpdate(sql)
print("删除了\(row)条内容")
return row > 0
}
///将当前对象的属性插入到数据库中
///
///- returns : 是否成功
func insertPerson() ->Bool{
//1.准备 sql
let sql = "insert into T_Person (name,age,height) values ('\(name!)',\(age),\(height));"
//2.返回结果
return SQLiteManager.sharedManager.execInsert(sql) > 0
}
}
| mit | 4721e67b8b4bdd72001cc1ec06100ea8 | 19.954545 | 96 | 0.494143 | 4.130824 | false | false | false | false |
MobileOrg/mobileorg | MobileOrgTests/Sync/iCloud/CloudTransferManagerTests.swift | 1 | 10327 | //
// CloudTransferManagerTests.swift
// MobileOrgTests
//
// Created by Artem Loenko on 10/10/2019.
// Copyright © 2019 Artem Loenko.
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
import XCTest
@testable import MobileOrg
class CloudTransferManagerTests: XCTestCase {
private var lastKnownCloudStorageDocumentsURL: URL?
override func tearDown() {
self.cleanUpDocuments()
self.cleanUpCloudDocuments()
self.lastKnownCloudStorageDocumentsURL = nil
}
private func cleanUpDocuments() {
// Clean up ~/Documents
let path = NSString(string: "~/Documents").expandingTildeInPath
guard let files = try? FileManager.default.contentsOfDirectory(atPath: path) else { return }
for filename in files {
guard filename.starts(with: "\(type(of: self))") else { continue }
try? FileManager.default.removeItem(atPath: "\(path)\\\(filename)")
}
}
private func cleanUpCloudDocuments() {
// Clean up iCloud storage
guard let url = self.lastKnownCloudStorageDocumentsURL,
let files = try? FileManager.default.contentsOfDirectory(atPath: url.path) else { return }
for filename in files {
guard filename.starts(with: "\(type(of: self))") else { continue }
let filePath = url.appendingPathComponent(filename)
try? FileManager.default.removeItem(atPath: filePath.path)
}
}
// MARK: Tests
func test_thatManagerInitializedInProperState() {
let sut = CloudTransferManager()
guard sut.isAvailable else {
print("iCloud is not available in the simulator. Skipping the test.")
return
}
XCTAssertFalse(sut.busy())
XCTAssertEqual(sut.queueSize(), 0)
}
func test_thatManagerFailsCorrectlyOnDownloadWhenTransferContextIsMalformed() {
self.ensureTransferContextFailureBehavior(for: TransferTypeDownload)
}
func test_thatManagerFailsCorrectlyOnUploadWhenTransferContextIsMailformed() {
self.ensureTransferContextFailureBehavior(for: TransferTypeUpload)
}
func test_thatManagerRespectsPauseResumeOptions() {
// Given
let sut = CloudTransferManager()
guard sut.isAvailable else {
print("iCloud is not available in the simulator. Skipping the test.")
return
}
// When
sut.pause()
let transferDelegate = MockTransferManagerDelegate()
let transferContext = self.mockTransferContext(with: TransferTypeUpload, delegate: transferDelegate)
// Then
transferDelegate.onTransferComplete = { _ in XCTFail("Sut is on pause.") }
transferDelegate.onTransferFailed = { _ in XCTFail("Sut is on pause.") }
sut.enqueueTransfer(transferContext)
XCTAssertTrue(sut.busy())
XCTAssertEqual(sut.queueSize(), 1)
var onTransferFailedWasCalled = false
transferDelegate.onTransferComplete = { _ in XCTFail("Cannot be completed.") }
transferDelegate.onTransferFailed = { _ in onTransferFailedWasCalled = true }
sut.resume()
XCTAssertTrue(onTransferFailedWasCalled)
}
func test_thatManagerHandlesAbortAppropriately() {
// Given
let sut = CloudTransferManager()
guard sut.isAvailable else {
print("iCloud is not available in the simulator. Skipping the test.")
return
}
// When
let transferDelegate = MockTransferManagerDelegate()
let transferContext = self.mockTransferContext(with: TransferTypeUpload, delegate: transferDelegate)
transferDelegate.onTransferComplete = { _ in XCTFail("Sut is not running.") }
transferDelegate.onTransferFailed = { _ in XCTFail("Sut is not running.") }
// Then
sut.pause()
sut.enqueueTransfer(transferContext)
XCTAssertEqual(sut.queueSize(), 1)
sut.abort()
XCTAssertEqual(sut.queueSize(), 0)
}
func test_thatManagerHandlesUploadProperly() {
self.tranferFileBetweenStorages(for: TransferTypeUpload)
}
func test_thatManagerHandlesDownloadProperly() {
self.tranferFileBetweenStorages(for: TransferTypeDownload)
}
// MARK: Helpers
private func tranferFileBetweenStorages(for type: TransferType) {
// Given
let sut = CloudTransferManager()
guard sut.isAvailable else {
print("iCloud is not available in the simulator. Skipping the test.")
return
}
self.waitForCloudURL(for: sut)
// When
XCTAssertNotNil(sut.iCloudStorageDocumentsURL)
let (localFile, remoteURL) = { () -> (String, URL) in
if type == TransferTypeUpload {
let tempLocalFile = self.createLocalFile()
let tempCloudFile = (sut.iCloudStorageDocumentsURL?.appendingPathComponent(String(tempLocalFile.split(separator: "/").last!)))!
return (tempLocalFile, tempCloudFile)
} else {
let tempCloudFile = self.createCloudFile(sut: sut)!
let tempLocalFile = NSString(string: "~/Documents/\(tempCloudFile.lastPathComponent)").expandingTildeInPath
return (tempLocalFile, tempCloudFile)
}
}()
let transferDelegate = MockTransferManagerDelegate()
let transferContext = self.mockTransferContext(
with: type,
delegate: transferDelegate,
remoteURL: remoteURL,
localFile: localFile)
let transferExpectation = expectation(description: "Wait for the result")
transferDelegate.onTransferFailed = { _ in XCTFail("The transfer suppose to succeed.") }
transferDelegate.onTransferComplete = { _ in transferExpectation.fulfill() }
// Then
sut.enqueueTransfer(transferContext)
wait(for: [ transferExpectation ], timeout: 1)
}
private func createCloudFile(sut: CloudTransferManager, with content: String? = "TestData") -> URL? {
guard let cloudURL = sut.iCloudStorageDocumentsURL else {
XCTFail("iCloud URL is not available.")
return nil
}
let path = cloudURL.appendingPathComponent("\(type(of: self))-\(UUID().uuidString).org")
let data = content?.data(using: .utf8)!
FileManager.default.createFile(atPath: path.path, contents: data, attributes: nil)
return path
}
private func createLocalFile(with content: String? = "TestData") -> String {
let path = NSString(string: "~/Documents/\(type(of: self))-\(UUID().uuidString).org").expandingTildeInPath
let data = content?.data(using: .utf8)!
FileManager.default.createFile(atPath: path, contents: data, attributes: nil)
return path
}
private func waitForCloudURL(for sut: CloudTransferManager) {
// We have to wait a bit for a proper URL from iCloud storage...
let iCloudStorageDocumentsURLExpectation = expectation(description: "Waiting for iCloudStorageDocumentsURL...")
DispatchQueue.global(qos: .userInitiated).async {
while(true) {
guard sut.iCloudStorageDocumentsURL != nil else {
Thread.sleep(forTimeInterval: 0.25)
continue
}
self.lastKnownCloudStorageDocumentsURL = sut.iCloudStorageDocumentsURL
DispatchQueue.main.async { iCloudStorageDocumentsURLExpectation.fulfill() }
break
}
}
wait(for: [ iCloudStorageDocumentsURLExpectation ], timeout: 1)
}
private func ensureTransferContextFailureBehavior(for type: TransferType) {
// Given
let sut = CloudTransferManager()
guard sut.isAvailable else {
print("iCloud is not available in the simulator. Skipping the test.")
return
}
// When
let transferDelegate = MockTransferManagerDelegate()
let transferContext = self.mockTransferContext(with: type, delegate: transferDelegate)
// Then
transferDelegate.onTransferComplete = { _ in XCTFail("The transfer has to fail.") }
var onTransferFailedWasCalled = false
transferDelegate.onTransferFailed = { context in
onTransferFailedWasCalled = true
XCTAssertEqual(transferContext, context)
XCTAssertFalse(transferContext.success)
XCTAssertNotNil(transferContext.errorText)
}
sut.enqueueTransfer(transferContext)
XCTAssertTrue(onTransferFailedWasCalled)
}
// Will always fail with default `remoteURL` and `localFile` arguments
private func mockTransferContext(
with type: TransferType,
delegate: MockTransferManagerDelegate? = nil,
remoteURL: URL? = URL(string: "unreachable:///\(UUID().uuidString)")!,
localFile: String? = "unreachable:////\(UUID().uuidString)") -> TransferContext {
let context = TransferContext()
context.remoteUrl = remoteURL
context.localFile = localFile
context.transferType = type
context.delegate = delegate
return context
}
}
private class MockTransferManagerDelegate: NSObject, TransferManagerDelegate {
var onTransferFailed: ((_ context: TransferContext) -> Void)?
func transferFailed(_ context: TransferContext!) { self.onTransferFailed?(context) }
var onTransferComplete: ((_ context: TransferContext) -> Void)?
func transferComplete(_ context: TransferContext!) { self.onTransferComplete?(context) }
}
| gpl-2.0 | c04509ece01261308d676528f60ff7af | 39.178988 | 143 | 0.660178 | 5.295385 | false | true | false | false |
tomasharkema/R.swift | Sources/RswiftCore/ResourceTypes/AssetFolder.swift | 3 | 5828 | //
// AssetFolder.swift
// R.swift
//
// Created by Mathijs Kadijk on 09-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
// Note: "appiconset" is not loadable by default, so it's not included here
private let imageExtensions: Set<String> = ["launchimage", "imageset", "imagestack"]
private let colorExtensions: Set<String> = ["colorset"]
// Ignore everything in folders with these extensions
private let ignoredExtensions: Set<String> = ["brandassets", "imagestacklayer"]
// Files checked for asset folder and subfolder properties
private let assetPropertiesFilenames: Array<(fileName: String, fileExtension: String)> = [("Contents","json")]
struct AssetFolder: WhiteListedExtensionsResourceType, NamespacedAssetSubfolderType {
static let supportedExtensions: Set<String> = ["xcassets"]
let url: URL
let name: String
let path = ""
let resourcePath = ""
var imageAssets: [String]
var colorAssets: [String]
var subfolders: [NamespacedAssetSubfolder]
init(url: URL, fileManager: FileManager) throws {
self.url = url
try AssetFolder.throwIfUnsupportedExtension(url.pathExtension)
guard let filename = url.filename else {
throw ResourceParsingError.parsingFailed("Couldn't extract filename from URL: \(url)")
}
name = filename
// Browse asset directory recursively and list only the assets folders
var imageAssetURLs = [URL]()
var colorAssetURLs = [URL]()
var namespaces = [URL]()
let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles, errorHandler: nil)
if let enumerator = enumerator {
for case let fileURL as URL in enumerator {
let pathExtension = fileURL.pathExtension
if fileURL.providesNamespace() {
namespaces.append(fileURL.namespaceURL)
}
if imageExtensions.contains(pathExtension) {
imageAssetURLs.append(fileURL)
}
if colorExtensions.contains(pathExtension) {
colorAssetURLs.append(fileURL)
}
if ignoredExtensions.contains(pathExtension) {
enumerator.skipDescendants()
}
}
}
subfolders = []
imageAssets = []
colorAssets = []
namespaces.sort { $0.absoluteString < $1.absoluteString }
for namespace in namespaces.map(NamespacedAssetSubfolder.init) {
populateSubfolders(subfolder: namespace)
}
for assetURL in imageAssetURLs {
populateImageAssets(asset: assetURL)
}
for assetURL in colorAssetURLs {
populateColorAssets(asset: assetURL)
}
}
}
protocol NamespacedAssetSubfolderType {
var url: URL { get }
var path: String { get }
var resourcePath: String { get }
var imageAssets: [String] { get set }
var colorAssets: [String] { get set }
var subfolders: [NamespacedAssetSubfolder] { get set }
}
extension NamespacedAssetSubfolderType {
mutating func populateSubfolders(subfolder: NamespacedAssetSubfolder) {
if var parent = subfolders.first(where: { subfolder.isSubfolderOf($0) }) {
parent.populateSubfolders(subfolder: subfolder)
} else {
let name = SwiftIdentifier(name: subfolder.name)
let resourceName = SwiftIdentifier(rawValue: subfolder.name)
subfolder.path = path != "" ? "\(path).\(name)" : "\(name)"
subfolder.resourcePath = resourcePath != "" ? "\(resourcePath)/\(resourceName)" : "\(resourceName)"
subfolders.append(subfolder)
}
}
mutating func populateImageAssets(asset: URL) {
if var parent = subfolders.first(where: { asset.matches($0.url) }) {
parent.populateImageAssets(asset: asset)
} else {
if let filename = asset.filename {
imageAssets.append(filename)
}
}
}
mutating func populateColorAssets(asset: URL) {
if var parent = subfolders.first(where: { asset.matches($0.url) }) {
parent.populateColorAssets(asset: asset)
} else {
if let filename = asset.filename {
colorAssets.append(filename)
}
}
}
func isSubfolderOf(_ subfolder: NamespacedAssetSubfolder) -> Bool {
return url.absoluteString != subfolder.url.absoluteString && url.matches(subfolder.url)
}
}
class NamespacedAssetSubfolder: NamespacedAssetSubfolderType {
let url: URL
let name: String
var path: String = ""
var resourcePath: String = ""
var imageAssets: [String] = []
var colorAssets: [String] = []
var subfolders: [NamespacedAssetSubfolder] = []
init(url: URL) {
self.url = url
self.name = url.namespace
}
}
fileprivate extension URL {
func providesNamespace() -> Bool {
guard isFileURL else { return false }
let isPropertiesFile = assetPropertiesFilenames.contains(where: { arg -> Bool in
let (fileName, fileExtension) = arg
guard let pathFilename = self.filename else {
return false
}
let pathExtension = self.pathExtension
return pathFilename == fileName && pathExtension == fileExtension
})
guard isPropertiesFile else { return false }
guard let data = try? Data(contentsOf: self) else { return false }
guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else { return false }
guard let dict = json as? [String: Any] else { return false }
guard let properties = dict["properties"] as? [String: Any] else { return false }
guard let providesNamespace = properties["provides-namespace"] as? Bool else { return false }
return providesNamespace
}
var namespace: String {
return lastPathComponent
}
var namespaceURL: URL {
return deletingLastPathComponent()
}
// Returns whether self is descendant of namespace
func matches(_ namespace: URL) -> Bool {
return self.absoluteString.hasPrefix(namespace.absoluteString)
}
}
| mit | b011f114e2042054c2c54e6638916365 | 31.021978 | 132 | 0.689602 | 4.489985 | false | false | false | false |
edragoev1/pdfjet | Sources/Example_16/main.swift | 1 | 1940 | import Foundation
import PDFjet
/**
* Example_16.java
*
*/
public class Example_16 {
public init() throws {
let stream = OutputStream(toFileAtPath: "Example_16.pdf", append: false)
let pdf = PDF(stream!)
let f1 = Font(pdf, CoreFont.HELVETICA)
f1.setSize(14.0)
let page = Page(pdf, Letter.PORTRAIT)
var colors = [String : UInt32]()
colors["Lorem"] = Color.blue
colors["ipsum"] = Color.red
colors["dolor"] = Color.green
colors["ullamcorper"] = Color.gray
let gs = GraphicsState()
gs.setAlphaStroking(0.5) // Stroking alpha
gs.setAlphaNonStroking(0.5) // Nonstroking alpha
page.setGraphicsState(gs)
f1.setSize(72.0)
let text = TextLine(f1, "Hello, World")
text.setLocation(50.0, 300.0)
text.drawOn(page)
let latinText = try String(contentsOfFile: "data/latin.txt", encoding: String.Encoding.utf8)
f1.setSize(14.0)
let textBox = TextBox(f1, latinText)
textBox.setLocation(50.0, 50.0)
textBox.setWidth(400.0)
// If no height is specified the height will be calculated based on the text.
// textBox.setHeight(400.0)
// textBox.setVerticalAlignment(Align.TOP)
// textBox.setVerticalAlignment(Align.BOTTOM)
// textBox.setVerticalAlignment(Align.CENTER)
textBox.setBgColor(Color.whitesmoke);
textBox.setTextColors(colors)
let xy = textBox.drawOn(page)
page.setGraphicsState(GraphicsState()) // Reset GS
let box = Box()
box.setLocation(xy[0], xy[1])
box.setSize(20.0, 20.0)
box.drawOn(page)
pdf.complete()
}
} // End of Example_16.swift
let time0 = Int64(Date().timeIntervalSince1970 * 1000)
_ = try Example_16()
let time1 = Int64(Date().timeIntervalSince1970 * 1000)
print("Example_16 => \(time1 - time0)")
| mit | ead175ecfd2d2bc83e9bce44da3edaf6 | 27.955224 | 100 | 0.61134 | 3.709369 | false | false | false | false |
mothule/RNDebugMenu | RNDebugMenu/RNDebugViewController.swift | 1 | 6525 | //
// RNDebugViewController.swift
// ResearchWindow
//
// Created by mothule on 2016/08/30.
// Copyright © 2016年 mothule. All rights reserved.
//
import Foundation
import UIKit
protocol RNDebugItemDatasource {
func getItems() -> [RNDebugItem]
}
protocol RNDebugViewControllerListener {
func closeWindow()
}
open class RNDebugViewController : UIViewController {
var dataSource:RNDebugItemDatasource!
var listener:RNDebugViewControllerListener!
override open func viewDidLoad() {
super.viewDidLoad()
let view = buildScrollView()
self.view.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
self.view.addConstraints([
NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 15),
NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -10),
NSLayoutConstraint(item: view, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: 10),
NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1, constant: -10),
])
// Add a close button
let closeButton = buildCloseButton()
self.view.addSubview(closeButton)
let stackView = buildVerticalStackView()
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraints([
NSLayoutConstraint(item: stackView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: stackView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: stackView, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: stackView, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: 0),
])
let guideView = buildGuideView()
guideView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(guideView)
self.view.addConstraints([
NSLayoutConstraint(item: guideView, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1, constant: 0),
NSLayoutConstraint(item: guideView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant:0),
NSLayoutConstraint(item: guideView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 15),
NSLayoutConstraint(item: guideView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 15),
])
}
fileprivate func buildCloseButton() -> UIButton {
class RNTapExpandableButton : UIButton{
override fileprivate func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return CGRect(x: bounds.origin.x - 3, y: bounds.origin.y - 10, width: bounds.width + 6, height: bounds.height + 20).contains(point)
}
}
let button = RNTapExpandableButton(type: .system)
button.frame = CGRect(x: 0, y: 0, width: 15, height: 15)
button.setTitleColor(UIColor.white, for: UIControlState())
button.setTitle("X", for: UIControlState())
button.backgroundColor = UIColor.darkGray
button.addTarget(self, action: #selector(RNDebugViewController.onTouchCloseButton(_:)), for: .touchDown)
return button
}
func onTouchCloseButton(_ sender:UIButton){
listener.closeWindow()
}
fileprivate func buildGuideView() -> UIView {
let frame = CGRect(x:0, y: 0, width: 15, height: 15)
let view = RNChangeGuide(frame:frame)
return view
}
fileprivate func buildScrollView() -> UIScrollView{
let scrollView = UIScrollView(frame: CGRect.zero)
scrollView.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
return scrollView
}
fileprivate func buildVerticalStackView() -> UIStackView{
let frame = view.bounds
let stackView = UIStackView(frame: frame)
stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .equalSpacing
stackView.spacing = 8
dataSource.getItems().forEach { item in
let v:UIView = item.viewable.createViewForItem()
stackView.addArrangedSubview(v)
v.translatesAutoresizingMaskIntoConstraints = false
stackView.addConstraints([
NSLayoutConstraint(item: v, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 0, constant: 300)
])
if v is UITextView {
stackView.addConstraint(
NSLayoutConstraint(item: v, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 0, constant: 50)
)
}
}
return stackView
}
}
extension RNDebugViewController : RNDebugItemListener{
func listenChangedValue(){
dataSource.getItems().forEach{ $0.viewable.updateView() }
}
}
open class RNChangeGuide : UIView {
override init(frame: CGRect) {
super.init(frame:frame)
backgroundColor = UIColor.clear
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()!
// Color
let color = UIColor.lightText
context.setStrokeColor(color.cgColor)
// Line Width
context.setLineWidth(2)
let splitSize = 3
for i in 0..<splitSize {
let x = (bounds.size.width / CGFloat(splitSize)) * CGFloat(i)
let points:[CGPoint] = [
CGPoint(x: x, y: bounds.size.height-2), CGPoint(x: bounds.size.width-2, y: x)
]
context.addLines(between: points)
}
context.strokePath()
}
}
| apache-2.0 | 4d94112e3e72f7d205479771dabb544f | 40.278481 | 153 | 0.638914 | 4.64861 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Insurance | PerchReadyApp/apps/Perch/iphone/native/Perch/Models/InsuranceCreditItem.swift | 1 | 668 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
* This is an item that makes up the insurance coverage plan.
*/
class InsuranceCreditItem: NSObject {
var creditName = ""
var creditSavingsString = ""
var creditSavings: Float = 0 {
didSet {
creditSavingsString = NSNumber(float: creditSavings).getCurrencyString()
}
}
init(name: String, savings: Float) {
super.init()
self.creditName = name
self.creditSavings = savings
self.creditSavingsString = NSNumber(float: creditSavings).getCurrencyString()
}
}
| epl-1.0 | 5f4625a48e6fe8163d87671a9776e41f | 24.653846 | 85 | 0.647676 | 4.303226 | false | false | false | false |
4taras4/totp-auth | TOTP/ViperModules/FolderDetails/Module/Interactor/FolderDetailsInteractor.swift | 1 | 1577 | //
// FolderDetailsFolderDetailsInteractor.swift
// TOTP
//
// Created by Tarik on 15/02/2021.
// Copyright © 2021 Taras Markevych. All rights reserved.
//
import OneTimePassword
import Base32
final class FolderDetailsInteractor: FolderDetailsInteractorInput {
weak var output: FolderDetailsInteractorOutput!
func converUserData(users: [User]) {
var codes = [Code]()
var favouritesArray = [Code]()
for u in users {
if let c = convertUser(user: u) {
if u.isFavourite == true {
favouritesArray.append(c)
}
codes.append(c)
}
}
output?.listOfCodes(codes: codes)
}
func convertUser(user: User) -> Code? {
guard let secretData = MF_Base32Codec.data(fromBase32String: user.token),
!secretData.isEmpty else {
print("Invalid secret")
return nil
}
guard let generator = Generator(
factor: .timer(period: 30),
secret: secretData,
algorithm: .sha1,
digits: 6) else {
print("Invalid generator parameters")
return nil
}
let token = Token(name: user.name ?? "", issuer: user.issuer ?? "", generator: generator)
guard let currentCode = token.currentPassword else {
print("Invalid generator parameters")
return nil
}
return Code(name: user.name, issuer: user.issuer, code: currentCode, token: user.token)
}
}
| mit | acdc23fa3d4f960376b9d20827070f8a | 28.735849 | 97 | 0.565355 | 4.718563 | false | false | false | false |
blinksh/blink | Blink/Migrator/1400Migration.swift | 1 | 4372 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Blink is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import CoreData
class MigrationToAppGroup: MigrationStep {
var version: Int { get { 1400 } }
func execute() throws {
// Creating a temporary folder tmp-migration-1400
let homePath = BlinkPaths.homePath() as NSString
let documentsPath = BlinkPaths.documentsPath() as NSString
try [".blink", ".ssh"].forEach {
try copyFiles(original: documentsPath.appendingPathComponent($0),
destination: homePath.appendingPathComponent($0),
attributes: $0 == ".blink")
}
}
func copyFiles(original: String, destination: String, attributes: Bool) throws {
let fm = FileManager.default
let tmpDirectoryPath = BlinkPaths.homePath() + "-1400-migration"
try? fm.removeItem(atPath: tmpDirectoryPath)
try fm.createDirectory(atPath: tmpDirectoryPath,
withIntermediateDirectories: true,
attributes: nil)
defer { try? fm.removeItem(atPath: tmpDirectoryPath) }
print("Temporary directory created")
if fm.fileExists(atPath: destination) {
print("Destination files exist")
try fm.contentsOfDirectory(atPath: destination).forEach { fileName in
let filePath = (destination as NSString).appendingPathComponent(fileName)
print("Creating file \(filePath)")
let tmpFilePath = (tmpDirectoryPath as NSString).appendingPathComponent(fileName)
try fm.copyItem(atPath: filePath, toPath: tmpFilePath)
print("Created file \(filePath)")
}
} else {
print("Destination does not exist. Creating...")
try fm.createDirectory(atPath: destination,
withIntermediateDirectories: true,
attributes: nil)
}
if fm.fileExists(atPath: original) {
print("Original files exist")
try fm.contentsOfDirectory(atPath: original).forEach { fileName in
let filePath = (original as NSString).appendingPathComponent(fileName)
print("Creating file \(filePath)")
let tmpFilePath = (tmpDirectoryPath as NSString).appendingPathComponent(fileName)
if !fm.fileExists(atPath: tmpFilePath) {
try fm.copyItem(atPath: filePath, toPath: tmpFilePath)
print("Created file \(filePath)")
} else {
print("File \(filePath) already created")
}
}
}
try fm.contentsOfDirectory(atPath: tmpDirectoryPath).forEach { fileName in
let tmpItem = URL(fileURLWithPath: tmpDirectoryPath).appendingPathComponent(fileName)
let originalItem = URL(fileURLWithPath: destination).appendingPathComponent(fileName)
if fm.fileExists(atPath: originalItem.path) {
print("Replacing \(originalItem.path)")
try fm.replaceItemAt(originalItem, withItemAt: tmpItem)
} else {
print("Copying to \(originalItem.path)")
try fm.copyItem(at: tmpItem, to: originalItem)
}
if attributes {
try fm.setAttributes([.protectionKey: FileProtectionType.none], ofItemAtPath: originalItem.path)
}
}
}
}
| gpl-3.0 | 0f4b489f55758c284cb3461c2d203475 | 37.690265 | 104 | 0.64936 | 5.036866 | false | false | false | false |
blinksh/blink | Settings/ViewControllers/BKPubKey/KeyDetailsView.swift | 1 | 10147 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Blink is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import SwiftUI
import SSH
struct KeyDetailsView: View {
@State var card: BKPubKey
let reloadCards: () -> ()
@EnvironmentObject private var _nav: Nav
@State private var _keyName: String = ""
@State private var _certificate: String? = nil
@State private var _originalCertificate: String? = nil
@State private var _pubkeyLines = 1
@State private var _certificateLines = 1
@State private var _actionSheetIsPresented = false
@State private var _filePickerIsPresented = false
@State private var _errorMessage = ""
@State private var _publicKeyCopied = false
@State private var _certificateCopied = false
@State private var _privateKeyCopied = false
private func _copyPublicKey() {
_publicKeyCopied = false
UIPasteboard.general.string = card.publicKey
withAnimation {
_publicKeyCopied = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
withAnimation {
_publicKeyCopied = false
}
}
}
private func _copyCertificate() {
_certificateCopied = false
UIPasteboard.general.string = _certificate ?? ""
withAnimation {
_certificateCopied = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
withAnimation {
_certificateCopied = false
}
}
}
private var _saveIsDisabled: Bool {
(card.id == _keyName && _certificate == _originalCertificate) || _keyName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
private func _showError(message: String) {
_errorMessage = message
}
private func _importCertificateFromClipboard() {
do {
guard
let str = UIPasteboard.general.string,
!str.isEmpty
else {
return _showError(message: "Pasteboard is empty")
}
guard let blob = str.data(using: .utf8) else {
return _showError(message: "Can't convert to string with UTF8 encoding")
}
try _importCertificateFromBlob(blob)
} catch {
_showError(message: error.localizedDescription)
}
}
private func _importCertificateFromFile(result: Result<URL, Error>) {
do {
let url = try result.get()
guard
url.startAccessingSecurityScopedResource()
else {
throw KeyUIError.noReadAccess
}
defer {
url.stopAccessingSecurityScopedResource()
}
let blob = try Data(contentsOf: url, options: .alwaysMapped)
try _importCertificateFromBlob(blob)
} catch {
_showError(message: error.localizedDescription)
}
}
private func _importCertificateFromBlob(_ certBlob: Data) throws {
guard
let privateKey = card.loadPrivateKey(),
let privateKeyBlob = privateKey.data(using: .utf8)
else {
return _showError(message: "Can't load private key")
}
_ = try SSHKey(fromFileBlob: privateKeyBlob, passphrase: "", withPublicFileCertBlob: SSHKey.sanitize(key: certBlob))
_certificate = String(data: certBlob, encoding: .utf8)
}
private func _sharePublicKey(frame: CGRect) {
let activityController = UIActivityViewController(activityItems: [card], applicationActivities: nil);
activityController.excludedActivityTypes = [
.postToTwitter, .postToFacebook,
.assignToContact, .saveToCameraRoll,
.addToReadingList, .postToFlickr,
.postToVimeo, .postToWeibo
]
activityController.popoverPresentationController?.sourceView = _nav.navController.view
activityController.popoverPresentationController?.sourceRect = frame
_nav.navController.present(activityController, animated: true, completion: nil)
}
private func _copyPrivateKey() {
_privateKeyCopied = false
LocalAuth.shared.authenticate(callback: { success in
guard
success,
let privateKey = card.loadPrivateKey()
else {
return
}
UIPasteboard.general.string = privateKey
withAnimation {
_privateKeyCopied = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
withAnimation {
_privateKeyCopied = false
}
}
}, reason: "to copy private key to clipboard.")
}
private func _removeCertificate() {
_certificate = nil
}
private func _deleteCard() {
LocalAuth.shared.authenticate(callback: { success in
if success {
BKPubKey.removeCard(card: card)
reloadCards()
_nav.navController.popViewController(animated: true)
}
}, reason: "to delete key.")
}
private func _saveCard() {
let keyID = _keyName.trimmingCharacters(in: .whitespacesAndNewlines)
do {
if keyID.isEmpty {
throw KeyUIError.emptyName
}
if let oldKey = BKPubKey.withID(keyID) {
if oldKey !== _card.wrappedValue {
throw KeyUIError.duplicateName(name: keyID)
}
}
_card.wrappedValue.id = keyID
_card.wrappedValue.storeCertificate(inKeychain: _certificate)
BKPubKey.saveIDS()
_nav.navController.popViewController(animated: true)
self.reloadCards()
} catch {
_showError(message: error.localizedDescription)
}
}
var body: some View {
List {
Section(
header: Text("NAME"),
footer: Text("Default key must be named `id_\(card.keyType?.lowercased() ?? "")`")
) {
FixedTextField(
"Enter a name for the key",
text: $_keyName,
id: "keyName",
nextId: "keyComment",
autocorrectionType: .no,
autocapitalizationType: .none
)
}
Section(header: Text("Public Key")) {
HStack {
Text(card.publicKey).lineLimit(_pubkeyLines)
}.onTapGesture {
_pubkeyLines = _pubkeyLines == 1 ? 100 : 1
}
Button(action: _copyPublicKey, label: {
HStack {
Label("Copy", systemImage: "doc.on.doc")
Spacer()
Text("Copied").opacity(_publicKeyCopied ? 1.0 : 0.0)
}
})
GeometryReader(content: { geometry in
let frame = geometry.frame(in: .global)
Button(action: { _sharePublicKey(frame: frame) }, label: {
Label("Share", systemImage: "square.and.arrow.up")
}).frame(width: frame.width, height: frame.height, alignment: .leading)
})
}
if card.storageType == BKPubKeyStorageTypeKeyChain {
if let certificate = _certificate {
Section(header: Text("Certificate")) {
HStack {
Text(certificate).lineLimit(_certificateLines)
}.onTapGesture {
_certificateLines = _certificateLines == 1 ? 100 : 1
}
Button(action: _copyCertificate, label: {
HStack {
Label("Copy", systemImage: "doc.on.doc")
Spacer()
Text("Copied").opacity(_certificateCopied ? 1.0 : 0.0)
}
})
Button(action: _removeCertificate, label: {
Label("Remove", systemImage: "minus.circle")
}).accentColor(.red)
}
} else {
Section() {
Button(
action: { _actionSheetIsPresented = true },
label: {
Label("Add Certificate", systemImage: "plus.circle")
}
)
.actionSheet(isPresented: $_actionSheetIsPresented) {
ActionSheet(
title: Text("Add Certificate"),
buttons: [
.default(Text("Import from clipboard")) { _importCertificateFromClipboard() },
.default(Text("Import from a file")) { _filePickerIsPresented = true },
.cancel()
]
)
}
}
}
Section() {
Button(action: _copyPrivateKey, label: {
HStack {
Label("Copy private key", systemImage: "doc.on.doc")
Spacer()
Text("Copied").opacity(_privateKeyCopied ? 1.0 : 0.0)
}
})
}
}
Section() {
Button(action: _deleteCard, label: { Label("Delete", systemImage: "trash")})
.accentColor(.red)
}
}
.listStyle(GroupedListStyle())
.navigationTitle("Key Info")
.navigationBarItems(
trailing: Button("Save", action: _saveCard)
.disabled(_saveIsDisabled)
)
.fileImporter(
isPresented: $_filePickerIsPresented,
allowedContentTypes: [.text, .data, .item],
onCompletion: _importCertificateFromFile
)
.onAppear(perform: {
_keyName = card.id
_certificate = card.loadCertificate()
_originalCertificate = _certificate
})
.alert(errorMessage: $_errorMessage)
}
}
| gpl-3.0 | 312c30151a9b2826f3a2b1a495e22d58 | 29.563253 | 133 | 0.594659 | 4.748245 | false | false | false | false |
legendecas/Rocket.Chat.iOS | Rocket.Chat.Shared/Models/Subscription.swift | 1 | 4542 | //
// Subscription.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/9/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
enum SubscriptionType: String {
case directMessage = "d"
case channel = "c"
case group = "p"
case livechat = "l"
}
/// A data structure represents a subscription
public class Subscription: BaseModel {
dynamic var auth: Auth?
internal dynamic var privateType = SubscriptionType.channel.rawValue
var type: SubscriptionType {
get { return SubscriptionType(rawValue: privateType) ?? SubscriptionType.group }
set { privateType = newValue.rawValue }
}
dynamic var rid = ""
// Name of the subscription
dynamic var name = ""
// Full name of the user, in the case of
// using the full user name setting
// Setting: UI_Use_Real_Name
dynamic var fname = ""
dynamic var unread = 0
dynamic var open = false
dynamic var alert = false
dynamic var favorite = false
dynamic var createdAt: Date?
dynamic var lastSeen: Date?
dynamic var roomTopic: String?
dynamic var roomDescription: String?
dynamic var otherUserId: String?
var directMessageUser: User? {
guard let otherUserId = otherUserId else { return nil }
guard let users = try? Realm().objects(User.self).filter("identifier = '\(otherUserId)'") else { return nil }
return users.first
}
let messages = LinkingObjects(fromType: Message.self, property: "subscription")
}
extension Subscription {
func displayName() -> String {
if type != .directMessage {
return name
}
guard let settings = DependencyRepository.authSettingsManager.settings else {
return name
}
return settings.useUserRealName ? fname : name
}
func isValid() -> Bool {
return self.rid.characters.count > 0
}
func isJoined() -> Bool {
return auth != nil || type != .channel
}
func fetchRoomIdentifier(subscriptionManager: SubscriptionManager, _ completion: @escaping MessageCompletionObject <Subscription>) {
if type == .channel {
subscriptionManager.getRoom(byName: name, completion: { [weak self] (response) in
guard !response.isError() else { return }
let result = response.result["result"]
Realm.executeOnMainThread({ realm in
if let obj = self {
obj.update(result, realm: realm)
realm.add(obj, update: true)
}
})
guard let strongSelf = self else { return }
completion(strongSelf)
})
} else if type == .directMessage {
subscriptionManager.createDirectMessage(name, completion: { [weak self] (response) in
guard !response.isError() else { return }
let rid = response.result["result"]["rid"].string ?? ""
Realm.executeOnMainThread({ realm in
if let obj = self {
obj.rid = rid
realm.add(obj, update: true)
}
})
guard let strongSelf = self else { return }
completion(strongSelf)
})
}
}
func fetchMessages(_ limit: Int = 20, lastMessageDate: Date? = nil) -> [Message] {
var limitedMessages: [Message] = []
var messages = fetchMessagesQueryResults()
if let lastMessageDate = lastMessageDate {
messages = messages.filter("createdAt < %@", lastMessageDate)
}
for i in 0..<min(limit, messages.count) {
limitedMessages.append(messages[i])
}
return limitedMessages
}
func fetchMessagesQueryResults() -> Results<Message> {
let filter = NSPredicate(format: "userBlocked == false")
return self.messages.filter(filter).sorted(byKeyPath: "createdAt", ascending: false)
}
func updateFavorite(_ favorite: Bool) {
Realm.executeOnMainThread({ _ in
self.favorite = favorite
})
}
}
extension Subscription {
static func find(rid: String, realm: Realm) -> Subscription? {
var object: Subscription?
if let findObject = realm.objects(Subscription.self).filter("rid == '\(rid)'").first {
object = findObject
}
return object
}
}
| mit | c3bc42818c287c0f09a31ceabd700d36 | 27.923567 | 136 | 0.590178 | 4.93051 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/GSR-Booking/Views/GSRGroups/CreateGroupCell.swift | 1 | 1073 | //
// CreateGroupCell.swift
// PennMobile
//
// Created by Josh Doman on 4/6/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
class CreateGroupCell: UITableViewCell {
static let cellHeight: CGFloat = 60
static let identifier = "createGroupCell"
fileprivate var titleLabel: UILabel!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel = UILabel()
titleLabel.text = "Add Group"
titleLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
titleLabel.textColor = UIColor(named: "baseLabsBlue")
addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 1ba9d5fafa87d1b7271d1d332d3d24ee | 31.484848 | 83 | 0.708022 | 4.850679 | false | false | false | false |
huonw/swift | test/Driver/Dependencies/bindings-build-record.swift | 36 | 4068 | // RUN: rm -rf %t && cp -r %S/Inputs/bindings-build-record/ %t
// RUN: %S/Inputs/touch.py 443865900 %t/*
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=MUST-EXEC
// MUST-EXEC-NOT: warning
// MUST-EXEC: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: run-without-cascading
// MUST-EXEC: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading
// MUST-EXEC: inputs: ["./yet-another.swift"], output: {{[{].*[}]}}, condition: run-without-cascading
// RUN: echo '{version: "'$(%swiftc_driver_plain -version | head -n1)'", inputs: {"./main.swift": [443865900, 0], "./other.swift": [443865900, 0], "./yet-another.swift": [443865900, 0]}, build_time: [443865901, 0]}' > %t/main~buildrecord.swiftdeps
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=NO-EXEC
// NO-EXEC: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: check-dependencies
// NO-EXEC: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: check-dependencies
// NO-EXEC: inputs: ["./yet-another.swift"], output: {{[{].*[}]}}, condition: check-dependencies
// RUN: echo '{version: "'$(%swiftc_driver_plain -version | head -n1)'", inputs: {"./main.swift": [443865900, 0], "./other.swift": !private [443865900, 0], "./yet-another.swift": !dirty [443865900, 0]}, build_time: [443865901, 0]}' > %t/main~buildrecord.swiftdeps
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=BUILD-RECORD
// BUILD-RECORD: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: check-dependencies{{$}}
// BUILD-RECORD: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading{{$}}
// BUILD-RECORD: inputs: ["./yet-another.swift"], output: {{[{].*[}]$}}
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift ./added.swift -incremental -output-file-map %t/output.json 2>&1 > %t/added.txt
// RUN: %FileCheck %s -check-prefix=BUILD-RECORD < %t/added.txt
// RUN: %FileCheck %s -check-prefix=FILE-ADDED < %t/added.txt
// FILE-ADDED: inputs: ["./added.swift"], output: {{[{].*[}]}}, condition: newly-added{{$}}
// RUN: %S/Inputs/touch.py 443865960 %t/main.swift
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=BUILD-RECORD-PLUS-CHANGE
// BUILD-RECORD-PLUS-CHANGE: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: run-without-cascading
// BUILD-RECORD-PLUS-CHANGE: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading{{$}}
// BUILD-RECORD-PLUS-CHANGE: inputs: ["./yet-another.swift"], output: {{[{].*[}]$}}
// RUN: %S/Inputs/touch.py 443865900 %t/*
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=FILE-REMOVED
// FILE-REMOVED: inputs: ["./main.swift"], output: {{[{].*[}]$}}
// FILE-REMOVED: inputs: ["./other.swift"], output: {{[{].*[}]$}}
// FILE-REMOVED-NOT: yet-another.swift
// RUN: echo '{version: "bogus", inputs: {"./main.swift": [443865900, 0], "./other.swift": !private [443865900, 0], "./yet-another.swift": !dirty [443865900, 0]}}' > %t/main~buildrecord.swiftdeps
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=INVALID-RECORD
// INVALID-RECORD-NOT: warning
// INVALID-RECORD: inputs: ["./main.swift"], output: {{[{].*[}]$}}
// INVALID-RECORD: inputs: ["./other.swift"], output: {{[{].*[}]$}}
// INVALID-RECORD: inputs: ["./yet-another.swift"], output: {{[{].*[}]$}}
| apache-2.0 | f44d0f67c3e7b8c251c9103dcacaf251 | 78.764706 | 263 | 0.641101 | 3.421362 | false | false | false | false |
17thDimension/AudioKit | Tests/Tests/AKVibes.swift | 2 | 1193 | //
// main.swift
// AudioKit
//
// Created by Aurelius Prochazka on 11/30/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
class Instrument : AKInstrument {
override init() {
super.init()
let note = Note()
let vibes = AKVibes()
vibes.frequency = note.frequency
setAudioOutput(vibes)
}
}
class Note: AKNote {
var frequency = AKNoteProperty(value: 220, minimum: 110, maximum: 880)
override init() {
super.init()
addProperty(frequency)
}
convenience init(frequency startingFrequency: Float) {
self.init()
frequency.value = startingFrequency
}
}
AKOrchestra.testForDuration(4)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
let note1 = Note(frequency: 440)
let note2 = Note(frequency: 550)
let note3 = Note(frequency: 660)
let phrase = AKPhrase()
phrase.addNote(note1, atTime:0.5)
phrase.addNote(note2, atTime:1.0)
phrase.addNote(note3, atTime:1.5)
phrase.addNote(note2, atTime:2.0)
instrument.playPhrase(phrase)
let manager = AKManager.sharedManager()
while(manager.isRunning) {} //do nothing
println("Test complete!")
| lgpl-3.0 | 8e94d6d9da6d13b545779011a231194e | 20.303571 | 74 | 0.682313 | 3.659509 | false | false | false | false |
crossroadlabs/ExpressCommandLine | swift-express/Commands/Bootstrap.swift | 1 | 5049 | //===--- Bootstrap.swift -------------------------------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express Command Line is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===---------------------------------------------------------------------------===//
import Result
import Commandant
import Foundation
// Install carthage dependencies.
//Input:
// workingFolder
//Output:
// None
struct CheckoutSPM : RunSubtaskStep {
let dependsOn = [Step]()
let force: Bool
init(force: Bool = true) {
self.force = force
}
func run(params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] {
guard let workingFolder = params["workingFolder"] as? String else {
throw SwiftExpressError.BadOptions(message: "CheckoutSPM: No workingFolder option.")
}
let pkgFolder = workingFolder.addPathComponent("Packages")
if !force && FileManager.isDirectoryExists(pkgFolder) {
return [String:Any]()
}
let result = try executeSubtaskAndWait(SubTask(task: "/usr/bin/env", arguments: ["swift", "build", "--fetch"], workingDirectory: workingFolder, environment: nil, useAppOutput: true))
if result != 0 {
throw SwiftExpressError.SubtaskError(message: "CheckoutSPM: package fetch failed. Exit code \(result)")
}
for pkg in try FileManager.listDirectory(pkgFolder) {
let testsDir = pkgFolder.addPathComponent(pkg).addPathComponent("Tests")
if FileManager.isDirectoryExists(testsDir) {
try FileManager.removeItem(testsDir)
}
}
return [String:Any]()
}
func cleanup(params:[String: Any], output: StepResponse) throws {
}
func revert(params: [String : Any], output: [String : Any]?, error: SwiftExpressError?) {
if let workingFolder = params["workingFolder"] {
do {
let pkgFolder = (workingFolder as! String).addPathComponent("Packages")
if FileManager.isDirectoryExists(pkgFolder) {
try FileManager.removeItem(pkgFolder)
}
} catch {
print("Can't revert CheckoutSPM: \(error)")
}
}
}
}
struct BootstrapCommand : StepCommand {
typealias Options = BootstrapCommandOptions
let verb = "bootstrap"
let function = "download and build Express project dependencies"
func step(opts: Options) -> Step {
if opts.spm || !opts.carthage || IS_LINUX {
return CheckoutSPM(force: true)
}
if opts.noRefetch {
return CarthageInstallLibs(updateCommand: "build", force: true)
}
return CarthageInstallLibs(updateCommand: "bootstrap", force: true, fetchOnly: opts.fetch)
}
func getOptions(opts: Options) -> Result<[String:Any], SwiftExpressError> {
return Result(["workingFolder": opts.path.standardizedPath()])
}
}
struct BootstrapCommandOptions : OptionsType {
let path: String
let spm: Bool
let carthage: Bool
let fetch: Bool
let noRefetch: Bool
static func create(path: String) -> (Bool -> (Bool -> (Bool -> (Bool -> BootstrapCommandOptions)))) {
return { (spm: Bool) in
{ (carthage: Bool) in
{ (fetch: Bool) in
{ (noRefetch: Bool) in
BootstrapCommandOptions(path: path, spm: spm, carthage: carthage, fetch: fetch, noRefetch: noRefetch)
}
}
}
}
}
static func evaluate(m: CommandMode) -> Result<BootstrapCommandOptions, CommandantError<SwiftExpressError>> {
return create
<*> m <| Option(key: "path", defaultValue: ".", usage: "project directory")
<*> m <| Option(key: "spm", defaultValue: DEFAULTS_USE_SPM, usage: "use SPM as package manager")
<*> m <| Option(key: "carthage", defaultValue: DEFAULTS_USE_CARTHAGE, usage: "use Carthage as package manager")
<*> m <| Option(key: "fetch", defaultValue: false, usage: "only fetch. Always true for SPM (ignored if --no-fetch presents)")
<*> m <| Option(key: "no-refetch", defaultValue: false, usage: "build without fetch. Always false for SPM.")
}
} | gpl-3.0 | fcd9c57184705fcbfd24e0f5c766f57e | 38.147287 | 190 | 0.606061 | 4.776727 | false | false | false | false |
mattiasjahnke/arduino-projects | matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/Scheduler.swift | 1 | 7850 | //
// Scheduler.swift
// Flow
//
// Created by Måns Bernhardt on 2015-09-30.
// Copyright © 2015 iZettle. All rights reserved.
//
import Foundation
/// Encapsulates how to asynchronously and synchronously scheduler work and allows comparing if two instances are representing the same scheduler.
public final class Scheduler {
private let identifyingObject: AnyObject
private let _async: (@escaping () -> Void) -> Void
private let _sync: (() -> Void) -> Void
/// Creates an instance that will use `async` for asynchrouns scheduling and `sync` for synchrouns scheduling.
/// - Parameter identifyingObject: Used to identify if two scheduler are the same using `===`.
public init(identifyingObject: AnyObject, async: @escaping (@escaping () -> Void) -> Void, sync: @escaping (() -> Void) -> Void) {
self.identifyingObject = identifyingObject
_async = async
_sync = sync
}
}
public extension Scheduler {
/// Asynchronously schedules `work` unless we are already currently scheduling work on `self`, where the `work` be immediately called.
func async(execute work: @escaping () -> Void) {
guard !isImmediate else {
return work()
}
_async {
let state = threadState
assert(state.scheduler == nil)
state.scheduler = self
work()
state.scheduler = nil
}
}
/// Synchronously schedules `work` unless we are already currently scheduling work on `self`, where the `work` be immediately called.
func sync<T>(execute work: () -> T) -> T {
guard !isImmediate else {
return work()
}
let state = threadState
state.syncScheduler = self
var result: T!
_sync {
result = work()
}
state.syncScheduler = nil
return result
}
/// Returns true if `async()` and `sync()` will execute work immediately and hence not be scheduled.
var isImmediate: Bool {
if (self == .main && Thread.isMainThread) || self == .none { return true }
let state = threadState
return self == state.scheduler || self == state.syncScheduler
}
/// Returns true if `self` is currently execute work
var isExecuting: Bool {
let state = threadState
return self == state.scheduler || (Thread.isMainThread && self == .main) || self == state.syncScheduler
}
/// Synchronously schedules `work` unless we are already currently scheduling work on `self`, where the `work` be immediately called.
/// - Throws: If `work` throws.
func sync<T>(execute work: () throws -> T) throws -> T {
return try sync {
Result { try work() }
}.getValue()
}
/// Will asynchronously schedule `work` on `self` after `delay` seconds
func async(after delay: TimeInterval, execute work: @escaping () -> ()) {
return DispatchQueue.concurrentBackground.asyncAfter(deadline: DispatchTime.now() + delay) {
self.async(execute: work)
}
}
}
public extension Scheduler {
/// The scheduler we are currently being scheduled on.
/// If we are currently not being scheduled, `.main` will be returned if we are on the main thread or `.background` if not.
static var current: Scheduler {
let state = threadState
return state.syncScheduler ?? state.scheduler ?? (Thread.isMainThread ? .main : .background)
}
/// A Scheduler that won't schedule any work and hence just call work() immediatly
static let none = Scheduler(identifyingObject: 0 as AnyObject, async: { _ in fatalError() }, sync: { _ in fatalError() })
/// A Scheduler that will schedule work on `DispatchQueue.main``
static let main = Scheduler(queue: .main)
/// A Scheduler that will schedule work on a serial background queue
static let background = Scheduler(label: "flow.background.serial")
/// A Scheduler that will schedule work on a concurrent background queue
static let concurrentBackground = Scheduler(label: "flow.background.concurrent", attributes: .concurrent)
}
public extension Scheduler {
/// Create a new instance that will schedule its work on the provided `queue`
convenience init(queue: DispatchQueue) {
self.init(identifyingObject: queue, async: { queue.async(execute: $0) }, sync: queue.sync)
}
/// Create a new instance that will schedule its work on a `DispatchQueue` created with the the provided `label` and `attributes`.
public convenience init(label: String, attributes: DispatchQueue.Attributes = []) {
self.init(queue: DispatchQueue(label: label, attributes: attributes))
}
}
extension Scheduler: Equatable {
public static func ==(lhs: Scheduler, rhs: Scheduler) -> Bool {
return lhs.identifyingObject === rhs.identifyingObject
}
}
// Below breaks fastlane builds
//#if canImport(CoreData)
//import CoreData
//
//pubic extension NSManagedObjectContext {
// var scheduler: Scheduler {
// return concurrencyType == .mainQueueConcurrencyType ? .main : Scheduler(identifyingObject: self, async: perform, sync: performAndWait)
// }
//}
//#endif
/// Used for scheduling delays and might be overridend in unit test with simulatated delays
func disposableAsync(after delay: TimeInterval, execute work: @escaping () -> ()) -> Disposable {
return _disposableAsync(delay, work)
}
private var _disposableAsync: (_ delay: TimeInterval, _ work: @escaping () -> ()) -> Disposable = Scheduler.concurrentBackground.disposableAsync
/// Useful for overriding `disposableAsync` in unit test with simulatated delays
func overrideDisposableAsync(by disposableAsync: @escaping (_ delay: TimeInterval, _ work: @escaping () -> ()) -> Disposable) -> Disposable {
let prev = _disposableAsync
_disposableAsync = disposableAsync
return Disposer {
_disposableAsync = prev
}
}
extension Scheduler {
/// Will asynchronously schedule `work` on `self` after `delay` seconds
/// - Returns: A disposable for cancelation
/// - Note: There is no guarantee that `work` will not be called after disposing the returned `Disposable`
func disposableAsync(after delay: TimeInterval, execute work: @escaping () -> ()) -> Disposable {
precondition(delay >= 0)
let s = StateAndCallback(state: Optional(work))
async(after: delay) { [weak s] in
guard let s = s else { return }
s.lock()
let work = s.val
s.val = nil
s.unlock()
// We can not hold a lock while calling out (risk of deadlock if callout calls dispose), hence dispose might be called just after releasing a lock but before calling out. This means there is guarantee `work` would be called after a dispose.
work?()
}
return Disposer { s.protectedVal = nil }
}
}
extension DispatchQueue {
static let concurrentBackground = DispatchQueue(label: "flow.background.concurrent", attributes: .concurrent)
static let serialBackground = DispatchQueue(label: "flow.background.serial")
}
final class ThreadState {
var scheduler: Scheduler?
var syncScheduler: Scheduler?
init() {}
}
var threadState: ThreadState {
guard !Thread.isMainThread else { return mainThreadState }
if let p = pthread_getspecific(threadStateKey) {
return Unmanaged<ThreadState>.fromOpaque(p).takeUnretainedValue()
}
let s = ThreadState()
pthread_setspecific(threadStateKey, Unmanaged.passRetained(s).toOpaque())
return s
}
private let mainThreadState = ThreadState()
private var _threadStateKey: pthread_key_t = 0
private var threadStateKey: pthread_key_t = {
pthread_key_create(&_threadStateKey, nil)
return _threadStateKey
}()
| mit | 055260b71022b12509b6588c6f6cb55f | 37.097087 | 252 | 0.662589 | 4.635558 | false | false | false | false |
afarber/ios-newbie | Tops1/Tops1/Persistence.swift | 1 | 1478 | //
// Persistence.swift
// Tops1
//
// Created by Alexander Farber on 03.06.21.
//
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
for var i in 0..<10 {
let newTop = TopEntity(context: viewContext)
newTop.uid = Int32(101 + i)
newTop.elo = Int32(2500 - i * 100)
newTop.given = "Person #\(newTop.uid)"
}
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "Tops1")
container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
container.viewContext.automaticallyMergesChangesFromParent = true
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
}
| unlicense | ba3153588d95b757835dee4839690124 | 31.130435 | 96 | 0.61502 | 4.959732 | false | false | false | false |
xocialize/Kiosk | kiosk/AppDelegate.swift | 1 | 6558 | //
// AppDelegate.swift
// kiosk
//
// Created by Dustin Nielson on 4/13/15.
// Copyright (c) 2015 Dustin Nielson. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var server: HttpServer?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let server = KioskServer(NSBundle.mainBundle().resourcePath)
self.server = server
var error: NSError?
if !server.start(error: &error) {
println("Server start error: \(error)")
}
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.xocialize.kiosk" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("kiosk", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("kiosk.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | bcbcd815af967086f0032d9b96e261ad | 49.061069 | 290 | 0.699146 | 5.737533 | false | false | false | false |
quire-io/SwiftyChrono | Sources/Result.swift | 1 | 7265 | //
// Result.swift
// SwiftyChrono
//
// Created by Jerry Chen on 1/17/17.
// Copyright © 2017 Potix. All rights reserved.
//
import Foundation
public struct ParsedResult {
public let ref: Date
public var index: Int
public var text: String
public var tags: [TagUnit: Bool]
public var start: ParsedComponents
public var end: ParsedComponents?
// used for parsing logic controll
public let isMoveIndexMode: Bool
public init(ref: Date, index: Int, text: String, tags: [TagUnit: Bool] = [TagUnit: Bool](), start: [ComponentUnit: Int]? = nil, end: [ComponentUnit: Int]? = nil, isMoveIndexMode: Bool = false) {
self.ref = ref
self.index = index
self.text = text
self.tags = tags
self.start = ParsedComponents(components: start, ref: ref)
if let end = end {
self.end = ParsedComponents(components: end, ref: ref)
}
self.isMoveIndexMode = isMoveIndexMode
}
static func moveIndexMode(index: Int) -> ParsedResult {
return self.init(ref: Date(), index: index, text: "", isMoveIndexMode: true)
}
func clone() -> ParsedResult {
var result = ParsedResult(ref: ref, index: index, text: text, tags: tags)
result.start = start
result.end = end
return result
}
func hasPossibleDates() -> Bool {
return start.isPossibleDate() && (end == nil || end!.isPossibleDate())
}
}
public struct ParsedComponents {
public var knownValues = [ComponentUnit: Int]()
public var impliedValues = [ComponentUnit: Int]()
init(components: [ComponentUnit: Int]?, ref: Date?) {
if let components = components {
knownValues = components
}
if let ref = ref {
imply(.day, to: ref.day)
imply(.month, to: ref.month)
imply(.year, to: ref.year)
}
imply(.hour, to: Chrono.defaultImpliedHour)
imply(.minute, to: Chrono.defaultImpliedMinute)
imply(.second, to: Chrono.defaultImpliedSecond)
imply(.millisecond, to: Chrono.defaultImpliedMillisecond)
}
private init(parsedComponents: ParsedComponents) {
knownValues = parsedComponents.knownValues
impliedValues = parsedComponents.impliedValues
}
public func clone() -> ParsedComponents {
return ParsedComponents(parsedComponents: self)
}
public subscript(component: ComponentUnit) -> Int? {
if knownValues.keys.contains(component) { return knownValues[component]! }
if impliedValues.keys.contains(component) { return impliedValues[component]! }
return nil
}
public mutating func assign(_ component: ComponentUnit, value: Int?) {
if let value = value {
knownValues[component] = value
impliedValues.removeValue(forKey: component)
}
}
public mutating func imply(_ component: ComponentUnit, to value: Int?) {
guard let value = value else {
return
}
if knownValues.keys.contains(component) { return }
impliedValues[component] = value
}
public func isCertain(component: ComponentUnit) -> Bool {
return knownValues.keys.contains(component)
}
public func isPossibleDate() -> Bool {
var date = moment
var isUTC = false
if isCertain(component: .timeZoneOffset) {
// iOS only: in moment.js lib, set utcOffset will turn on isUTC, so the getter will count on utc based time zone
isUTC = true
date.utcOffset = self[.timeZoneOffset]!
}
if (isUTC ? date.utcYear : date.year) != self[.year] { return false }
if (isUTC ? date.utcMonth : date.month) != self[.month] { return false }
if (isUTC ? date.utcDay : date.day) != self[.day] { return false }
if (isUTC ? date.utcHour : date.hour) != self[.hour] { return false }
if (isUTC ? date.utcMinute : date.minute) != self[.minute] { return false }
return true
}
public var date: Date {
return moment
}
public var moment: Date {
var comps = DateComponents()
if let year = self[.year] {
comps.year = year
}
if let month = self[.month] {
comps.month = month
}
if let day = self[.day] {
comps.day = day
}
if let hour = self[.hour] {
comps.hour = hour
}
if let minute = self[.minute] {
comps.minute = minute
}
if let second = self[.second] {
comps.second = second
}
if let millisecond = self[.millisecond] {
comps.nanosecond = millisecondsToNanoSeconds(millisecond)
}
let date = cal.date(from: comps)!
let currenttimeZoneOffset = date.utcOffset
let targettimeZoneOffset =
isCertain(component: .timeZoneOffset) ? self[.timeZoneOffset]! : currenttimeZoneOffset
let adjustedtimeZoneOffset = targettimeZoneOffset - currenttimeZoneOffset
let newDate = date.added(-adjustedtimeZoneOffset, .minute)
if Chrono.sixMinutesFixBefore1900 && newDate.utcYear < 1900 {
return newDate.added(6, .minute)
}
return newDate
}
}
public enum ComponentUnit {
case year, month, day, hour, minute, second, millisecond, weekday, timeZoneOffset, meridiem
}
public enum TagUnit { case
none,
enCasualTimeParser,
enCasualDateParser,
enDeadlineFormatParser,
enISOFormatParser,
enMonthNameLittleEndianParser,
enMonthNameMiddleEndianParser,
enMonthNameParser,
enRelativeDateFormatParser,
enSlashDateFormatParser,
enSlashDateFormatStartWithYearParser,
enSlashMonthFormatParser,
enTimeAgoFormatParser,
enTimeExpressionParser,
enWeekdayParser,
esCasualDateParser,
esDeadlineFormatParser,
esMonthNameLittleEndianParser,
esSlashDateFormatParser,
esTimeAgoFormatParser,
esTimeExpressionParser,
esWeekdayParser,
frCasualDateParser,
frDeadlineFormatParser,
frMonthNameLittleEndianParser,
frSlashDateFormatParser,
frTimeAgoFormatParser,
frTimeExpressionParser,
frWeekdayParser,
jpCasualDateParser,
jpStandardParser,
deCasualTimeParser,
deCasualDateParser,
deDeadlineFormatParser,
deMonthNameLittleEndianParser,
deSlashDateFormatParser,
deTimeAgoFormatParser,
deTimeExpressionParser,
deWeekdayParser,
deMorgenTimeParser,
zhHantCasualDateParser,
zhHantDateParser,
zhHantDeadlineFormatParser,
zhHantTimeExpressionParser,
zhHantWeekdayParser,
extractTimezoneAbbrRefiner,
extractTimezoneOffsetRefiner,
forwardDateRefiner,
enMergeDateAndTimeRefiner,
enMergeDateRangeRefiner,
enPrioritizeSpecificDateRefiner,
frMergeDateRangeRefiner,
frMergeDateAndTimeRefiner,
deMergeDateAndTimeRefiner,
deMergeDateRangeRefiner
}
| mit | a9bc078528eb5bea894c9f83136aa7b9 | 27.155039 | 198 | 0.62266 | 4.782093 | false | false | false | false |
ZakariyyaSv/LYNetwork | LYNetwork/Source/LYNetworkMD5.swift | 1 | 8959 | //
// LYNetworkMD5.swift
// LYNetwork
//
// Created by zakariyyasv on 2017/8/7.
// Copyright © 2017年 yangqianguan.com. All rights reserved.
//
import Foundation
// MARK: - Public
public func MD5(_ input: String) -> String {
return hex_md5(input)
}
// MARK: - Functions
func hex_md5(_ input: String) -> String {
return rstr2hex(rstr_md5(str2rstr_utf8(input)))
}
func str2rstr_utf8(_ input: String) -> [CUnsignedChar] {
return Array(input.utf8)
}
func rstr2tr(_ input: [CUnsignedChar]) -> String {
var output: String = ""
input.forEach {
output.append(String(UnicodeScalar($0)))
}
return output
}
/*
* Convert a raw string to a hex string
*/
func rstr2hex(_ input: [CUnsignedChar]) -> String {
let hexTab: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
var output: [Character] = []
for i in 0..<input.count {
let x = input[i]
let value1 = hexTab[Int((x >> 4) & 0x0F)]
let value2 = hexTab[Int(Int32(x) & 0x0F)]
output.append(value1)
output.append(value2)
}
return String(output)
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
func rstr2binl(_ input: [CUnsignedChar]) -> [Int32] {
var output: [Int: Int32] = [:]
for i in stride(from: 0, to: input.count * 8, by: 8) {
let value: Int32 = (Int32(input[i/8]) & 0xFF) << (Int32(i) % 32)
output[i >> 5] = unwrap(output[i >> 5]) | value
}
return dictionary2array(output)
}
/*
* Convert an array of little-endian words to a string
*/
func binl2rstr(_ input: [Int32]) -> [CUnsignedChar] {
var output: [CUnsignedChar] = []
for i in stride(from: 0, to: input.count * 32, by: 8) {
// [i>>5] >>>
let value: Int32 = zeroFillRightShift(input[i>>5], Int32(i % 32)) & 0xFF
output.append(CUnsignedChar(value))
}
return output
}
/*
* Calculate the MD5 of a raw string
*/
func rstr_md5(_ input: [CUnsignedChar]) -> [CUnsignedChar] {
return binl2rstr(binl_md5(rstr2binl(input), input.count * 8))
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
func safe_add(_ x: Int32, _ y: Int32) -> Int32 {
let lsw = (x & 0xFFFF) + (y & 0xFFFF)
let msw = (x >> 16) + (y >> 16) + (lsw >> 16)
return (msw << 16) | (lsw & 0xFFFF)
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
func bit_rol(_ num: Int32, _ cnt: Int32) -> Int32 {
// num >>>
return (num << cnt) | zeroFillRightShift(num, (32 - cnt))
}
/*
* These funcs implement the four basic operations the algorithm uses.
*/
func md5_cmn(_ q: Int32, _ a: Int32, _ b: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
}
func md5_ff(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
}
func md5_gg(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
}
func md5_hh(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return md5_cmn(b ^ c ^ d, a, b, x, s, t)
}
func md5_ii(_ a: Int32, _ b: Int32, _ c: Int32, _ d: Int32, _ x: Int32, _ s: Int32, _ t: Int32) -> Int32 {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
func binl_md5(_ input: [Int32], _ len: Int) -> [Int32] {
/* append padding */
var x: [Int: Int32] = [:]
for (index, value) in input.enumerated() {
x[index] = value
}
let value: Int32 = 0x80 << Int32((len) % 32)
x[len >> 5] = unwrap(x[len >> 5]) | value
// >>> 9
let index = (((len + 64) >> 9) << 4) + 14
x[index] = unwrap(x[index]) | Int32(len)
var a: Int32 = 1732584193
var b: Int32 = -271733879
var c: Int32 = -1732584194
var d: Int32 = 271733878
for i in stride(from: 0, to: length(x), by: 16) {
let olda: Int32 = a
let oldb: Int32 = b
let oldc: Int32 = c
let oldd: Int32 = d
a = md5_ff(a, b, c, d, unwrap(x[i + 0]), 7 , -680876936)
d = md5_ff(d, a, b, c, unwrap(x[i + 1]), 12, -389564586)
c = md5_ff(c, d, a, b, unwrap(x[i + 2]), 17, 606105819)
b = md5_ff(b, c, d, a, unwrap(x[i + 3]), 22, -1044525330)
a = md5_ff(a, b, c, d, unwrap(x[i + 4]), 7 , -176418897)
d = md5_ff(d, a, b, c, unwrap(x[i + 5]), 12, 1200080426)
c = md5_ff(c, d, a, b, unwrap(x[i + 6]), 17, -1473231341)
b = md5_ff(b, c, d, a, unwrap(x[i + 7]), 22, -45705983)
a = md5_ff(a, b, c, d, unwrap(x[i + 8]), 7 , 1770035416)
d = md5_ff(d, a, b, c, unwrap(x[i + 9]), 12, -1958414417)
c = md5_ff(c, d, a, b, unwrap(x[i + 10]), 17, -42063)
b = md5_ff(b, c, d, a, unwrap(x[i + 11]), 22, -1990404162)
a = md5_ff(a, b, c, d, unwrap(x[i + 12]), 7 , 1804603682)
d = md5_ff(d, a, b, c, unwrap(x[i + 13]), 12, -40341101)
c = md5_ff(c, d, a, b, unwrap(x[i + 14]), 17, -1502002290)
b = md5_ff(b, c, d, a, unwrap(x[i + 15]), 22, 1236535329)
a = md5_gg(a, b, c, d, unwrap(x[i + 1]), 5 , -165796510)
d = md5_gg(d, a, b, c, unwrap(x[i + 6]), 9 , -1069501632)
c = md5_gg(c, d, a, b, unwrap(x[i + 11]), 14, 643717713)
b = md5_gg(b, c, d, a, unwrap(x[i + 0]), 20, -373897302)
a = md5_gg(a, b, c, d, unwrap(x[i + 5]), 5 , -701558691)
d = md5_gg(d, a, b, c, unwrap(x[i + 10]), 9 , 38016083)
c = md5_gg(c, d, a, b, unwrap(x[i + 15]), 14, -660478335)
b = md5_gg(b, c, d, a, unwrap(x[i + 4]), 20, -405537848)
a = md5_gg(a, b, c, d, unwrap(x[i + 9]), 5 , 568446438)
d = md5_gg(d, a, b, c, unwrap(x[i + 14]), 9 , -1019803690)
c = md5_gg(c, d, a, b, unwrap(x[i + 3]), 14, -187363961)
b = md5_gg(b, c, d, a, unwrap(x[i + 8]), 20, 1163531501)
a = md5_gg(a, b, c, d, unwrap(x[i + 13]), 5 , -1444681467)
d = md5_gg(d, a, b, c, unwrap(x[i + 2]), 9 , -51403784)
c = md5_gg(c, d, a, b, unwrap(x[i + 7]), 14, 1735328473)
b = md5_gg(b, c, d, a, unwrap(x[i + 12]), 20, -1926607734)
a = md5_hh(a, b, c, d, unwrap(x[i + 5]), 4 , -378558)
d = md5_hh(d, a, b, c, unwrap(x[i + 8]), 11, -2022574463)
c = md5_hh(c, d, a, b, unwrap(x[i + 11]), 16, 1839030562)
b = md5_hh(b, c, d, a, unwrap(x[i + 14]), 23, -35309556)
a = md5_hh(a, b, c, d, unwrap(x[i + 1]), 4 , -1530992060)
d = md5_hh(d, a, b, c, unwrap(x[i + 4]), 11, 1272893353)
c = md5_hh(c, d, a, b, unwrap(x[i + 7]), 16, -155497632)
b = md5_hh(b, c, d, a, unwrap(x[i + 10]), 23, -1094730640)
a = md5_hh(a, b, c, d, unwrap(x[i + 13]), 4 , 681279174)
d = md5_hh(d, a, b, c, unwrap(x[i + 0]), 11, -358537222)
c = md5_hh(c, d, a, b, unwrap(x[i + 3]), 16, -722521979)
b = md5_hh(b, c, d, a, unwrap(x[i + 6]), 23, 76029189)
a = md5_hh(a, b, c, d, unwrap(x[i + 9]), 4 , -640364487)
d = md5_hh(d, a, b, c, unwrap(x[i + 12]), 11, -421815835)
c = md5_hh(c, d, a, b, unwrap(x[i + 15]), 16, 530742520)
b = md5_hh(b, c, d, a, unwrap(x[i + 2]), 23, -995338651)
a = md5_ii(a, b, c, d, unwrap(x[i + 0]), 6 , -198630844)
d = md5_ii(d, a, b, c, unwrap(x[i + 7]), 10, 1126891415)
c = md5_ii(c, d, a, b, unwrap(x[i + 14]), 15, -1416354905)
b = md5_ii(b, c, d, a, unwrap(x[i + 5]), 21, -57434055)
a = md5_ii(a, b, c, d, unwrap(x[i + 12]), 6 , 1700485571)
d = md5_ii(d, a, b, c, unwrap(x[i + 3]), 10, -1894986606)
c = md5_ii(c, d, a, b, unwrap(x[i + 10]), 15, -1051523)
b = md5_ii(b, c, d, a, unwrap(x[i + 1]), 21, -2054922799)
a = md5_ii(a, b, c, d, unwrap(x[i + 8]), 6 , 1873313359)
d = md5_ii(d, a, b, c, unwrap(x[i + 15]), 10, -30611744)
c = md5_ii(c, d, a, b, unwrap(x[i + 6]), 15, -1560198380)
b = md5_ii(b, c, d, a, unwrap(x[i + 13]), 21, 1309151649)
a = md5_ii(a, b, c, d, unwrap(x[i + 4]), 6 , -145523070)
d = md5_ii(d, a, b, c, unwrap(x[i + 11]), 10, -1120210379)
c = md5_ii(c, d, a, b, unwrap(x[i + 2]), 15, 718787259)
b = md5_ii(b, c, d, a, unwrap(x[i + 9]), 21, -343485551)
a = safe_add(a, olda)
b = safe_add(b, oldb)
c = safe_add(c, oldc)
d = safe_add(d, oldd)
}
return [a, b, c, d]
}
// MARK: - Helper
func length(_ dictionary: [Int: Int32]) -> Int {
return (dictionary.keys.max() ?? 0) + 1
}
func dictionary2array(_ dictionary: [Int: Int32]) -> [Int32] {
var array = Array<Int32>(repeating: 0, count: dictionary.keys.count)
for i in Array(dictionary.keys).sorted() {
array[i] = unwrap(dictionary[i])
}
return array
}
func unwrap(_ value: Int32?, _ fallback: Int32 = 0) -> Int32 {
if let value = value {
return value
}
return fallback
}
func zeroFillRightShift(_ num: Int32, _ count: Int32) -> Int32 {
let value = UInt32(bitPattern: num) >> UInt32(bitPattern: count)
return Int32(bitPattern: value)
}
| mit | 4f8cb58d83f4204f8c9b2822554e706f | 32.543071 | 108 | 0.541201 | 2.326838 | false | false | false | false |
meninsilicium/apple-swifty | JSONPath.swift | 1 | 10382 | //
// author: fabrice truillot de chambrier
// created: 29.01.2015
//
// license: see license.txt
//
// © 2015-2015, men in silicium sàrl
//
// MARK: JSONPath
public struct JSONPath {
private var components: [JSONPathComponent]
}
// MARK: JSONPathComponent
public enum JSONPathComponent {
case Key( String )
case Index( Int )
}
// MARK: conforming types
public protocol JSONPathComponentType {}
extension String : JSONPathComponentType {}
extension Int : JSONPathComponentType {}
// MARK: -
// MARK: implementation
// MARK: JSONPath init
extension JSONPath {
public init() {
self.components = []
}
// init with 1 component
public init( _ any: JSONPathComponentType ) {
switch any {
case let key as String:
self.init( JSONPathComponent( key: key ) )
case let index as Int:
self.init( JSONPathComponent( index: index ) )
default:
self.init()
println( "JSONPath.init didn't match \( any )" )
}
}
// init with 1+ component
public init( _ component: JSONPathComponentType, _ components: JSONPathComponentType... ) {
// assembling an array
var array = [JSONPathComponentType]()
array.append( component )
array.extend( components )
self.init( array )
}
public init( _ components: [JSONPathComponentType] ) {
var array = [JSONPathComponent]()
for component in components {
switch component {
case let key as String:
array.append( JSONPathComponent( key: key ) )
case let index as Int:
array.append( JSONPathComponent( index: index ) )
default:
println( "JSONPath.init didn't match \(component)" )
break
}
}
self.components = array
}
public init( _ key: String ) {
self.components = [ JSONPathComponent( key: key ) ]
}
public init( _ index: Int ) {
self.components = [ JSONPathComponent( index: index ) ]
}
private init( _ component: JSONPathComponent ) {
self.components = [ component ]
}
private init( _ components: [JSONPathComponent] ) {
self.components = components
}
}
// MARK: JSONPath init with literals
// Array
extension JSONPath : ArrayLiteralConvertible {
public typealias Element = JSONPathComponentType
public init( arrayLiteral elements: JSONPathComponentType... ) {
var array = [JSONPathComponent]()
for element in elements {
switch element {
case let key as String:
array.append( JSONPathComponent( key: key ) )
case let index as Int:
array.append( JSONPathComponent( index: index ) )
default:
break
}
}
self.init( array )
}
}
// String
extension JSONPath : StringLiteralConvertible {
public init( stringLiteral value: String ) {
self.init( value )
}
public init( extendedGraphemeClusterLiteral value: StaticString ) {
self.init( value.stringValue )
}
public init( unicodeScalarLiteral value: Character ) {
self.init( String( value ) )
}
}
// Int
extension JSONPath : IntegerLiteralConvertible {
public init( integerLiteral value: Int ) {
self.init( value )
}
}
// MARK: JSONPath accessors
extension JSONPath {
public var count: Int {
return self.components.count
}
public var isEmpty: Bool {
return self.components.isEmpty
}
public var first: JSONPathComponent? {
return self.components.first
}
public func take( count: Int ) -> JSONPath {
if count <= 0 {
return JSONPath()
}
if count <= self.count {
let splice = self.components[ 0 ..< count ]
let array = [JSONPathComponent]( splice )
return JSONPath( array )
}
return self
}
public func drop( count: Int ) -> JSONPath {
if count <= 0 {
return self
}
if count <= self.count {
let splice = self.components[ count ..< self.count ]
let array = [JSONPathComponent]( splice )
return JSONPath( array )
}
return JSONPath()
}
public func dropFirst() -> JSONPath {
let slice = Swift.dropFirst( self.components )
let array = [JSONPathComponent]( slice )
let path = JSONPath( array )
return path
}
var body: JSONPath {
let slice = Swift.dropLast( self.components )
let array = [JSONPathComponent]( slice )
let path = JSONPath( array )
return path
}
var tail: JSONPath {
let slice = Swift.dropFirst( self.components )
let array = [JSONPathComponent]( slice )
let path = JSONPath( array )
return path
}
public func dropLast() -> JSONPath {
let slice = Swift.dropLast( self.components )
let array = [JSONPathComponent]( slice )
let path = JSONPath( array )
return path
}
public var last: JSONPathComponent? {
return self.components.last
}
}
// MARK: JSONPath : Equatable
extension JSONPath : Equatable {}
public func ==( lhs: JSONPath, rhs: JSONPath ) -> Bool {
if lhs.components.count != rhs.components.count {
return false
}
for index in 0 ..< lhs.components.count {
let lcomponent = lhs.components[ index ]
let rcomponent = rhs.components[ index ]
if lcomponent != rcomponent {
return false
}
}
return true
}
// MARK: JSONPath : Comparable
extension JSONPath : Comparable {}
public func <( lhs: JSONPath, rhs: JSONPath ) -> Bool {
let lcomponent = lhs.first
let rcomponent = rhs.first
switch (lcomponent, rcomponent) {
case (.Some, .Some):
if lcomponent < rcomponent { return true }
if lcomponent > rcomponent { return false }
return lhs.body < rhs.body
case (.None, .Some):
return true
case (.Some, .None), (.None, .None):
return false
}
}
extension JSONPathComponent : Comparable {}
public func <( lhs: JSONPathComponent, rhs: JSONPathComponent ) -> Bool {
switch (lhs, rhs) {
case (.Key( let lkey ), .Key( let rkey )):
return lkey < rkey
case (.Index( let lindex ), .Index( let rindex )):
return lindex < rindex
case (.Key, .Index):
return true
case (.Index, .Key):
return false
}
}
extension JSONPath {
public func isPrefixOf( path: JSONPath ) -> Bool {
if self.count <= path.count {
for index in 0 ..< self.count {
if self[ index ] != path[ index ] {
return false
}
}
return true
}
else {
return false
}
}
}
// MARK: JSONPath : Hashable
extension JSONPath : Hashable {
public var hashValue: Int {
var path = join( "+", self.components.map { $0.string } )
return path.hashValue
}
}
// MARK: JSONPath : SequenceType
extension JSONPath : SequenceType {
typealias Generator = IndexingGenerator<[JSONPathComponent]>
public func generate() -> IndexingGenerator<[JSONPathComponent]> {
return self.components.generate()
}
}
// MARK: JSONPath : CollectionType
extension JSONPath : CollectionType {
public typealias Index = Int
public var startIndex: Int {
return self.components.startIndex
}
public var endIndex: Int {
return self.components.endIndex
}
public subscript( position: Int ) -> JSONPathComponent {
return self.components[ position ]
}
}
// MARK: JSONPath : ExtensibleCollectionType
extension JSONPath : ExtensibleCollectionType {
public mutating func reserveCapacity( capacity: Int ) {
self.components.reserveCapacity( capacity )
}
public mutating func append( component: JSONPathComponent ) {
self.components.append( component )
}
public mutating func append( component: JSONPathComponentType ) {
self.components.append( JSONPathComponent( component ) )
}
public mutating func extend<S : SequenceType where S.Generator.Element == JSONPathComponent>( elements: S ) {
self.components.extend( elements )
}
public mutating func extend( elements: JSONPath ) {
self.components.extend( elements.components )
}
}
public func +=( inout lhs: JSONPath, rhs: JSONPathComponentType ) {
lhs.append( rhs )
}
public func +=( inout lhs: JSONPath, rhs: JSONPathComponent ) {
lhs.append( rhs )
}
public func +=( inout lhs: JSONPath, rhs: JSONPath ) {
lhs.extend( rhs )
}
// MARK: JSONPath : Printable
extension JSONPath : Printable {
public var description: String {
return "[ " + join( ", ", self.components.map { $0.string } ) + " ]"
}
}
// MARK: -
// MARK: JSONPathComponent init
extension JSONPathComponent {
private init( key: String ) {
self = .Key( key )
}
private init( index: Int ) {
self = .Index( index )
}
// copy init
private init( component: JSONPathComponent ) {
self = component
}
private init( _ any: JSONPathComponentType ) {
switch any {
case let key as String:
self.init( key: key )
case let index as Int:
self.init( index: index )
default:
self.init( key: "" )
println( "JSONPathComponent.init didn't match \( any )" )
}
}
}
// MARK: JSONPathComponent init with literals
// String
extension JSONPathComponent : StringLiteralConvertible {
public init( stringLiteral value: String ) {
self.init( key: value )
}
public init( extendedGraphemeClusterLiteral value: StaticString ) {
self.init( key: value.stringValue )
}
public init( unicodeScalarLiteral value: Character ) {
self.init( key: String( value ) )
}
}
// Int
extension JSONPathComponent : IntegerLiteralConvertible {
public init( integerLiteral value: Int ) {
self.init( index: value )
}
}
// MARK: JSONPathComponent accessors
extension JSONPathComponent {
var key: String? {
switch self {
case .Key( let key ):
return key
case .Index:
return nil
}
}
var index: Int? {
switch self {
case .Key:
return nil
case .Index( let index ):
return index
}
}
var string: String {
switch self {
case .Key( let key ):
return key
case .Index( let index ):
return toString( index )
}
}
}
// MARK: JSONPathComponent : Equatable
extension JSONPathComponent : Equatable {}
public func ==( lhs: JSONPathComponent, rhs: JSONPathComponent ) -> Bool {
switch (lhs, rhs) {
case (.Key( let lkey ), .Key( let rkey ) ):
return lkey == rkey
case (.Index( let lindex ), .Index( let rindex )):
return lindex == rindex
default:
return false
}
}
// MARK: JSONPathComponent : Hashable
extension JSONPathComponent : Hashable {
public var hashValue: Int {
switch self {
case .Key( let key ):
return key.hashValue
case .Index( let index ):
return index.hashValue
}
}
}
// MARK: JSONPathComponent : Printable
extension JSONPathComponent : Printable {
public var description: String {
switch self {
case .Key( let key ):
return "key: \(key)"
case .Index( let index ):
return "index: \( index )"
}
}
}
| mpl-2.0 | 229795a9e7a92fb2096c438a31b57cf1 | 17.274648 | 110 | 0.66869 | 3.615465 | false | false | false | false |
dehli/TouchDraw | Sources/Stroke.swift | 1 | 1576 | //
// Stroke.swift
// TouchDraw
//
// Created by Christian Paul Dehli on 9/4/16.
//
import Foundation
import UIKit
/// A drawing stroke
open class Stroke: NSObject {
/// The points that make up the stroke
internal var points: [CGPoint]
/// The properties of the stroke
internal var settings: StrokeSettings
/// Default initializer
override public init() {
points = []
settings = StrokeSettings()
super.init()
}
/// Initialize a stroke with certain points and settings
public convenience init(points: [CGPoint], settings: StrokeSettings) {
self.init()
self.points = points
self.settings = StrokeSettings(settings)
}
/// Used to decode a Stroke with a decoder
required public convenience init?(coder aDecoder: NSCoder) {
var points = aDecoder.decodeObject(forKey: Stroke.pointsKey) as? [CGPoint]
if points == nil {
points = []
}
var settings = aDecoder.decodeObject(forKey: Stroke.settingsKey) as? StrokeSettings
if settings == nil {
settings = StrokeSettings()
}
self.init(points: points!, settings: settings!)
}
}
// MARK: - NSCoding
extension Stroke: NSCoding {
internal static let pointsKey = "points"
internal static let settingsKey = "settings"
/// Used to encode a Stroke with a coder
open func encode(with aCoder: NSCoder) {
aCoder.encode(self.points, forKey: Stroke.pointsKey)
aCoder.encode(self.settings, forKey: Stroke.settingsKey)
}
}
| mit | 0adef43f33e50f95df64483d2e6953d5 | 24.836066 | 91 | 0.639594 | 4.502857 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | Steps4Impact/Settings/SettingsDataSource.swift | 1 | 5542 | /**
* Copyright © 2019 Aga Khan Foundation
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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 Foundation
import RxSwift
class SettingsDataSource: TableViewDataSource {
var cache = Cache.shared
var disposeBag = DisposeBag()
var cells: [[CellContext]] = []
var completion: (() -> Void)?
enum SettingsContext: Context {
case viewTeam
case leaveTeam
case logout
case deleteAccount
case connectSource
case createAKFProfile
case personalMileCommitment
}
private var isTeamLead = false
private var imageURL: URL?
private var name: String = " "
private var isOnTeam: Bool = false
private var teamName: String = " "
private var teamMembership: String = " "
private var commitment: Int = 0
init() {
let update = Observable.combineLatest(
cache.socialDisplayNamesRelay,
cache.socialProfileImageURLsRelay,
cache.participantRelay
)
update.subscribeOnNext { [weak self] (names, imageURLs, participant) in
self?.name = names["me"] ?? " "
self?.imageURL = imageURLs["me"]
if let participant = participant {
self?.isOnTeam = participant.team != nil
self?.isTeamLead = participant.team?.creator == participant.fbid
self?.commitment = participant.currentEvent?.commitment?.miles ?? 0
}
self?.configure()
self?.completion?()
}.disposed(by: disposeBag)
}
func reload(completion: @escaping () -> Void) {
self.completion = completion
configure()
completion()
cache.fetchSocialInfo(fbid: User.id)
AKFCausesService.getParticipant(fbid: User.id) { [weak self] (result) in
self?.cache.participantRelay.accept(Participant(json: result.response))
}
}
func configure() {
cells = [[
// Profile
SettingsProfileCellContext(imageURL: imageURL, name: name,
teamName: teamName, membership: teamMembership),
// Personal
SettingsTitleCellContext(title: "Personal"),
SettingsDisclosureCellContext(title: "Personal Mile Commitment",
body: "Mile commitment cannot be changed once the challenge has started.",
value: "\(commitment) mi",
context: SettingsContext.personalMileCommitment),
SettingsSwitchCellContext(title: "Push Notifications",
isSwitchEnabled: true),
SettingsDisclosureCellContext(title: "Connected apps & devices",
context: SettingsContext.connectSource)
]]
if UserInfo.AKFID == nil {
cells.append([SettingsDisclosureCellContext(title: "Create Aga Khan Foundation Profile",
isLastItem: true,
context: SettingsContext.createAKFProfile)])
}
cells.append(contentsOf: [[
// Team
SettingsTitleCellContext(title: "Team"),
SettingsDisclosureCellContext(title: "View team",
isDisclosureHidden: !isOnTeam,
context: isOnTeam ? SettingsContext.viewTeam : nil),
(isTeamLead
? SettingsSwitchCellContext(title: "Team visibility",
body: "Your team is discoverable.\nAny participant can find and join your team.",
switchLabel: "Public",
isSwitchEnabled: true, isLastItem: true)
: SettingsDisclosureCellContext(title: "Leave Team",
isDisclosureHidden: !isOnTeam,
isLastItem: true,
context: isOnTeam ? SettingsContext.leaveTeam : nil)),
SettingsActionCellContext(title: "Logout",
context: SettingsContext.logout),
SettingsActionCellContext(title: "Delete Account", buttonStyle: .plain,
context: SettingsContext.deleteAccount)
]])
cells.append([
AppInfoCellContext(title: "Build Information", body: AppConfig.build)
])
}
}
| bsd-3-clause | 8261adfd9626bb588052a59c34c5929d | 39.152174 | 115 | 0.640679 | 5.111624 | false | false | false | false |
ctarda/Turnstile | Samples/TurnstileSample/Turnstile/ViewController.swift | 1 | 1200 | //
// ViewController.swift
// Turnstile
//
// Created by Cesar Tardaguila on 06/06/2015.
//
import UIKit
class ViewController: UIViewController, RegularDayObserver {
@IBOutlet weak var status: UILabel!
@IBOutlet weak var ringAlarmButton: UIButton!
@IBOutlet weak var brewTeaButton: UIButton!
@IBOutlet weak var goToWorkButton: UIButton!
@IBOutlet weak var fleeOfficeButton: UIButton!
private final lazy var myDay: RegularDay = {
return RegularDay(observer: self)
}()
@IBAction func ringAlarm() {
myDay.getUp()
}
@IBAction func brewTea() {
myDay.brewTea()
}
@IBAction func goToWork() {
myDay.goToWork()
}
@IBAction func fleeOffice() {
myDay.fleeOffice()
}
override func viewDidLoad() {
super.viewDidLoad()
myDay.start()
}
func newEvent(message: String) {
status?.text = message
ringAlarmButton?.isEnabled = myDay.canGetUp()
brewTeaButton?.isEnabled = myDay.canBrewTea()
goToWorkButton?.isEnabled = myDay.canGoToWork()
fleeOfficeButton?.isEnabled = myDay.canFleeOffice()
}
}
| mit | 806074f6b7853dfc052ab2d944ab9ae1 | 22.076923 | 60 | 0.620833 | 4.270463 | false | false | false | false |
rbailoni/SOSHospital | SOSHospital/SOSHospital/CustomTabBarController.swift | 1 | 2505 | //
// CustomTabBarController.swift
// SOSHospital
//
// Created by William kwong huang on 11/3/15.
// Copyright © 2015 Quaddro. All rights reserved.
//
import UIKit
import CoreLocation
class CustomTabBarController: UITabBarController, CLLocationManagerDelegate {
// MARK: Variaveis globais
private var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
private var hospitalData = Hospital()
var locationManager = CLLocationManager()
var coordinate: CLLocationCoordinate2D?
// MARK: View
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
print("bem vindo tabBar")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if !self.locationManager.requestAuthorization() {
presentViewController(self.locationManager.showNegativeAlert(), animated: true, completion: nil)
}
}
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
// Tomar cuidado
switch item.title! {
// Mapa
//case 0:
// Filtro
// case "Filtro":
// let storyBoard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
//
// let controller = storyBoard.instantiateViewControllerWithIdentifier("FilterTableViewController") as? FilterTableViewController
//
// controller?.locationManager = self.locationManager
// Credito
case "Créditos":
locationManager.stopUpdatingLocation()
default:
if !self.locationManager.requestAuthorization() {
presentViewController(self.locationManager.showNegativeAlert(), animated: true, completion: nil)
}
break
}
}
// MARK: Location Manager Delegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.coordinate = locations.last!.coordinate
print("TabBar --> \(NSDate()) lat:\(coordinate!.latitude), long:\(coordinate!.longitude)")
locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error)
}
}
| mit | 4e51a1561773af5c7bface686186a0c9 | 28.104651 | 140 | 0.613664 | 5.624719 | false | false | false | false |
LiskUser1234/SwiftyLisk | Lisk/Peer/Operations/PeerGetPeerOperation.swift | 1 | 2058 | /*
The MIT License
Copyright (C) 2017 LiskUser1234
- Github: https://github.com/liskuser1234
Please vote LiskUser1234 for delegate to support this project.
For donations:
- Lisk: 6137947831033853925L
- Bitcoin: 1NCTZwBJF7ZFpwPeQKiSgci9r2pQV3G7RG
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 SwiftyJSON
open class PeerGetPeerOperation : APIOperation {
private let ip: String
private let port: Int16
private let peerPtr: UnsafeMutablePointer<JSON>
public init(ip: String,
port: Int16,
peerPtr: UnsafeMutablePointer<JSON>,
errorPtr: UnsafeMutablePointer<String?>? = nil) {
self.ip = ip
self.port = port
self.peerPtr = peerPtr
super.init(errorPtr: errorPtr)
}
override open func start() {
PeerAPI.getPeer(ip: ip, port: port, callback: callback)
}
override internal func processResponse(json: JSON) {
self.peerPtr.pointee = json["peer"]
}
}
| mit | 64f48b2ec4ecadd46c1a12dc47942d07 | 32.193548 | 78 | 0.713314 | 4.48366 | false | false | false | false |
prey/prey-ios-client | Prey/Classes/AlertVC.swift | 1 | 1236 | //
// AlertVC.swift
// Prey
//
// Created by Javier Cala Uribe on 29/06/16.
// Copyright © 2016 Prey, Inc. All rights reserved.
//
import UIKit
class AlertVC: UIViewController {
// MARK: Properties
@IBOutlet var messageLbl : UILabel!
@IBOutlet var subtitleLbl : UILabel!
var messageToShow = ""
// MARK: Init
override func viewDidLoad() {
super.viewDidLoad()
// View title for GAnalytics
// self.screenName = "Alert"
// Set message
messageLbl.text = messageToShow
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool){
// Hide navigationBar when appear this ViewController
self.navigationController?.isNavigationBarHidden = true
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Hide navigationBar when appear this ViewController
self.navigationController?.isNavigationBarHidden = false
}
}
| gpl-3.0 | 9961cfbeecce2d12bef9dd336b07330b | 23.215686 | 64 | 0.616194 | 5.369565 | false | false | false | false |
nastia05/TTU-iOS-Developing-Course | Lecture 6/Passworder/Passworder/PasswordGenerator.swift | 1 | 1792 | //
// PasswordGenerator.swift
// Passworder
//
// Created by nastia on 21.12.16.
// Copyright © 2016 Anastasiia Soboleva. All rights reserved.
//
import Foundation
fileprivate let elements = ["qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM", "1234567890", "🤓😂👻😉😜😎😈👍🎃"]
struct CharType: OptionSet {
let rawValue: Int
static let letters = CharType(rawValue: 1 << 0)
static let numbers = CharType(rawValue: 1 << 1)
static let symbols = CharType(rawValue: 1 << 2)
var toGeneratePasswordFrom: String {
var result = ""
if contains(.letters) {
result += elements[0]
}
if contains(.numbers) {
result += elements[1]
}
if contains(.symbols) {
result += elements[2]
}
return result
}
mutating func updateSetting(with type: CharType, include: Bool) {
if include {
insert(type)
} else {
remove(type)
}
}
}
class PasswordGenerator {
weak var passwordDelegate: PasswordGeneratorProtocol?
var settings = CharType.letters {
didSet {
passwordDelegate?.passwordGeneratorDidUpdateSettings(passwordGenerator: self)
}
}
var length = 8 {
didSet {
passwordDelegate?.passwordGeneratorDidUpdateSettings(passwordGenerator: self)
}
}
func generate() -> String {
var password = ""
for _ in 0..<length {
let passwordToGenerate = settings.toGeneratePasswordFrom
let randomIndex = arc4random_uniform(UInt32(passwordToGenerate.characters.count))
let element = passwordToGenerate.characters[passwordToGenerate.index(passwordToGenerate.startIndex, offsetBy: String.IndexDistance(randomIndex))]
password += String(element)
}
return password
}
}
protocol PasswordGeneratorProtocol: NSObjectProtocol {
func passwordGeneratorDidUpdateSettings(passwordGenerator: PasswordGenerator)
}
| mit | 198b8d224204a104ba81c1cd1c19d2de | 22.52 | 148 | 0.725624 | 3.62963 | false | false | false | false |
stendahls/AsyncTask | Source/Base/Task.swift | 1 | 2759 | //
// AsyncTask.swift
// Pods
//
// Created by Zhixuan Lai on 5/27/16.
//
// 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
// Meant to be used only for scenarios where no error can be produced
public protocol TaskType {
associatedtype ReturnType
typealias ResultCallback = (ReturnType) -> Void
func action(_ completion: @escaping ResultCallback)
func async(_ queue: DispatchQueue, completion: @escaping ResultCallback)
func await(_ queue: DispatchQueue) -> ReturnType
}
extension TaskType {
public var throwableTask: ThrowableTask<ReturnType> {
return ThrowableTask<ReturnType>(action: { callback in
self.action { result in
callback(Result.success(result))
}
})
}
public func async(_ queue: DispatchQueue = DefaultQueue, completion: @escaping (ResultCallback) = {_ in}) {
throwableTask.asyncResult(queue) {result in
if case let .success(r) = result {
completion(r)
}
}
}
public func await(_ queue: DispatchQueue = DefaultQueue) -> ReturnType {
return try! throwableTask.awaitResult(queue).extract()
}
}
open class Task<ReturnType> : TaskType {
public typealias ResultCallback = (ReturnType) -> Void
private let action: (@escaping ResultCallback) -> Void
open func action(_ completion: @escaping ResultCallback) {
self.action(completion)
}
public init(action anAction: @escaping (@escaping ResultCallback) -> Void) {
self.action = anAction
}
public convenience init(action: @escaping () -> ReturnType) {
self.init {callback in callback(action())}
}
}
| mit | 4b48f53458a2747d576c8536555d3938 | 33.4875 | 111 | 0.68793 | 4.629195 | false | false | false | false |
tanuva/wled | WLED/WLED/API.swift | 1 | 4895 | //
// API.swift
// WLED
//
// Created by Marcel on 23.07.15.
// Copyright © 2015 Marcel Brüggebors. All rights reserved.
//
import Foundation
import UIKit
enum APIErrorCode: ErrorType {
case NETWORK_ERROR
case JSON_ERROR
}
class APIError {
let code: APIErrorCode
var description: String?
required init(code: APIErrorCode, description: String?) {
self.code = code
self.description = description
}
}
class API: NSObject {
let cgiUrl: String
let session: NSURLSession
required init(cgiUrl: String) {
self.cgiUrl = cgiUrl
let urlSessionConfig = NSURLSessionConfiguration.ephemeralSessionConfiguration()
self.session = NSURLSession(configuration: urlSessionConfig)
}
func setEnabled(enabled: Bool, handler: (APIError?) -> Void) {
self.sendPost("enabled=1", handler: handler)
}
func getColor(handler: (APIError?, UIColor?) -> Void) {
let request = NSURLRequest(URL: NSURL(string: self.cgiUrl + "/color")!)
print("<< \(request.URL!)")
let task = self.session.dataTaskWithRequest(request) {
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Example:
// { "color": "3eff18" }
if let e = error {
print("Error: \(e.localizedDescription)\nReason: \(e.localizedFailureReason)")
handler(APIError(code: APIErrorCode.NETWORK_ERROR, description: e.localizedDescription), nil)
return
}
// TODO Are we interested in 'response'?
let jsonString = String(NSString(data: data!, encoding: NSUTF8StringEncoding)!)
do {
print(">> \(jsonString)")
let parsedObject = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
guard let dict = parsedObject as? NSDictionary else {
throw APIErrorCode.JSON_ERROR
}
handler(nil, API.colorWithHexString(dict["color"] as! String))
} catch _ {
handler(APIError(code: APIErrorCode.JSON_ERROR, description: jsonString), nil)
}
}
task.resume()
}
func setColor(color: UIColor, handler: (APIError?) -> Void) {
print("sending " + API.hexStringWithColor(color))
sendPost("color=" + API.hexStringWithColor(color), handler: handler)
}
func sendPost(data: String, handler: (APIError?) -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: self.cgiUrl)!)
request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding)
print("<< \(request.URL!) Body: \(data)")
let task = self.session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let e = error {
print("Error: \(e.localizedDescription)\nReason: \(e.localizedFailureReason)")
handler(APIError(code: APIErrorCode.NETWORK_ERROR, description: e.localizedDescription))
return
}
if let r = (response as? NSHTTPURLResponse) {
if r.statusCode != 200 {
handler(APIError(code: APIErrorCode.NETWORK_ERROR, description: "Code: \(r.statusCode)\nDescription: \(r.description)"))
return
}
}
print(">> \(String(NSString(data: data!, encoding: NSUTF8StringEncoding)!))")
handler(nil)
}
task.resume()
}
// Creates a UIColor from a hex string. (Adapted from: arshad, https://gist.github.com/arshad/de147c42d7b3063ef7bc)
static func colorWithHexString(hex: String) -> UIColor {
var tmpHex = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if tmpHex.hasPrefix("#") {
tmpHex = tmpHex.substringFromIndex(tmpHex.startIndex.advancedBy(1))
}
if (tmpHex.characters.count != 6) {
return UIColor.grayColor()
}
let rString = tmpHex.substringToIndex(tmpHex.startIndex.advancedBy(2))
let gString = tmpHex.substringFromIndex(tmpHex.startIndex.advancedBy(2)).substringToIndex(tmpHex.startIndex.advancedBy(2))
let bString = tmpHex.substringFromIndex(tmpHex.startIndex.advancedBy(4))
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(Float(r) / 255.0),
green: CGFloat(Float(g) / 255.0),
blue: CGFloat(Float(b) / 255.0),
alpha: CGFloat(1))
}
// Creates a hex string from a UIColor. (Adapted from http://stackoverflow.com/a/14428870)
static func hexStringWithColor(color: UIColor) -> String {
var hexColor = ""
// This method only works for RGBA colors
if (CGColorGetNumberOfComponents(color.CGColor) == 4) {
let components = CGColorGetComponents(color.CGColor)
let r = roundf(Float(components[0] * 255.0))
let g = roundf(Float(components[1] * 255.0))
let b = roundf(Float(components[2] * 255.0))
// Convert with %02x (use 02 to always get two chars)
hexColor = String(NSString(format: "%02x%02x%02x", Int(r), Int(g), Int(b)))
}
return hexColor;
}
}
| gpl-3.0 | 87c4c3656ed8741881e54c5b8b977e24 | 33.216783 | 126 | 0.709176 | 3.632517 | false | false | false | false |
ProteanBear/ProteanBear_Swift | library/pb.swift.ui/ExtensionUIViewController.swift | 1 | 3605 | //
// ExtensionUIViewController.swift
// pb.swift.ui
// 扩展视图控制器,增加数据绑定载入处理方法
// Created by Maqiang on 15/6/29.
// Copyright (c) 2015年 Maqiang. All rights reserved.
//
import Foundation
import UIKit
/*PbMsyPosition:
* 消息显示位置
*/
public enum PbMsyPosition:Int
{
case top,bottom
}
extension UIViewController
{
/// 获取数据,这种扩展方式需要实现协议
/// - parameter updateMode:数据更新模式
/// - parameter controller:协议实现对象
public func pbLoadData(_ updateMode:PbDataUpdateMode,controller:PbUIViewControllerProtocol?)
{
PbDataAdapter(delegate:controller).loadData(updateMode)
}
/// 提示信息,注意有些表格或网格视图底部显示时会看不到
/// - parameter msg :提示信息
/// - parameter dismissAfterSecond :消失时间,单位为秒
/// - parameter position :显示位置
public func pbMsgTip(_ msg:String,dismissAfterSecond:TimeInterval,position:PbMsyPosition)
{
//创建元素
let label=UILabel(frame:CGRect.zero)
label.translatesAutoresizingMaskIntoConstraints=false
label.backgroundColor=UIColor(white:0, alpha:0.7)
label.textColor=UIColor.white
label.font=UIFont.systemFont(ofSize: 14)
label.layer.cornerRadius=4
label.clipsToBounds=true
label.textAlignment = .center
label.numberOfLines=0
label.text=msg
label.layer.opacity=0
self.view.addSubview(label)
//计算尺寸
let minSize:CGFloat=200.0
let margin:CGFloat=10.0
let size=NSString(string:msg).boundingRect(with: CGSize(width: minSize,height: minSize), options: .usesLineFragmentOrigin, attributes:["NSFontAttributeName":label.font], context:nil).size
//设置布局
self.view.addConstraint(NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[label(==width)]", options: .alignAllLastBaseline, metrics: ["width":minSize], views:["label":label]))
if(position == .top)
{
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-margin-[label(==height)]", options: .alignAllLastBaseline, metrics:["height":size.height+margin,"margin":margin], views:["label":label]))
}
if(position == .bottom)
{
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[label(==height)]-margin-|", options: .alignAllLastBaseline, metrics: ["height":size.height+margin,"margin":margin], views:["label":label]))
}
//显示元素
UIView.animate(withDuration: 0.3, delay: 0, options:UIViewAnimationOptions(), animations: { () -> Void in
label.layer.opacity=1
}) { (finished) -> Void in
if(finished)
{
//隐藏元素
UIView.animate(withDuration: 0.3, delay: dismissAfterSecond, options: UIViewAnimationOptions(), animations: { () -> Void in
label.layer.opacity=0
}, completion: { (isFinished) -> Void in
if(isFinished)
{
label.removeFromSuperview()
}
})
}
}
}
}
| apache-2.0 | 281e4dc4c531f0f733b0e9409864c450 | 38.658824 | 229 | 0.611391 | 4.464901 | false | false | false | false |
jakeheis/Shout | Sources/Shout/Session.swift | 1 | 2954 | //
// Session.swift
// Shout
//
// Created by Jake Heiser on 3/4/18.
//
import Foundation
import CSSH
import Socket
/// Direct bindings to libssh2_session
class Session {
private static let initResult = libssh2_init(0)
private let cSession: OpaquePointer
private var agent: Agent?
var blocking: Int32 {
get {
return libssh2_session_get_blocking(cSession)
}
set(newValue) {
libssh2_session_set_blocking(cSession, newValue)
}
}
init() throws {
guard Session.initResult == 0 else {
throw SSHError.genericError("libssh2_init failed")
}
guard let cSession = libssh2_session_init_ex(nil, nil, nil, nil) else {
throw SSHError.genericError("libssh2_session_init failed")
}
self.cSession = cSession
}
func handshake(over socket: Socket) throws {
let code = libssh2_session_handshake(cSession, socket.socketfd)
try SSHError.check(code: code, session: cSession)
}
func authenticate(username: String, privateKey: String, publicKey: String, passphrase: String?) throws {
let code = libssh2_userauth_publickey_fromfile_ex(cSession,
username,
UInt32(username.count),
publicKey,
privateKey,
passphrase)
try SSHError.check(code: code, session: cSession)
}
func authenticate(username: String, password: String) throws {
let code = libssh2_userauth_password_ex(cSession,
username,
UInt32(username.count),
password,
UInt32(password.count),
nil)
try SSHError.check(code: code, session: cSession)
}
func openSftp() throws -> SFTP {
return try SFTP(session: self, cSession: cSession)
}
func openCommandChannel() throws -> Channel {
return try Channel.createForCommand(cSession: cSession)
}
func openSCPChannel(fileSize: Int64, remotePath: String, permissions: FilePermissions) throws -> Channel {
return try Channel.createForSCP(cSession: cSession, fileSize: fileSize, remotePath: remotePath, permissions: permissions)
}
func openAgent() throws -> Agent {
if let agent = agent {
return agent
}
let newAgent = try Agent(cSession: cSession)
agent = newAgent
return newAgent
}
deinit {
libssh2_session_free(cSession)
}
}
| mit | 07e430dc95dd47f9fced622928984d56 | 31.461538 | 129 | 0.520311 | 5.200704 | false | false | false | false |
lieonCX/Live | Live/ViewModel/Common/LiveListViewModel.swift | 1 | 3632 | //
// LiveListViewModel.swift
// Live
//
// Created by lieon on 2017/7/12.
// Copyright © 2017年 ChengDuHuanLeHui. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import PromiseKit
class LiveListViewModel {
lazy var listGroup: ListGroup = ListGroup()
lazy var moreListGroup: ListGroup = ListGroup()
var currentPage: Int = 0
var lastRequstCount: Int = 0
func requstList(with param: LiveListRequstParam, isMoreRefresh: Bool = false) -> Promise<Bool> {
let req: Promise<ListGroupResponse> = RequestManager.request(.endpoint(LiveListPath.live, param: param))
return req.then { [unowned self] (response) -> Bool in
guard let listgroup = response.object, let group = listgroup.group else { return false }
if isMoreRefresh { /// 如果是刷新更多,则在原始数据上拼接数据
if !group.isEmpty {
self.listGroup.group?.append(contentsOf: group)
self.moreListGroup = listgroup
return true
} else {
self.currentPage -= 1
if self.currentPage <= 0 {
self.currentPage = 0
}
return false
}
} else {
self.listGroup = listgroup
self.moreListGroup = listgroup
}
return true
}
}
func requestNearByList(with param: LiveListRequstParam, isMoreRefresh: Bool = false) -> Promise<Bool> {
let req: Promise<ListGroupResponse> = RequestManager.request(.endpoint(LiveListPath.nearby, param: param))
return req.then { [unowned self] (response) -> Bool in
guard let listgroup = response.object, let group = listgroup.group else { return false }
if isMoreRefresh { /// 如果是刷新更多,则在原始数据上拼接数据
if !group.isEmpty {
self.listGroup.group?.append(contentsOf: group)
self.moreListGroup = listgroup
return true
} else {
self.currentPage -= 1
if self.currentPage <= 0 {
self.currentPage = 0
}
return false
}
} else {
self.listGroup = listgroup
self.moreListGroup = listgroup
}
return true
}
}
func requestMybroadcastList(with param: LiveListRequstParam, isClear: Bool) -> Promise<Bool> {
let req: Promise<ListGroupResponse> = RequestManager.request(.endpoint(LiveListPath.byUserId, param: param))
print(param)
return req.then { [unowned self] (response) -> Bool in
guard let listgroup = response.object, let group = listgroup.group else { return false }
if isClear {
self.listGroup.group = []
}
if group.isEmpty {
self.lastRequstCount = 0
self.listGroup = listgroup
return false
} else {
self.lastRequstCount = group.count
self.listGroup.group?.append(contentsOf: group)
return true
}
}
}
func delteBrocast(with liveId: Int) -> Promise<NullDataResponse> {
LiveListRequstParam.liveId = liveId
let req: Promise<NullDataResponse> = RequestManager.request(.endpoint(BroadcatPath.deleteeBroadcast, param: nil))
return req
}
}
| mit | 0dc6fdfcf4904cad9fb7be60aaa774d1 | 36.797872 | 122 | 0.554461 | 4.893939 | false | false | false | false |
amnuaym/TiAppBuilder | Day4/MyCameraApp/MyCameraApp/AppDelegate.swift | 1 | 4590 | //
// AppDelegate.swift
// MyCameraApp
//
// Created by Amnuay M on 9/4/17.
// Copyright © 2017 Amnuay M. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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: - 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: "MyCameraApp")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// 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)")
}
}
}
}
| gpl-3.0 | 8341f4d635207347040f1201ce23fad4 | 48.344086 | 285 | 0.685552 | 5.838422 | false | false | false | false |
team-pie/DDDKit | DDDKit/Classes/Extensions.swift | 1 | 2406 | //
// Extensions.swift
// Pods
//
// Created by Guillaume Sabran on 12/15/16.
//
//
import GLKit
extension EAGLContext {
static func ensureContext(is context: EAGLContext?) {
guard let context = context else { return }
if current() !== context {
if !setCurrent(context) {
print("could not set eagl context")
}
}
}
}
public extension GLKQuaternion {
/**
Initialize a quaternion from a vertical and horizontal rotations, in radian
- parameter right: the horizontal angle in radian
- parameter top: the vertical angle in radian
*/
public init(right: CGFloat, top: CGFloat) {
let ch = Float(cos(right / 2))
let sh = Float(sin(right / 2))
let cv = Float(cos(top / 2))
let sv = Float(sin(top / 2))
self.init(q: (
sv * ch,
cv * sh,
-sv * sh,
cv * ch
))
}
}
extension CVReturn {
func didError(from key: String) -> Bool {
if self != kCVReturnSuccess {
print("DDDKit error in \(key): \(self)")
return true
}
return false
}
}
extension CVPixelBufferPool {
/// Create an empty buffer pool
static func create(for size: CGSize, with format: OSType = kCVPixelFormatType_32BGRA) -> CVPixelBufferPool? {
var bufferPool: CVPixelBufferPool? = nil
let attributes: [String: Any] = [
kCVPixelFormatOpenGLESCompatibility as String: true,
kCVPixelBufferIOSurfacePropertiesKey as String: [:],
kCVPixelBufferPixelFormatTypeKey as String: format,
kCVPixelBufferWidthKey as String: size.width,
kCVPixelBufferHeightKey as String: size.height
]
let retainedBufferCount = 6
let poolAttributes: [String: Any] = [
kCVPixelBufferPoolMinimumBufferCountKey as String: retainedBufferCount
]
CVPixelBufferPoolCreate(
nil,
poolAttributes as CFDictionary,
attributes as CFDictionary,
&bufferPool
).didError(from: "CVPixelBufferPoolCreate")
guard bufferPool != nil else { return nil }
let bufferPoolAuxAttrs = [
kCVPixelBufferPoolAllocationThresholdKey as String:
retainedBufferCount
] as CFDictionary
var pixelBuffers = [CVPixelBuffer]()
var error: OSStatus? = nil
while true {
var pixelBuffer: CVPixelBuffer? = nil
error = CVPixelBufferPoolCreatePixelBufferWithAuxAttributes(
nil, bufferPool!, bufferPoolAuxAttrs, &pixelBuffer)
if error == kCVReturnWouldExceedAllocationThreshold { break }
pixelBuffers.append(pixelBuffer!)
}
pixelBuffers.removeAll()
return bufferPool
}
}
| mit | bf4f302feb5647fbeb9e46a2e0238594 | 22.821782 | 110 | 0.710308 | 3.788976 | false | false | false | false |
mozilla-mobile/firefox-ios | Sync/Synchronizers/ClientsSynchronizer.swift | 2 | 19134 | // 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 Shared
import Storage
import SwiftyJSON
private let log = Logger.syncLogger
let ClientsStorageVersion = 1
// TODO
public protocol Command {
static func fromName(_ command: String, args: [JSON]) -> Command?
func run(_ synchronizer: ClientsSynchronizer) -> Success
static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command?
}
// Shit.
// We need a way to wipe or reset engines.
// We need a way to log out the account.
// So when we sync commands, we're gonna need a delegate of some kind.
open class WipeCommand: Command {
public init?(command: String, args: [JSON]) {
return nil
}
open class func fromName(_ command: String, args: [JSON]) -> Command? {
return WipeCommand(command: command, args: args)
}
open func run(_ synchronizer: ClientsSynchronizer) -> Success {
return succeed()
}
public static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? {
let json = JSON(parseJSON: syncCommand.value)
if let name = json["command"].string,
let args = json["args"].array {
return WipeCommand.fromName(name, args: args)
}
return nil
}
}
open class DisplayURICommand: Command {
let uri: URL
let title: String
let sender: String
public init?(command: String, args: [JSON]) {
if let uri = args[0].string?.asURL,
let sender = args[1].string,
let title = args[2].string {
self.uri = uri
self.sender = sender
self.title = title
} else {
// Oh, Swift.
self.uri = "http://localhost/".asURL!
self.title = ""
return nil
}
}
open class func fromName(_ command: String, args: [JSON]) -> Command? {
return DisplayURICommand(command: command, args: args)
}
open func run(_ synchronizer: ClientsSynchronizer) -> Success {
func display(_ deviceName: String? = nil) -> Success {
synchronizer.delegate.displaySentTab(for: uri, title: title, from: deviceName)
return succeed()
}
guard let sender = synchronizer.localClients?.getClient(guid: sender) else {
return display()
}
return sender >>== { client in
return display(client?.name)
}
}
public static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? {
let json = JSON(parseJSON: syncCommand.value)
if let name = json["command"].string,
let args = json["args"].array {
return DisplayURICommand.fromName(name, args: args)
}
return nil
}
}
let Commands: [String: (String, [JSON]) -> Command?] = [
"wipeAll": WipeCommand.fromName,
"wipeEngine": WipeCommand.fromName,
// resetEngine
// resetAll
// logout
"displayURI": DisplayURICommand.fromName,
// repairResponse
]
open class ClientsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer {
public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, why: SyncReason) {
super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, why: why, collection: "clients")
}
var localClients: RemoteClientsAndTabs?
// Indicates whether the local client record has been updated to used the
// FxA Device ID rather than the native client GUID
var clientGuidIsMigrated: Bool = false
override var storageVersion: Int {
return ClientsStorageVersion
}
var clientRecordLastUpload: Timestamp {
get {
return self.prefs.unsignedLongForKey("lastClientUpload") ?? 0
}
set(value) {
self.prefs.setLong(value, forKey: "lastClientUpload")
}
}
// Sync Object Format (Version 1) for Form Factors: http://docs.services.mozilla.com/sync/objectformats.html#id2
fileprivate enum SyncFormFactorFormat: String {
case phone = "phone"
case tablet = "tablet"
}
open func getOurClientRecord() -> Record<ClientPayload> {
let fxaDeviceId = self.scratchpad.fxaDeviceId
let formfactor = formFactorString()
let json = JSON([
"id": fxaDeviceId,
"fxaDeviceId": fxaDeviceId,
"version": AppInfo.appVersion,
"protocols": ["1.5"],
"name": self.scratchpad.clientName,
"os": "iOS",
"commands": [JSON](),
"type": "mobile",
"appPackage": AppInfo.baseBundleIdentifier,
"application": AppInfo.displayName,
"device": DeviceInfo.deviceModel(),
"formfactor": formfactor])
let payload = ClientPayload(json)
return Record(id: fxaDeviceId, payload: payload, ttl: ThreeWeeksInSeconds)
}
fileprivate func formFactorString() -> String {
let userInterfaceIdiom = UIDevice.current.userInterfaceIdiom
var formfactor: String
switch userInterfaceIdiom {
case .phone:
formfactor = SyncFormFactorFormat.phone.rawValue
case .pad:
formfactor = SyncFormFactorFormat.tablet.rawValue
default:
formfactor = SyncFormFactorFormat.phone.rawValue
}
return formfactor
}
fileprivate func clientRecordToLocalClientEntry(_ record: Record<ClientPayload>) -> RemoteClient {
let modified = record.modified
let payload = record.payload
return RemoteClient(json: payload.json, modified: modified)
}
// If this is a fresh start, do a wipe.
// N.B., we don't wipe outgoing commands! (TODO: check this when we implement commands!)
// N.B., but perhaps we should discard outgoing wipe/reset commands!
fileprivate func wipeIfNecessary(_ localClients: RemoteClientsAndTabs) -> Success {
if self.lastFetched == 0 {
return localClients.wipeClients()
}
return succeed()
}
/**
* Returns whether any commands were found (and thus a replacement record
* needs to be uploaded). Also returns the commands: we run them after we
* upload a replacement record.
*/
fileprivate func processCommandsFromRecord(_ record: Record<ClientPayload>?, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Deferred<Maybe<(Bool, [Command])>> {
log.debug("Processing commands from downloaded record.")
// TODO: short-circuit based on the modified time of the record we uploaded, so we don't need to skip ahead.
if let record = record {
let commands = record.payload.commands
if !commands.isEmpty {
func parse(_ json: JSON) -> Command? {
if let name = json["command"].string,
let args = json["args"].array,
let constructor = Commands[name] {
return constructor(name, args)
}
return nil
}
// TODO: can we do anything better if a command fails?
return deferMaybe((true, optFilter(commands.map(parse))))
}
}
return deferMaybe((false, []))
}
fileprivate func uploadClientCommands(toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
return localClients.getCommands() >>== { clientCommands in
return clientCommands.map { (clientGUID, commands) -> Success in
self.syncClientCommands(clientGUID, commands: commands, clientsAndTabs: localClients, withServer: storageClient)
}.allSucceed()
}
}
fileprivate func syncClientCommands(_ clientGUID: GUID, commands: [SyncCommand], clientsAndTabs: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
let deleteCommands: () -> Success = {
return clientsAndTabs.deleteCommands(clientGUID).bind({ x in return succeed() })
}
log.debug("Fetching current client record for client \(clientGUID).")
let fetch = storageClient.get(clientGUID)
return fetch.bind { result in
if let response = result.successValue, response.value.payload.isValid() {
let record = response.value
if var clientRecord = record.payload.json.dictionary {
clientRecord["commands"] = JSON(record.payload.commands + commands.map { JSON(parseJSON: $0.value) })
let uploadRecord = Record(id: clientGUID, payload: ClientPayload(JSON(clientRecord)), ttl: ThreeWeeksInSeconds)
return storageClient.put(uploadRecord, ifUnmodifiedSince: record.modified)
>>== { resp in
log.debug("Client \(clientGUID) commands upload succeeded.")
// Always succeed, even if we couldn't delete the commands.
return deleteCommands()
}
}
} else {
if let failure = result.failureValue {
log.warning("Failed to fetch record with GUID \(clientGUID).")
if failure is NotFound<HTTPURLResponse> {
log.debug("Not waiting to see if the client comes back.")
// TODO: keep these around and retry, expiring after a while.
// For now we just throw them away so we don't fail every time.
return deleteCommands()
}
if failure is BadRequestError<HTTPURLResponse> {
log.debug("We made a bad request. Throwing away queued commands.")
return deleteCommands()
}
}
}
log.error("Client \(clientGUID) commands upload failed: No remote client for GUID")
return deferMaybe(UnknownError())
}
}
/**
* Upload our record if either (a) we know we should upload, or (b)
* our own notes tell us we're due to reupload.
*/
fileprivate func maybeUploadOurRecord(_ should: Bool, ifUnmodifiedSince: Timestamp?, toServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
let lastUpload = self.clientRecordLastUpload
let expired = lastUpload < (Date.now() - (2 * OneDayInMilliseconds))
log.debug("Should we upload our client record? Caller = \(should), expired = \(expired).")
if !should && !expired {
return succeed()
}
let iUS: Timestamp? = ifUnmodifiedSince ?? ((lastUpload == 0) ? nil : lastUpload)
var uploadStats = SyncUploadStats()
return storageClient.put(getOurClientRecord(), ifUnmodifiedSince: iUS)
>>== { resp in
if let ts = resp.metadata.lastModifiedMilliseconds {
// Protocol says this should always be present for success responses.
log.debug("Client record upload succeeded. New timestamp: \(ts).")
self.clientRecordLastUpload = ts
uploadStats.sent += 1
} else {
uploadStats.sentFailed += 1
}
self.statsSession.recordUpload(stats: uploadStats)
return succeed()
}
}
fileprivate func applyStorageResponse(
_ response: StorageResponse<[Record<ClientPayload>]>,
toLocalClients localClients: RemoteClientsAndTabs,
withServer storageClient: Sync15CollectionClient<ClientPayload>
) -> Success {
log.debug("Applying clients response.")
var downloadStats = SyncDownloadStats()
let records = response.value
let responseTimestamp = response.metadata.lastModifiedMilliseconds
log.debug("Got \(records.count) client records.")
let ourGUID = self.scratchpad.clientGUID
let ourFxaDeviceId = self.scratchpad.fxaDeviceId
var toInsert = [RemoteClient]()
var ours: Record<ClientPayload>?
// Indicates whether the local client records include a record with an ID
// matching the FxA Device ID
var ourClientRecordExists: Bool = false
for (rec) in records {
guard rec.payload.isValid() else {
log.warning("Client record \(rec.id) is invalid. Skipping.")
continue
}
if rec.id == ourGUID {
if self.clientGuidIsMigrated {
log.debug("Skipping our own client records since the guid is not the fxa device ID")
} else {
SentryIntegration.shared.send(message: "An unmigrated client record was found with a GUID for an ID", tag: SentryTag.clientSynchronizer, severity: .error)
}
} else if rec.id == ourFxaDeviceId {
ourClientRecordExists = true
if rec.modified == self.clientRecordLastUpload {
log.debug("Skipping our own unmodified record.")
} else {
log.debug("Saw our own record in response.")
ours = rec
}
} else {
toInsert.append(self.clientRecordToLocalClientEntry(rec))
}
}
downloadStats.applied += toInsert.count
// Apply remote changes.
// Collect commands from our own record and reupload if necessary.
// Then run the commands and return.
return localClients.insertOrUpdateClients(toInsert)
>>== { succeeded in
downloadStats.succeeded += succeeded
downloadStats.failed += (toInsert.count - succeeded)
self.statsSession.recordDownload(stats: downloadStats)
return succeed()
}
>>== { self.processCommandsFromRecord(ours, withServer: storageClient) }
>>== { (shouldUpload, commands) in
let ourRecordDidChange = self.why == .didLogin || self.why == .clientNameChanged
return self.maybeUploadOurRecord(shouldUpload || ourRecordDidChange || self.clientGuidIsMigrated || !ourClientRecordExists, ifUnmodifiedSince: ours?.modified, toServer: storageClient)
>>> { self.uploadClientCommands(toLocalClients: localClients, withServer: storageClient) }
>>> {
log.debug("Running \(commands.count) commands.")
for command in commands {
_ = command.run(self)
}
self.lastFetched = responseTimestamp!
return succeed()
}
}
}
open func synchronizeLocalClients(_ localClients: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult {
log.debug("Synchronizing clients.")
self.localClients = localClients // Store for later when we process a repairResponse command
if let reason = self.reasonToNotSync(storageClient) {
switch reason {
case .engineRemotelyNotEnabled:
// This is a hard error for us.
return deferMaybe(FatalError(message: "clients not mentioned in meta/global. Server wiped?"))
default:
return deferMaybe(SyncStatus.notStarted(reason))
}
}
let keys = self.scratchpad.keys?.value
let encoder = RecordEncoder<ClientPayload>(decode: { ClientPayload($0) }, encode: { $0.json })
let encrypter = keys?.encrypter(self.collection, encoder: encoder)
if encrypter == nil {
log.error("Couldn't make clients encrypter.")
return deferMaybe(FatalError(message: "Couldn't make clients encrypter."))
}
let clientsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter!)
// TODO: some of the commands we process might involve wiping collections or the
// entire profile. We should model this as an explicit status, and return it here
// instead of .completed.
statsSession.start()
// XXX: This is terrible. We always force a re-sync of the clients to work around
// the fact that `fxaDeviceId` may not have been populated if the list of clients
// hadn't changed since before the update to v8.0. To force a re-sync, we get all
// clients since the beginning of time instead of looking at `self.lastFetched`.
return clientsClient.getSince(0)
>>== { response in
return self.maybeDeleteClients(response: response, withServer: storageClient)
>>> { self.wipeIfNecessary(localClients)
>>> { self.applyStorageResponse(response, toLocalClients: localClients, withServer: clientsClient) }
}
}
>>> { deferMaybe(self.completedWithStats) }
}
private func maybeDeleteClients(response: StorageResponse<[Record<ClientPayload>]>, withServer storageClient: Sync15StorageClient) -> Success {
let hasOldClientId = response.value.contains { $0.id == self.scratchpad.clientGUID }
self.clientGuidIsMigrated = false
if hasOldClientId {
// Here we are deleting the old client record with the client GUID as the sync ID record. If the browser schema,
// needs to be reverted from version 41, the client record with an FxA device ID as the record ID will need to
// be deleted in a similar manner.
return storageClient.deleteObject(collection: "clients", guid: self.scratchpad.clientGUID).bind { result in
if result.isSuccess {
self.clientGuidIsMigrated = true
return succeed()
} else {
if let error = result.failureValue {
log.debug("Unable to delete records from client engine")
return deferMaybe(error as MaybeErrorType)
} else {
log.debug("Unable to delete records from client engine with unknown error")
return deferMaybe(UnknownError() as MaybeErrorType)
}
}
}
}
return succeed()
}
public static func resetClientsWithStorage(_ storage: ResettableSyncStorage, basePrefs: Prefs) -> Success {
let clientPrefs = BaseCollectionSynchronizer.prefsForCollection("clients", withBasePrefs: basePrefs)
clientPrefs.removeObjectForKey("lastFetched")
return storage.resetClient()
}
}
| mpl-2.0 | c1c98be03b32f862656c7196097d00c7 | 41.145374 | 200 | 0.605885 | 5.385308 | false | false | false | false |
benlangmuir/swift | validation-test/stdlib/StringBreadcrumbs.swift | 9 | 3650 | // RUN: %target-run-stdlib-swift
// REQUIRES: executable_test,optimized_stdlib
// UNSUPPORTED: freestanding
// Some targeted tests for the breadcrumbs path. There is some overlap with
// UTF16View tests for huge strings, but we want a simpler suite that targets
// some corner cases specifically.
import Swift
import StdlibUnittest
let smallASCII = "abcdefg"
let smallUnicode = "abéÏ𓀀"
let largeASCII = "012345678901234567890"
let largeUnicode = "abéÏ012345678901234567890𓀀"
let emoji = "😀😃🤢🤮👩🏿🎤🧛🏻♂️🧛🏻♂️👩👩👦👦"
let chinese = "Swift 是面向 Apple 平台的编程语言,功能强大且直观易用,而本次更新对其进行了全面优化。"
let nonBMP = String(repeating: "𓀀", count: 1 + (64 / 2))
let largeString: String = {
var result = ""
result += smallASCII
result += smallUnicode
result += largeASCII
result += chinese
result += largeUnicode
result += emoji
result += smallASCII
result += result.reversed()
return result
}()
extension FixedWidthInteger {
var hexStr: String { return "0x\(String(self, radix: 16, uppercase: true))" }
}
let StringBreadcrumbsTests = TestSuite("StringBreadcrumbsTests")
func validateBreadcrumbs(_ str: String) {
var utf16CodeUnits = Array(str.utf16)
var outputBuffer = Array<UInt16>(repeating: 0, count: utf16CodeUnits.count)
// Include the endIndex, so we can test end conversions
var utf16Indices = Array(str.utf16.indices) + [str.utf16.endIndex]
for i in 0...utf16CodeUnits.count {
for j in i...utf16CodeUnits.count {
let range = Range(uncheckedBounds: (i, j))
let indexRange = str._toUTF16Indices(range)
// Range<String.Index> <=> Range<Int>
expectEqual(utf16Indices[i], indexRange.lowerBound)
expectEqual(utf16Indices[j], indexRange.upperBound)
expectEqualSequence(
utf16CodeUnits[i..<j], str.utf16[indexRange])
let roundTripOffsets = str._toUTF16Offsets(indexRange)
expectEqualSequence(range, roundTripOffsets)
// Single Int <=> String.Index
expectEqual(indexRange.lowerBound, str._toUTF16Index(i))
expectEqual(indexRange.upperBound, str._toUTF16Index(j))
expectEqual(i, str._toUTF16Offset(indexRange.lowerBound))
expectEqual(j, str._toUTF16Offset(indexRange.upperBound))
// Copy characters
outputBuffer.withUnsafeMutableBufferPointer {
str._copyUTF16CodeUnits(into: $0, range: range)
}
expectEqualSequence(utf16CodeUnits[i..<j], outputBuffer[..<range.count])
}
}
}
StringBreadcrumbsTests.test("uniform strings") {
validateBreadcrumbs(smallASCII)
validateBreadcrumbs(largeASCII)
validateBreadcrumbs(smallUnicode)
validateBreadcrumbs(largeUnicode)
}
StringBreadcrumbsTests.test("largeString") {
validateBreadcrumbs(largeString)
}
// Test various boundary conditions with surrogate pairs aligning or not
// aligning
StringBreadcrumbsTests.test("surrogates-heavy") {
// Mis-align the hieroglyphics by 1,2,3 UTF-8 and UTF-16 code units
validateBreadcrumbs(nonBMP)
validateBreadcrumbs("a" + nonBMP)
validateBreadcrumbs("ab" + nonBMP)
validateBreadcrumbs("abc" + nonBMP)
validateBreadcrumbs("é" + nonBMP)
validateBreadcrumbs("是" + nonBMP)
validateBreadcrumbs("aé" + nonBMP)
}
// Test bread-crumb invalidation
StringBreadcrumbsTests.test("stale breadcrumbs") {
var str = nonBMP + "𓀀"
let oldLen = str.utf16.count
str.removeLast()
expectEqual(oldLen - 2, str.utf16.count)
str += "a"
expectEqual(oldLen - 1, str.utf16.count)
str += "𓀀"
expectEqual(oldLen + 1, str.utf16.count)
}
runAllTests()
| apache-2.0 | 195d235769bfbac43564bbd5a000760f | 29.347826 | 79 | 0.72149 | 4.034682 | false | true | false | false |
1271284056/JDPhotoBrowser | JDPhotoBrowser/Classes/JDPhotoBrowser.swift | 1 | 10722 | //
// JDPhotoBrowser
//
//
// Created by 张江东 on 17/3/3.
// Copyright © 2017年 58kuaipai. All rights reserved.
// 邮箱 [email protected] 简书 http://www.jianshu.com/u/5e7182f9e694
import UIKit
import Photos
let jdkresuId = "kJDPhotoBrowserId"
public class JDPhotoBrowser: UIViewController {
fileprivate let imageViewSpace: CGFloat = 25
var collectionView1: UICollectionView!
var imageRectDict: [IndexPath: CGRect] = [IndexPath: CGRect]()
var isViewAppeared: Bool = false
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isViewAppeared = true
}
enum imageSourceType {
case image
case url
case asserts
}
///图片的url字符串数组
var urls:[String]?
var images: [UIImage]?
var asserts: [PHAsset]?
//传回当前浏览器图片索引
public var endPageIndexClosure: (( _ index: Int)->())?
var imageSourceTp: imageSourceType = .image
var deleteButtonClosure: (( _ index: Int)->())? //点击删除按钮时index
private lazy var indexLabel = UILabel()
public var sourceImageView: UIImageView?{
didSet{
photoBrowserAnimator.sourceImageView = sourceImageView
photoBrowserAnimator.endImageView = sourceImageView
photoBrowserAnimator.superVc = self
}
} // 来源view
public var endImageView: UIImageView?{
didSet{
photoBrowserAnimator.endImageView = endImageView
}
} // 消失时候imageview
var lastPage: Int = 0
///静止后选中照片的索引
var currentPage : Int?{
didSet{
if self.imageSourceTp == .image {
guard let kcount = images?.count else { return }
indexLabel.text = "\((currentPage ?? 0) + 1)/\(kcount)"
}else if self.imageSourceTp == .url{
guard let kcount = urls?.count else { return }
indexLabel.text = "\((currentPage ?? 0) + 1)/\(kcount)"
}else if self.imageSourceTp == .asserts{
guard let kcount = asserts?.count else { return }
indexLabel.text = "\((currentPage ?? 0) + 1)/\(kcount)"
}
}
}
//1111 url
public init(selectIndex: Int, urls: [String]) {
super.init(nibName: nil, bundle: nil)
self.currentPage = selectIndex
self.urls = urls
self.imageSourceTp = .url
self.modalPresentationStyle = .custom
self.transitioningDelegate = photoBrowserAnimator
}
//2 image 第一个0
public init(selectIndex: Int, images: [UIImage]) {
super.init(nibName: nil, bundle: nil)
self.currentPage = selectIndex
self.images = images
self.imageSourceTp = .image
self.modalPresentationStyle = .custom
self.transitioningDelegate = photoBrowserAnimator
}
//3 相册
public init(selectIndex: Int, asserts: [PHAsset]) {
super.init(nibName: nil, bundle: nil)
self.currentPage = selectIndex
self.asserts = asserts
self.imageSourceTp = .asserts
self.modalPresentationStyle = .custom
self.transitioningDelegate = photoBrowserAnimator
}
private func setupCollectionView() {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width: kJDScreenWidth , height: kJDScreenHeight )
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = imageViewSpace
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, imageViewSpace)
var bounds = self.view.bounds
bounds.size.width += imageViewSpace
collectionView1 = UICollectionView(frame: bounds, collectionViewLayout: layout)
collectionView1.backgroundColor = UIColor.black
collectionView1.showsVerticalScrollIndicator = false
collectionView1.showsVerticalScrollIndicator = false
collectionView1.delegate = self
collectionView1.dataSource = self
collectionView1.register(JDPhotoBrowserCell.self, forCellWithReuseIdentifier: jdkresuId)
collectionView1.isPagingEnabled = true
collectionView1.showsHorizontalScrollIndicator = false
collectionView1.alwaysBounceHorizontal = true
collectionView1.contentOffset = CGPoint(x: collectionView1.bounds.size.width * CGFloat(currentPage!), y: 0)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black
self.setupCollectionView()
self.view.addSubview(collectionView1)
let indexPath = IndexPath(item: (currentPage ?? 0), section: 0)
DispatchQueue.main.async {
if indexPath.row <= ((self.images?.count ?? 1) - 1) || indexPath.row <= ((self.urls?.count ?? 1) - 1) || indexPath.row <= ((self.asserts?.count ?? 1) - 1){
self.collectionView1.scrollToItem(at: indexPath, at: .left, animated: false)
}
}
photoBrowserAnimator.currentPage = (currentPage ?? 0)
deleteBtn.frame = CGRect(x: kJDScreenWidth - 45, y: 30, width: 30, height: 30)
deleteBtn.setBackgroundImage(UIImage(named: "delete"), for: .normal)
// self.view.addSubview(deleteBtn)
// deleteBtn.addTarget(self, action: #selector(delete(btn:)), for: .touchUpInside)
self.view.addSubview(indexLabel)
indexLabel.backgroundColor = UIColor.black
indexLabel.textColor = UIColor.white
indexLabel.textAlignment = .center
indexLabel.frame = CGRect(x: 0, y: kJDScreenHeight - 40, width: 80, height: 30)
indexLabel.JDcenterX = kJDScreenWidth * 0.5
// saveBtn.frame = CGRect(x: kJDScreenWidth - 80, y: indexLabel.y, width: 50, height: 50)
// saveBtn.addTarget(self, action: #selector(saveImg), for: .touchUpInside)
// self.view.addSubview(saveBtn)
if self.imageSourceTp == .image{
guard let kcount = images?.count else { return }
indexLabel.text = "\((currentPage ?? 0) + 1)/\(kcount)"
}else if self.imageSourceTp == .url{
guard let kcount = urls?.count else { return }
indexLabel.text = "\((currentPage ?? 0) + 1)/\(kcount)"
}else if self.imageSourceTp == .asserts{
guard let kcount = asserts?.count else { return }
indexLabel.text = "\((currentPage ?? 0) + 1)/\(kcount)"
}
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//隐藏状态栏
let statusBar = UIApplication.shared.value(forKey: "statusBar")
(statusBar as! UIView).JDy = -UIApplication.shared.statusBarFrame.size.height
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
//恢复状态栏
let statusBar = UIApplication.shared.value(forKey: "statusBar")
(statusBar as! UIView).JDy = 0
}
//删除
@objc private func delete(btn: UIButton){
if deleteButtonClosure != nil {
deleteButtonClosure?((currentPage ?? 0))
}
}
//--------懒加载--------
fileprivate lazy var photoBrowserAnimator : JDPhotoBrowserAnimator = JDPhotoBrowserAnimator()
private lazy var deleteBtn : UIButton = {
let btn: UIButton = UIButton()
btn.setTitleColor(UIColor.red, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
return btn
}()
private lazy var saveBtn : UIButton = {
let btn: UIButton = UIButton()
btn.JDsize = CGSize(width: 50, height: 50)
btn.setBackGroundColor(color: UIColor.red, type: .normal)
btn.setTitleColor(UIColor.red, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
return btn
}()
// @objc private func saveImg(){
// let indexPath = IndexPath(item: (currentPage ?? 0), section: 0)
// let cell = self.collectionView.cellForItem(at: indexPath) as! JDPhotoBrowserCell
//
// self.saveImageToPhotoAlbum1(saveImage: cell.backImg.image!)
// }
//
// //保存照片
// func saveImageToPhotoAlbum1(saveImage: UIImage){
// UIImageWriteToSavedPhotosAlbum(saveImage, self, #selector(saveImageToo(image:didFinishSavingWithError:contextInfo:)), nil)
// }
//
// func saveImageToo(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
// if error != nil {
// return
// } else {
// }
//
//
// }
}
extension JDPhotoBrowser :UICollectionViewDelegate,UICollectionViewDataSource{
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if self.imageSourceTp == .image {
return (self.images?.count)!
}else if self.imageSourceTp == .url{
return (self.urls?.count)!
}else {
return (self.asserts?.count)!
}
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: jdkresuId, for: indexPath as IndexPath) as! JDPhotoBrowserCell
cell.scrollView.setZoomScale(1, animated: false)
if self.imageSourceTp == .image {
cell.image = self.images?[indexPath.item]
}else if self.imageSourceTp == .url{
cell.imageUrl = self.urls?[indexPath.item]
}else if self.imageSourceTp == .asserts{
cell.assert = self.asserts?[indexPath.item]
}
cell.cellPhotoBrowserAnimator = photoBrowserAnimator
return cell
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.dismiss(animated: true, completion: nil)
}
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
currentPage = Int(scrollView.contentOffset.x / scrollView.JDwidth)
lastPage = currentPage!
photoBrowserAnimator.currentPage = currentPage ?? 0
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView){
if self.endPageIndexClosure != nil {
endPageIndexClosure?(currentPage ?? 0)
}
}
}
| mit | 295f59a9f40257689b5c8cc5f9feaeef | 36.626335 | 167 | 0.631893 | 4.764759 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/SpeechToTextV1/WebSockets/SpeechToTextRecorder.swift | 1 | 6980 | /**
* Copyright IBM Corporation 2016
*
* 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.
**/
#if os(Linux)
#else
import Foundation
import AudioToolbox
import AVFoundation
internal class SpeechToTextRecorder {
// This implementation closely follows Apple's "Audio Queue Services Programming Guide".
// See the guide for more information about audio queues and recording.
internal var onMicrophoneData: ((Data) -> Void)? // callback to handle pcm buffer
internal var onPowerData: ((Float32) -> Void)? // callback for average dB power
internal let session = AVAudioSession.sharedInstance() // session for recording permission
internal var isRecording = false // state of recording
internal private(set) var format = AudioStreamBasicDescription() // audio data format specification
private var queue: AudioQueueRef? // opaque reference to an audio queue
private var powerTimer: Timer? // timer to invoke metering callback
private let callback: AudioQueueInputCallback = {
userData, queue, bufferRef, startTimeRef, numPackets, packetDescriptions in
// parse `userData` as `SpeechToTextRecorder`
guard let userData = userData else { return }
let audioRecorder = Unmanaged<SpeechToTextRecorder>.fromOpaque(userData).takeUnretainedValue()
// dereference pointers
let buffer = bufferRef.pointee
let startTime = startTimeRef.pointee
// calculate number of packets
var numPackets = numPackets
if numPackets == 0 && audioRecorder.format.mBytesPerPacket != 0 {
numPackets = buffer.mAudioDataByteSize / audioRecorder.format.mBytesPerPacket
}
// work with pcm data in an Autorelease Pool to make sure it is released in a timely manner
autoreleasepool {
// execute callback with audio data
let pcm = Data(bytes: buffer.mAudioData, count: Int(buffer.mAudioDataByteSize))
audioRecorder.onMicrophoneData?(pcm)
}
// return early if recording is stopped
guard audioRecorder.isRecording else {
return
}
// enqueue buffer
if let queue = audioRecorder.queue {
AudioQueueEnqueueBuffer(queue, bufferRef, 0, nil)
}
}
internal init() {
// define audio format
var formatFlags = AudioFormatFlags()
formatFlags |= kLinearPCMFormatFlagIsSignedInteger
formatFlags |= kLinearPCMFormatFlagIsPacked
format = AudioStreamBasicDescription(
mSampleRate: 16000.0,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: formatFlags,
mBytesPerPacket: UInt32(1*MemoryLayout<Int16>.stride),
mFramesPerPacket: 1,
mBytesPerFrame: UInt32(1*MemoryLayout<Int16>.stride),
mChannelsPerFrame: 1,
mBitsPerChannel: 16,
mReserved: 0
)
}
private func prepareToRecord() {
// create recording queue
let pointer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
AudioQueueNewInput(&format, callback, pointer, nil, nil, 0, &queue)
// ensure queue was set
guard let queue = queue else {
return
}
// update audio format
var formatSize = UInt32(MemoryLayout<AudioStreamBasicDescription>.stride)
AudioQueueGetProperty(queue, kAudioQueueProperty_StreamDescription, &format, &formatSize)
// allocate and enqueue buffers
let numBuffers = 5
let bufferSize = deriveBufferSize(seconds: 0.5)
for _ in 0..<numBuffers {
let bufferRef = UnsafeMutablePointer<AudioQueueBufferRef?>.allocate(capacity: 1)
AudioQueueAllocateBuffer(queue, bufferSize, bufferRef)
if let buffer = bufferRef.pointee {
AudioQueueEnqueueBuffer(queue, buffer, 0, nil)
}
}
// enable metering
var metering: UInt32 = 1
let meteringSize = UInt32(MemoryLayout<UInt32>.stride)
let meteringProperty = kAudioQueueProperty_EnableLevelMetering
AudioQueueSetProperty(queue, meteringProperty, &metering, meteringSize)
// set metering timer to invoke callback
powerTimer = Timer(
timeInterval: 0.025,
target: self,
selector: #selector(samplePower),
userInfo: nil,
repeats: true
)
RunLoop.current.add(powerTimer!, forMode: RunLoopMode.commonModes)
}
internal func startRecording() throws {
guard !isRecording else { return }
self.prepareToRecord()
self.isRecording = true
guard let queue = queue else { return }
AudioQueueStart(queue, nil)
}
internal func stopRecording() throws {
guard isRecording else { return }
guard let queue = queue else { return }
isRecording = false
powerTimer?.invalidate()
AudioQueueStop(queue, true)
AudioQueueDispose(queue, false)
}
private func deriveBufferSize(seconds: Float64) -> UInt32 {
guard let queue = queue else { return 0 }
let maxBufferSize = UInt32(0x50000)
var maxPacketSize = format.mBytesPerPacket
if maxPacketSize == 0 {
var maxVBRPacketSize = UInt32(MemoryLayout<UInt32>.stride)
AudioQueueGetProperty(
queue,
kAudioQueueProperty_MaximumOutputPacketSize,
&maxPacketSize,
&maxVBRPacketSize
)
}
let numBytesForTime = UInt32(format.mSampleRate * Float64(maxPacketSize) * seconds)
let bufferSize = (numBytesForTime < maxBufferSize ? numBytesForTime : maxBufferSize)
return bufferSize
}
@objc
private func samplePower() {
guard let queue = queue else { return }
var meters = [AudioQueueLevelMeterState(mAveragePower: 0, mPeakPower: 0)]
var metersSize = UInt32(meters.count * MemoryLayout<AudioQueueLevelMeterState>.stride)
let meteringProperty = kAudioQueueProperty_CurrentLevelMeterDB
let meterStatus = AudioQueueGetProperty(queue, meteringProperty, &meters, &metersSize)
guard meterStatus == 0 else { return }
onPowerData?(meters[0].mAveragePower)
}
}
#endif
| mit | 4a73eb49c6995fc491b2beadf50542da | 37.563536 | 106 | 0.647851 | 5.197319 | false | false | false | false |
WERUreo/werureo-slackbots | Sources/App/Models/Train.swift | 1 | 2905 | //
// Train.swift
// slack-commands
//
// Created by Keli'i Martin on 1/22/17.
//
//
import Foundation
import Vapor
import Fluent
public enum Direction: String
{
case northbound = "NB"
case southbound = "SB"
////////////////////////////////////////////////////////////
func toString() -> String
{
switch self
{
case .northbound:
return "northbound"
case .southbound:
return "southbound"
}
}
}
struct Train
{
////////////////////////////////////////////////////////////
// MARK: - Properties
////////////////////////////////////////////////////////////
var id: Node?
var exists: Bool = false
var number: Int
var direction: String
////////////////////////////////////////////////////////////
// MARK: - Initializers
////////////////////////////////////////////////////////////
init(number: Int, direction: Direction)
{
self.id = nil
self.number = number
self.direction = direction.rawValue
}
}
////////////////////////////////////////////////////////////
// MARK: - Model
////////////////////////////////////////////////////////////
extension Train : Model
{
init(node: Node, in context: Context) throws
{
self.id = try node.extract("id")
self.number = try node.extract("number")
self.direction = try node.extract("direction")
}
////////////////////////////////////////////////////////////
func makeNode(context: Context) throws -> Node
{
return try Node(node:
[
"id" : self.id,
"number" : self.number,
"direction" : self.direction
])
}
////////////////////////////////////////////////////////////
static func prepare(_ database: Database) throws
{
try database.create("trains")
{ trains in
trains.id()
trains.int("number")
trains.string("direction")
}
}
////////////////////////////////////////////////////////////
static func revert(_ database: Database) throws
{
try database.delete("trains")
}
}
////////////////////////////////////////////////////////////
// MARK: - Helpers
////////////////////////////////////////////////////////////
extension Train
{
static func northbound() throws -> [Train]
{
return try Train.query().filter("direction", "NB").all()
}
////////////////////////////////////////////////////////////
static func southbound() throws -> [Train]
{
return try Train.query().filter("direction", "SB").all()
}
////////////////////////////////////////////////////////////
func stations() throws -> [Station]
{
let stations: Siblings<Station> = try siblings()
return try stations.all()
}
}
| mit | 8db205f69eac90c007bf4c6fc136e80f | 22.055556 | 64 | 0.374871 | 5.47081 | false | false | false | false |
shuuchen/Swift-Down-Video | source/YoutubeViewController.swift | 1 | 12083 | //
// YoutubeViewController.swift
// table_template
//
// Created by Shuchen Du on 2015/09/26.
// Copyright (c) 2015年 Shuchen Du. All rights reserved.
//
import UIKit
class YoutubeViewController: UIViewController {
let myCell = "cell_id"
@IBOutlet weak var indicator: UIActivityIndicatorView!
var configuration: NSURLSessionConfiguration!
var session: NSURLSession!
var url: NSURL!
var selectedVideoIndex: Int!
var apiKey = "AIzaSyDqxwQmV1UcawuR6C4hWP5iBlZY7WqqHAI"
var videosArray: Array<Dictionary<NSObject, AnyObject>> = []
var videoDetailsArray: Array<Dictionary<NSObject, AnyObject>> = []
var allVideoIDs = ""
var refreshControl: UIRefreshControl!
var isRefreshing: Bool!
var pageToken: String?
var hasVideoDetail: Bool?
// youtube text field
@IBOutlet weak var yttf: UITextField!
@IBOutlet weak var videoTable: UITableView!
// perform request task
func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) {
let request = NSMutableURLRequest(URL: targetURL)
request.HTTPMethod = "GET"
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfiguration)
let task = session.dataTaskWithRequest(request, completionHandler: {
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(data: data,
HTTPStatusCode: (response as! NSHTTPURLResponse).statusCode, error: error)
})
})
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
self.indicator.hidden = true
refreshControl = UIRefreshControl()
refreshControl!.addTarget(self,
action: "handleRefresh:",
forControlEvents: .ValueChanged)
videoTable.addSubview(refreshControl!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// table view extension
extension YoutubeViewController: UITableViewDelegate, UITableViewDataSource {
// table refresh
func handleRefresh(paramSender: AnyObject) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC))
dispatch_after(popTime, dispatch_get_main_queue(), {
self.isRefreshing = true
self.getGeneralVideos(self.yttf.text)
self.refreshControl!.endRefreshing()
})
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let videoCount = self.videosArray.count
return videoCount
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell {
let cell = self.videoTable.dequeueReusableCellWithIdentifier(myCell,
forIndexPath: indexPath) as! MyCell
if videosArray.count > videoDetailsArray.count {
hasVideoDetail = false
} else {
hasVideoDetail = true
}
let videoDetails = videosArray[videosArray.count - indexPath.row - 1]
cell.duration.text = ""
if hasVideoDetail! {
let details = videoDetailsArray[videosArray.count - indexPath.row - 1]
let duration = details["duration"] as! String
cell.duration.text = formatDuration(duration)
}
cell.vidTitleLabel.text = videoDetails["title"] as? String
if let thumbnail = videoDetails["thumbnail"] as? String {
if let url = NSURL(string: thumbnail), data = NSData(contentsOfURL: url) {
cell.imgView.image = UIImage(data: data)
}
} else {
cell.imgView.image = UIImage(named: "no_image")
}
return cell
}
// cell segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let id = segue.identifier {
switch id {
case "seg_music":
let nvc = segue.destinationViewController as! UINavigationController
let dvc = nvc.childViewControllers[0] as! MusicViewController
let id = self.videoTable.indexPathForCell(sender as! MyCell)!
dvc.videoID = videosArray[videosArray.count - id.row - 1]["videoID"] as! String
dvc.videoNameText = videosArray[videosArray.count - id.row - 1]["title"] as? String
dvc.videoDuration = videoDetailsArray[videosArray.count - id.row - 1]["duration"] as! String
default:
break
}
}
}
}
// text field extension
extension YoutubeViewController: UITextFieldDelegate {
// get general videos
func getGeneralVideos(text: String) {
// Form the request URL string.
var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(text)&type=video&key=\(apiKey)"
// page token
if let _pageToken = self.pageToken, _isRefreshing = isRefreshing where _isRefreshing {
urlString = urlString.stringByAppendingString("&pageToken=\(_pageToken)" )
}
urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
// Create a NSURL object based on the above string.
let targetURL = NSURL(string: urlString)
// Get the results.
performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil {
// Convert the JSON data to a dictionary object.
let resultsDict = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! Dictionary<NSObject, AnyObject>
// Get all search result items ("items" array).
let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>
self.pageToken = resultsDict["nextPageToken"] as? String
// remove old data
if !self.isRefreshing {
self.videosArray.removeAll(keepCapacity: false)
}
// Loop through all search results and keep just the necessary data.
for var i=0; i<items.count; ++i {
let snippetDict = items[i]["snippet"] as! Dictionary<NSObject, AnyObject>
// Create a new dictionary to store the video details.
var videoDetailsDict = Dictionary<NSObject, AnyObject>()
videoDetailsDict["title"] = snippetDict["title"]
videoDetailsDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["default"] as! Dictionary<NSObject, AnyObject>)["url"]
videoDetailsDict["videoID"] = (items[i]["id"] as! Dictionary<NSObject, AnyObject>)["videoId"]
// Append the desiredPlaylistItemDataDict dictionary to the videos array.
self.videosArray.append(videoDetailsDict)
}
// get all video ids
for var i = 0; i < self.videosArray.count; i++ {
let str = self.videosArray[i]["videoID"] as! String
self.allVideoIDs = self.allVideoIDs.stringByAppendingString(str)
if i != self.videosArray.count - 1 {
self.allVideoIDs = self.allVideoIDs.stringByAppendingString(",")
}
}
self.getVideoDetails(self.allVideoIDs)
} else {
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading videos: \(error)")
if !self.isRefreshing {
self.indicator.stopAnimating()
self.indicator.hidden = true
}
}
})
}
// get video details
func getVideoDetails(videoID: String) {
// Form the request URL string.
var urlString = "https://www.googleapis.com/youtube/v3/videos?id=\(allVideoIDs)&part=contentDetails&key=\(apiKey)"
urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
// Create a NSURL object based on the above string.
let targetURL = NSURL(string: urlString)
// Get the results.
performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil {
// Convert the JSON data to a dictionary object.
let resultsDict = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! Dictionary<NSObject, AnyObject>
// Get all search result items ("items" array).
let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>
// remove old data
if !self.isRefreshing {
self.videoDetailsArray.removeAll(keepCapacity: false)
}
// Loop through all search results and keep just the necessary data.
for var i=0; i<items.count; ++i {
let detailsDict = items[i]["contentDetails"] as! Dictionary<NSObject, AnyObject>
// Create a new dictionary to store the video details.
var videoDetailsDict = Dictionary<NSObject, AnyObject>()
videoDetailsDict["duration"] = detailsDict["duration"]
videoDetailsDict["definition"] = detailsDict["definition"]
// Append the desiredPlaylistItemDataDict dictionary to the videos array.
self.videoDetailsArray.append(videoDetailsDict)
}
if !self.isRefreshing {
self.indicator.stopAnimating()
self.indicator.hidden = true
}
self.videoTable.reloadData()
} else {
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading details: \(error)")
if !self.isRefreshing {
self.indicator.stopAnimating()
self.indicator.hidden = true
}
}
})
}
// called when return is typed
func textFieldShouldReturn(textField: UITextField) -> Bool {
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
self.indicator.hidden = false
self.indicator.startAnimating()
self.yttf.resignFirstResponder()
self.isRefreshing = false
self.getGeneralVideos(textField.text)
return true
}
} | mit | a364f61da3beeb90a5698bd8f74b99e4 | 36.06135 | 171 | 0.551113 | 5.797025 | false | false | false | false |
karstengresch/rw_studies | SBLoader - Starter/SBLoader/TriangleLayer.swift | 1 | 3497 | //
// TriangleLayer.swift
// SBLoader
//
// Created by Satraj Bambra on 2015-03-19.
// Copyright (c) 2015 Satraj Bambra. All rights reserved.
//
import UIKit
class TriangleLayer: CAShapeLayer {
let innerPadding: CGFloat = 30.0
override init() {
super.init()
fillColor = Colors.red.CGColor
strokeColor = Colors.red.CGColor
lineWidth = 7.0
lineCap = kCALineCapRound
lineJoin = kCALineJoinRound
path = trianglePathSmall.CGPath
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var trianglePathSmall: UIBezierPath {
let trianglePath = UIBezierPath()
trianglePath.moveToPoint(CGPoint(x: 5.0 + innerPadding, y: 95.0))
trianglePath.addLineToPoint(CGPoint(x: 50.0, y: 12.5 + innerPadding))
trianglePath.addLineToPoint(CGPoint(x: 95.0 - innerPadding, y: 95.0))
trianglePath.closePath()
return trianglePath
}
var trianglePathLeftExtension: UIBezierPath {
let trianglePath = UIBezierPath()
trianglePath.moveToPoint(CGPoint(x: 5.0, y: 95.0))
trianglePath.addLineToPoint(CGPoint(x: 50.0, y: 12.5 + innerPadding))
trianglePath.addLineToPoint(CGPoint(x: 95.0 - innerPadding, y: 95.0))
trianglePath.closePath()
return trianglePath
}
var trianglePathRightExtension: UIBezierPath {
let trianglePath = UIBezierPath()
trianglePath.moveToPoint(CGPoint(x: 5.0, y: 95.0))
trianglePath.addLineToPoint(CGPoint(x: 50.0, y: 12.5 + innerPadding))
trianglePath.addLineToPoint(CGPoint(x: 95.0, y: 95.0))
trianglePath.closePath()
return trianglePath
}
var trianglePathTopExtension: UIBezierPath {
let trianglePath = UIBezierPath()
trianglePath.moveToPoint(CGPoint(x: 5.0, y: 95.0))
trianglePath.addLineToPoint(CGPoint(x: 50.0, y: 12.5))
trianglePath.addLineToPoint(CGPoint(x: 95.0, y: 95.0))
trianglePath.closePath()
return trianglePath
}
func animate() {
let triangleAnimationLeft: CABasicAnimation = CABasicAnimation(keyPath: "path")
triangleAnimationLeft.fromValue = trianglePathSmall.CGPath
triangleAnimationLeft.toValue = trianglePathLeftExtension.CGPath
triangleAnimationLeft.beginTime = 0.0
triangleAnimationLeft.duration = 0.3
let triangleAnimationRight: CABasicAnimation = CABasicAnimation(keyPath: "path")
triangleAnimationRight.fromValue = trianglePathLeftExtension.CGPath
triangleAnimationRight.toValue = trianglePathRightExtension.CGPath
triangleAnimationRight.beginTime = triangleAnimationLeft.beginTime + triangleAnimationLeft.duration
triangleAnimationRight.duration = 0.25
let triangleAnimationTop: CABasicAnimation = CABasicAnimation(keyPath: "path")
triangleAnimationTop.fromValue = trianglePathRightExtension.CGPath
triangleAnimationTop.toValue = trianglePathTopExtension.CGPath
triangleAnimationTop.beginTime = triangleAnimationRight.beginTime + triangleAnimationRight.duration
triangleAnimationTop.duration = 0.2
let triangleAnimationGroup: CAAnimationGroup = CAAnimationGroup()
triangleAnimationGroup.animations = [triangleAnimationLeft, triangleAnimationRight, triangleAnimationTop]
triangleAnimationGroup.duration = triangleAnimationTop.beginTime + triangleAnimationTop.duration
triangleAnimationGroup.fillMode = kCAFillModeForwards
triangleAnimationGroup.removedOnCompletion = false
addAnimation(triangleAnimationGroup, forKey: nil)
}
}
| unlicense | 80e35e86e79b73fa53bc763fe9d7f5a6 | 35.051546 | 109 | 0.745496 | 4.946252 | false | false | false | false |
jurezove/dynamic-uitableview-row-heights | DynamicTableRows/DynamicTableViewController.swift | 1 | 3676 | //
// DynamicTableViewController.swift
// DynamicTableRows
//
// Created by Jure Zove on 03/08/15.
// Copyright (c) 2015 Candy Code. All rights reserved.
//
import UIKit
class DynamicTableViewController: UITableViewController {
static let kTitleKey:String = "title"
static let kDateKey:String = "date"
static let kBodyKey:String = "body"
var data = [
[kDateKey: "Aug 15", kTitleKey: "Bacon", kBodyKey: "Bacon ipsum dolor amet ball tip doner boudin ribeye beef ribs venison pastrami prosciutto sirloin. Jerky ball tip ground round, pork belly doner ham hock picanha ribeye fatback tenderloin sirloin pig. Spare ribs kielbasa hamburger swine ground round landjaeger shank pig. Ham pig cupim tri-tip meatball jowl shoulder. Pork loin turkey short ribs, boudin beef ribs cow t-bone meatloaf bacon leberkas kevin swine sirloin ham hock. Shankle ham tenderloin tail biltong turkey brisket boudin spare ribs. Pork loin filet mignon ham hock shankle venison landjaeger drumstick."],
[kDateKey: "Aug 16", kTitleKey: "Meatball", kBodyKey: "Meatball filet mignon short ribs, landjaeger chuck flank kevin alcatra chicken ham hock salami biltong sirloin shankle. Flank tongue turducken, pig pork loin shankle sirloin fatback pork chop. Short ribs pork belly pork chop corned beef pork loin swine. Pork chop tail hamburger alcatra meatball t-bone turkey ribeye spare ribs prosciutto venison. Ham hock capicola strip steak landjaeger leberkas porchetta meatloaf boudin tail ground round t-bone pancetta frankfurter andouille. Brisket pig fatback pork belly capicola landjaeger rump chuck frankfurter hamburger biltong. Chicken biltong tongue jerky frankfurter short loin ribeye."],
[kDateKey: "Aug 17", kTitleKey: "Ribs", kBodyKey: "Spare ribs beef ribs tri-tip pastrami, tail kielbasa shoulder doner kevin jowl meatloaf ham hock shankle landjaeger. Venison kevin doner, kielbasa flank meatloaf boudin. Prosciutto rump kevin pancetta turkey bacon ground round beef ribs shank. Ham kevin ball tip shankle brisket fatback beef prosciutto beef ribs pig landjaeger short ribs tri-tip."],
[kDateKey: "Aug 18", kTitleKey: "Salami", kBodyKey: "Salami t-bone cow brisket tongue leberkas meatloaf pig meatball. Pork belly boudin capicola, short ribs meatball tri-tip pork chop biltong shoulder chicken rump fatback hamburger. Jerky flank swine, doner alcatra pork belly bacon andouille. Boudin shankle pork loin prosciutto shoulder turducken."]
]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 80
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.setNeedsLayout()
self.tableView.layoutIfNeeded()
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) // Status bar inset
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.data.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("DynamicCell", forIndexPath: indexPath) as! DynamicTableViewCell
var entry = self.data[indexPath.row]
cell.titleLabel.text = entry[DynamicTableViewController.kTitleKey]
cell.dateLabel.text = entry[DynamicTableViewController.kDateKey]
cell.bodyLabel.text = entry[DynamicTableViewController.kBodyKey]
return cell
}
}
| mit | dbb5321a5a742ce99a733562eb555014 | 64.642857 | 699 | 0.756801 | 4.309496 | false | false | false | false |
arvedviehweger/swift | test/decl/protocol/protocols.swift | 1 | 16895 | // RUN: %target-typecheck-verify-swift
protocol EmptyProtocol { }
protocol DefinitionsInProtocols {
init() {} // expected-error {{protocol initializers may not have bodies}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
// Protocol decl.
protocol Test {
func setTitle(_: String)
func erase() -> Bool
var creator: String { get }
var major : Int { get }
var minor : Int { get }
var subminor : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
static var staticProperty: Int // expected-error{{property in protocol must have explicit { get } or { get set } specifier}}
}
protocol Test2 {
var property: Int { get }
var title: String = "The Art of War" { get } // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
static var title2: String = "The Art of War" // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
associatedtype mytype
associatedtype mybadtype = Int
associatedtype V : Test = // expected-error {{expected type in associated type declaration}}
}
func test1() {
var v1: Test
var s: String
v1.setTitle(s)
v1.creator = "Me" // expected-error {{cannot assign to property: 'creator' is a get-only property}}
}
protocol Bogus : Int {} // expected-error{{inheritance from non-protocol, non-class type 'Int'}}
// Explicit conformance checks (successful).
protocol CustomStringConvertible { func print() } // expected-note{{protocol requires function 'print()' with type '() -> ()'}} expected-note{{protocol requires}} expected-note{{protocol requires}} expected-note{{protocol requires}}
struct TestFormat { }
protocol FormattedPrintable : CustomStringConvertible {
func print(format: TestFormat)
}
struct X0 : Any, CustomStringConvertible {
func print() {}
}
class X1 : Any, CustomStringConvertible {
func print() {}
}
enum X2 : Any { }
extension X2 : CustomStringConvertible {
func print() {}
}
// Explicit conformance checks (unsuccessful)
struct NotPrintableS : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableS' does not conform to protocol 'CustomStringConvertible'}}
class NotPrintableC : CustomStringConvertible, Any {} // expected-error{{type 'NotPrintableC' does not conform to protocol 'CustomStringConvertible'}}
enum NotPrintableO : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableO' does not conform to protocol 'CustomStringConvertible'}}
struct NotFormattedPrintable : FormattedPrintable { // expected-error{{type 'NotFormattedPrintable' does not conform to protocol 'CustomStringConvertible'}}
func print(format: TestFormat) {} // expected-note{{candidate has non-matching type '(TestFormat) -> ()'}}
}
// Circular protocols
protocol CircleMiddle : CircleStart { func circle_middle() } // expected-error 2 {{circular protocol inheritance CircleMiddle}}
// expected-error@-1{{circular protocol inheritance 'CircleMiddle' -> 'CircleStart' -> 'CircleEnd' -> 'CircleMiddle'}}
// expected-error @+1 {{circular protocol inheritance CircleStart}}
protocol CircleStart : CircleEnd { func circle_start() } // expected-error 2{{circular protocol inheritance CircleStart}}
// expected-note@-1{{protocol 'CircleStart' declared here}}
protocol CircleEnd : CircleMiddle { func circle_end()} // expected-note{{protocol 'CircleEnd' declared here}}
protocol CircleEntry : CircleTrivial { }
protocol CircleTrivial : CircleTrivial { } // expected-error 2{{circular protocol inheritance CircleTrivial}}
struct Circle {
func circle_start() {}
func circle_middle() {}
func circle_end() {}
}
func testCircular(_ circle: Circle) {
// FIXME: It would be nice if this failure were suppressed because the protocols
// have circular definitions.
_ = circle as CircleStart // expected-error{{'Circle' is not convertible to 'CircleStart'; did you mean to use 'as!' to force downcast?}} {{14-16=as!}}
}
// <rdar://problem/14750346>
protocol Q : C, H { }
protocol C : E { }
protocol H : E { }
protocol E { }
//===----------------------------------------------------------------------===//
// Associated types
//===----------------------------------------------------------------------===//
protocol SimpleAssoc {
associatedtype Associated // expected-note{{protocol requires nested type 'Associated'}}
}
struct IsSimpleAssoc : SimpleAssoc {
struct Associated {}
}
struct IsNotSimpleAssoc : SimpleAssoc {} // expected-error{{type 'IsNotSimpleAssoc' does not conform to protocol 'SimpleAssoc'}}
protocol StreamWithAssoc {
associatedtype Element
func get() -> Element // expected-note{{protocol requires function 'get()' with type '() -> NotAStreamType.Element'}}
}
struct AnRange<Int> : StreamWithAssoc {
typealias Element = Int
func get() -> Int {}
}
// Okay: Word is a typealias for Int
struct AWordStreamType : StreamWithAssoc {
typealias Element = Int
func get() -> Int {}
}
struct NotAStreamType : StreamWithAssoc { // expected-error{{type 'NotAStreamType' does not conform to protocol 'StreamWithAssoc'}}
typealias Element = Float
func get() -> Int {} // expected-note{{candidate has non-matching type '() -> Int'}}
}
// Okay: Infers Element == Int
struct StreamTypeWithInferredAssociatedTypes : StreamWithAssoc {
func get() -> Int {}
}
protocol SequenceViaStream {
associatedtype SequenceStreamTypeType : IteratorProtocol // expected-note{{protocol requires nested type 'SequenceStreamTypeType'}}
func makeIterator() -> SequenceStreamTypeType
}
struct IntIterator : IteratorProtocol /*, Sequence, ReplPrintable*/ {
typealias Element = Int
var min : Int
var max : Int
var stride : Int
mutating func next() -> Int? {
if min >= max { return .none }
let prev = min
min += stride
return prev
}
typealias Generator = IntIterator
func makeIterator() -> IntIterator {
return self
}
}
extension IntIterator : SequenceViaStream {
typealias SequenceStreamTypeType = IntIterator
}
struct NotSequence : SequenceViaStream { // expected-error{{type 'NotSequence' does not conform to protocol 'SequenceViaStream'}}
typealias SequenceStreamTypeType = Int // expected-note{{possibly intended match 'NotSequence.SequenceStreamTypeType' (aka 'Int') does not conform to 'IteratorProtocol'}}
func makeIterator() -> Int {}
}
protocol GetATuple {
associatedtype Tuple
func getATuple() -> Tuple
}
struct IntStringGetter : GetATuple {
typealias Tuple = (i: Int, s: String)
func getATuple() -> Tuple {}
}
//===----------------------------------------------------------------------===//
// Default arguments
//===----------------------------------------------------------------------===//
// FIXME: Actually make use of default arguments, check substitutions, etc.
protocol ProtoWithDefaultArg {
func increment(_ value: Int = 1) // expected-error{{default argument not permitted in a protocol method}}
}
struct HasNoDefaultArg : ProtoWithDefaultArg {
func increment(_: Int) {}
}
//===----------------------------------------------------------------------===//
// Variadic function requirements
//===----------------------------------------------------------------------===//
protocol IntMaxable {
func intmax(first: Int, rest: Int...) -> Int // expected-note 2{{protocol requires function 'intmax(first:rest:)' with type '(Int, Int...) -> Int'}}
}
struct HasIntMax : IntMaxable {
func intmax(first: Int, rest: Int...) -> Int {}
}
struct NotIntMax1 : IntMaxable { // expected-error{{type 'NotIntMax1' does not conform to protocol 'IntMaxable'}}
func intmax(first: Int, rest: [Int]) -> Int {} // expected-note{{candidate has non-matching type '(Int, [Int]) -> Int'}}
}
struct NotIntMax2 : IntMaxable { // expected-error{{type 'NotIntMax2' does not conform to protocol 'IntMaxable'}}
func intmax(first: Int, rest: Int) -> Int {} // expected-note{{candidate has non-matching type '(Int, Int) -> Int'}}
}
//===----------------------------------------------------------------------===//
// 'Self' type
//===----------------------------------------------------------------------===//
protocol IsEqualComparable {
func isEqual(other: Self) -> Bool // expected-note{{protocol requires function 'isEqual(other:)' with type '(WrongIsEqual) -> Bool'}}
}
struct HasIsEqual : IsEqualComparable {
func isEqual(other: HasIsEqual) -> Bool {}
}
struct WrongIsEqual : IsEqualComparable { // expected-error{{type 'WrongIsEqual' does not conform to protocol 'IsEqualComparable'}}
func isEqual(other: Int) -> Bool {} // expected-note{{candidate has non-matching type '(Int) -> Bool'}}
}
//===----------------------------------------------------------------------===//
// Using values of existential type.
//===----------------------------------------------------------------------===//
func existentialSequence(_ e: Sequence) { // expected-error{{has Self or associated type requirements}}
// FIXME: Weird diagnostic
var x = e.makeIterator() // expected-error{{'Sequence' is not convertible to 'Sequence.Iterator'}}
x.next()
x.nonexistent()
}
protocol HasSequenceAndStream {
associatedtype R : IteratorProtocol, Sequence
func getR() -> R
}
func existentialSequenceAndStreamType(_ h: HasSequenceAndStream) { // expected-error{{has Self or associated type requirements}}
// FIXME: Crummy diagnostics.
var x = h.getR() // expected-error{{member 'getR' cannot be used on value of protocol type 'HasSequenceAndStream'; use a generic constraint instead}}
x.makeIterator()
x.next()
x.nonexistent()
}
//===----------------------------------------------------------------------===//
// Subscripting
//===----------------------------------------------------------------------===//
protocol IntIntSubscriptable {
subscript (i: Int) -> Int { get }
}
protocol IntSubscriptable {
associatedtype Element
subscript (i: Int) -> Element { get }
}
struct DictionaryIntInt {
subscript (i: Int) -> Int {
get {
return i
}
}
}
func testSubscripting(_ iis: IntIntSubscriptable, i_s: IntSubscriptable) { // expected-error{{has Self or associated type requirements}}
var i: Int = iis[17]
var i2 = i_s[17] // expected-error{{member 'subscript' cannot be used on value of protocol type 'IntSubscriptable'; use a generic constraint instead}}
}
//===----------------------------------------------------------------------===//
// Static methods
//===----------------------------------------------------------------------===//
protocol StaticP {
static func f()
}
protocol InstanceP {
func f() // expected-note{{protocol requires function 'f()' with type '() -> ()'}}
}
struct StaticS1 : StaticP {
static func f() {}
}
struct StaticS2 : InstanceP { // expected-error{{type 'StaticS2' does not conform to protocol 'InstanceP'}}
static func f() {} // expected-note{{candidate operates on a type, not an instance as required}}
}
struct StaticAndInstanceS : InstanceP {
static func f() {}
func f() {}
}
func StaticProtocolFunc() {
let a: StaticP = StaticS1()
a.f() // expected-error{{static member 'f' cannot be used on instance of type 'StaticP'}}
}
func StaticProtocolGenericFunc<t : StaticP>(_: t) {
t.f()
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
protocol Eq {
static func ==(lhs: Self, rhs: Self) -> Bool
}
extension Int : Eq { }
// Matching prefix/postfix.
prefix operator <>
postfix operator <>
protocol IndexValue {
static prefix func <> (_ max: Self) -> Int
static postfix func <> (min: Self) -> Int
}
prefix func <> (max: Int) -> Int { return 0 }
postfix func <> (min: Int) -> Int { return 0 }
extension Int : IndexValue {}
//===----------------------------------------------------------------------===//
// Class protocols
//===----------------------------------------------------------------------===//
protocol IntrusiveListNode : class {
var next : Self { get }
}
final class ClassNode : IntrusiveListNode {
var next : ClassNode = ClassNode()
}
struct StructNode : IntrusiveListNode { // expected-error{{non-class type 'StructNode' cannot conform to class protocol 'IntrusiveListNode'}}
var next : StructNode // expected-error {{value type 'StructNode' cannot have a stored property that recursively contains it}}
}
final class ClassNodeByExtension { }
struct StructNodeByExtension { }
extension ClassNodeByExtension : IntrusiveListNode {
var next : ClassNodeByExtension {
get {
return self
}
set {}
}
}
extension StructNodeByExtension : IntrusiveListNode { // expected-error{{non-class type 'StructNodeByExtension' cannot conform to class protocol 'IntrusiveListNode'}}
var next : StructNodeByExtension {
get {
return self
}
set {}
}
}
final class GenericClassNode<T> : IntrusiveListNode {
var next : GenericClassNode<T> = GenericClassNode()
}
struct GenericStructNode<T> : IntrusiveListNode { // expected-error{{non-class type 'GenericStructNode<T>' cannot conform to class protocol 'IntrusiveListNode'}}
var next : GenericStructNode<T> // expected-error {{value type 'GenericStructNode<T>' cannot have a stored property that recursively contains it}}
}
// Refined protocols inherit class-ness
protocol IntrusiveDListNode : IntrusiveListNode {
var prev : Self { get }
}
final class ClassDNode : IntrusiveDListNode {
var prev : ClassDNode = ClassDNode()
var next : ClassDNode = ClassDNode()
}
struct StructDNode : IntrusiveDListNode { // expected-error{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveDListNode'}}
// expected-error@-1{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveListNode'}}
var prev : StructDNode // expected-error {{value type 'StructDNode' cannot have a stored property that recursively contains it}}
var next : StructDNode
}
@objc protocol ObjCProtocol {
func foo() // expected-note{{protocol requires function 'foo()' with type '() -> ()'}}
}
protocol NonObjCProtocol : class { //expected-note{{protocol 'NonObjCProtocol' declared here}}
func bar()
}
class DoesntConformToObjCProtocol : ObjCProtocol { // expected-error{{type 'DoesntConformToObjCProtocol' does not conform to protocol 'ObjCProtocol'}}
}
@objc protocol ObjCProtocolRefinement : ObjCProtocol { }
@objc protocol ObjCNonObjCProtocolRefinement : NonObjCProtocol { } //expected-error{{@objc protocol 'ObjCNonObjCProtocolRefinement' cannot refine non-@objc protocol 'NonObjCProtocol'}}
// <rdar://problem/16079878>
protocol P1 {
associatedtype Assoc // expected-note 2{{protocol requires nested type 'Assoc'}}
}
protocol P2 {
}
struct X3<T : P1> where T.Assoc : P2 {}
struct X4 : P1 { // expected-error{{type 'X4' does not conform to protocol 'P1'}}
func getX1() -> X3<X4> { return X3() }
}
protocol ShouldntCrash {
// rdar://16109996
let fullName: String { get } // expected-error {{'let' declarations cannot be computed properties}}
// <rdar://problem/17200672> Let in protocol causes unclear errors and crashes
let fullName2: String // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}}
// <rdar://problem/16789886> Assert on protocol property requirement without a type
var propertyWithoutType { get } // expected-error {{type annotation missing in pattern}}
// expected-error@-1 {{computed property must have an explicit type}} {{26-26=: <# Type #>}}
}
// rdar://problem/18168866
protocol FirstProtocol {
weak var delegate : SecondProtocol? { get } // expected-error{{'weak' may only be applied to class and class-bound protocol types, not 'SecondProtocol'}}
}
protocol SecondProtocol {
func aMethod(_ object : FirstProtocol)
}
// <rdar://problem/19495341> Can't upcast to parent types of type constraints without forcing
class C1 : P2 {}
func f<T : C1>(_ x : T) {
_ = x as P2
}
class C2 {}
func g<T : C2>(_ x : T) {
x as P2 // expected-error{{'T' is not convertible to 'P2'; did you mean to use 'as!' to force downcast?}} {{5-7=as!}}
}
class C3 : P1 {} // expected-error{{type 'C3' does not conform to protocol 'P1'}}
func h<T : C3>(_ x : T) {
_ = x as P1 // expected-error{{protocol 'P1' can only be used as a generic constraint because it has Self or associated type requirements}}
}
protocol P4 {
associatedtype T // expected-note {{protocol requires nested type 'T'}}
}
class C4 : P4 { // expected-error {{type 'C4' does not conform to protocol 'P4'}}
associatedtype T = Int // expected-error {{associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement}} {{3-17=typealias}}
}
| apache-2.0 | 19395fd9830046bee6110079309cf10d | 34.718816 | 232 | 0.651909 | 4.542888 | false | false | false | false |
theorix/Swift | AVFoundationQRcode/AVFoundationQRcode/ViewController.swift | 9 | 4041 | //
// ViewController.swift
// AVFoundationQRcode
//
// Created by Carlos Butron on 07/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// 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 AVFoundation
class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
@IBOutlet var previewView: UIView!
var previewLayer: AVCaptureVideoPreviewLayer!
var captureSession : AVCaptureSession!
var metadataOutput: AVCaptureMetadataOutput!
var videoDevice:AVCaptureDevice!
var videoInput: AVCaptureDeviceInput!
var running = false
var sendURL: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupCaptureSession()
previewLayer.frame = previewView.bounds
previewView.layer.addSublayer(previewLayer)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "startRunning:", name:UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "stopRunning:", name:UIApplicationDidEnterBackgroundNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startRunning(){
captureSession.startRunning()
metadataOutput.metadataObjectTypes =
metadataOutput.availableMetadataObjectTypes
running = true
}
func stopRunning(){
captureSession.stopRunning()
running = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.startRunning()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.stopRunning()
}
func setupCaptureSession(){
if(captureSession != nil){
return
}
videoDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
if(videoDevice == nil){
println("No camera on this device")
}
captureSession = AVCaptureSession()
videoInput = AVCaptureDeviceInput.deviceInputWithDevice(videoDevice, error: nil) as AVCaptureDeviceInput
if(captureSession.canAddInput(videoInput)){
captureSession.addInput(videoInput)
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
metadataOutput = AVCaptureMetadataOutput()
var metadataQueue = dispatch_queue_create("com.example.QRCode.metadata", nil)
metadataOutput.setMetadataObjectsDelegate(self, queue: metadataQueue)
if(captureSession.canAddOutput(metadataOutput)){
captureSession.addOutput(metadataOutput)
} }
func captureOutput(captureOutput: AVCaptureOutput!,
didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection
connection: AVCaptureConnection!) {
var elemento = metadataObjects.first as?
AVMetadataMachineReadableCodeObject
if(elemento != nil){
println(elemento!.stringValue)
sendURL = elemento!.stringValue
}
}
}
| gpl-3.0 | 6f8483a280856e977f442ab4b59acfbe | 35.405405 | 153 | 0.690671 | 5.907895 | false | false | false | false |
CPRTeam/CCIP-iOS | Pods/SwiftDate/Sources/SwiftDate/Supports/Commons.swift | 1 | 11175 | //
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import Foundation
// MARK: - Atomic Variable Support
@propertyWrapper
internal struct Atomic<Value> {
private let queue = DispatchQueue(label: "com.vadimbulavin.atomic")
private var value: Value
init(wrappedValue: Value) {
self.value = wrappedValue
}
var wrappedValue: Value {
get {
return queue.sync { value }
}
set {
queue.sync { value = newValue }
}
}
}
// MARK: - DateFormatter
public extension DateFormatter {
/// Return the local thread shared formatter initialized with the configuration of the region passed.
///
/// - Parameters:
/// - region: region used to pre-configure the cell.
/// - format: optional format used to set the `dateFormat` property.
/// - Returns: date formatter instance
static func sharedFormatter(forRegion region: Region?, format: String? = nil) -> DateFormatter {
let name = "SwiftDate_\(NSStringFromClass(DateFormatter.self))"
let formatter: DateFormatter = threadSharedObject(key: name, create: { return DateFormatter() })
if let region = region {
formatter.timeZone = region.timeZone
formatter.calendar = region.calendar
formatter.locale = region.locale
}
formatter.dateFormat = (format ?? DateFormats.iso8601)
return formatter
}
/// Returned number formatter instance shared along calling thread to format ordinal numbers.
///
/// - Parameter locale: locale to set
/// - Returns: number formatter instance
@available(iOS 9.0, macOS 10.11, *)
static func sharedOrdinalNumberFormatter(locale: LocaleConvertible) -> NumberFormatter {
var formatter: NumberFormatter?
let name = "SwiftDate_\(NSStringFromClass(NumberFormatter.self))"
formatter = threadSharedObject(key: name, create: { return NumberFormatter() })
formatter!.numberStyle = .ordinal
formatter!.locale = locale.toLocale()
return formatter!
}
}
/// This function create (if necessary) and return a thread singleton instance of the
/// object you want.
///
/// - Parameters:
/// - key: identifier of the object.
/// - create: create routine used the first time you are about to create the object in thread.
/// - Returns: instance of the object for caller's thread.
internal func threadSharedObject<T: AnyObject>(key: String, create: () -> T) -> T {
if let cachedObj = Thread.current.threadDictionary[key] as? T {
return cachedObj
} else {
let newObject = create()
Thread.current.threadDictionary[key] = newObject
return newObject
}
}
/// Style used to format month, weekday, quarter symbols.
/// Stand-alone properties are for use in places like calendar headers.
/// Non-stand-alone properties are for use in context (for example, “Saturday, November 12th”).
///
/// - `default`: Default formatter (ie. `4th quarter` for quarter, `April` for months and `Wednesday` for weekdays)
/// - defaultStandalone: See `default`; See `short`; stand-alone properties are for use in places like calendar headers.
/// - short: Short symbols (ie. `Jun` for months, `Fri` for weekdays, `Q1` for quarters).
/// - veryShort: Very short symbols (ie. `J` for months, `F` for weekdays, for quarter it just return `short` variant).
/// - standaloneShort: See `short`; stand-alone properties are for use in places like calendar headers.
/// - standaloneVeryShort: See `veryShort`; stand-alone properties are for use in places like calendar headers.
public enum SymbolFormatStyle {
case `default`
case defaultStandalone
case short
case veryShort
case standaloneShort
case standaloneVeryShort
}
/// Encapsulate the logic to use date format strings
public struct DateFormats {
/// This is the built-in list of all supported formats for auto-parsing of a string to a date.
internal static let builtInAutoFormat: [String] = [
DateFormats.iso8601,
"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ",
"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd",
"h:mm:ss A",
"h:mm A",
"MM/dd/yyyy",
"MMMM d, yyyy",
"MMMM d, yyyy LT",
"dddd, MMMM D, yyyy LT",
"yyyyyy-MM-dd",
"yyyy-MM-dd",
"yyyy-'W'ww-E",
"GGGG-'['W']'ww-E",
"yyyy-'W'ww",
"GGGG-'['W']'ww",
"yyyy'W'ww",
"yyyy-ddd",
"HH:mm:ss.SSSS",
"HH:mm:ss",
"HH:mm",
"HH"
]
/// This is the ordered list of all formats SwiftDate can use in order to attempt parsing a passaed
/// date expressed as string. Evaluation is made in order; you can add or remove new formats as you wish.
/// In order to reset the list call `resetAutoFormats()` function.
public static var autoFormats: [String] = DateFormats.builtInAutoFormat
/// Default ISO8601 format string
public static let iso8601: String = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
/// Extended format
public static let extended: String = "eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz"
/// The Alternative RSS formatted date "d MMM yyyy HH:mm:ss ZZZ" i.e. "09 Sep 2011 15:26:08 +0200"
public static let altRSS: String = "d MMM yyyy HH:mm:ss ZZZ"
/// The RSS formatted date "EEE, d MMM yyyy HH:mm:ss ZZZ" i.e. "Fri, 09 Sep 2011 15:26:08 +0200"
public static let rss: String = "EEE, d MMM yyyy HH:mm:ss ZZZ"
/// The http header formatted date "EEE, dd MMM yyyy HH:mm:ss zzz" i.e. "Tue, 15 Nov 1994 12:45:26 GMT"
public static let httpHeader: String = "EEE, dd MMM yyyy HH:mm:ss zzz"
/// A generic standard format date i.e. "EEE MMM dd HH:mm:ss Z yyyy"
public static let standard: String = "EEE MMM dd HH:mm:ss Z yyyy"
/// SQL date format
public static let sql: String = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
/// Reset the list of auto formats to the initial settings.
public static func resetAutoFormats() {
autoFormats = DateFormats.builtInAutoFormat
}
/// Parse a new string optionally passing the format in which is encoded. If no format is passed
/// an attempt is made by cycling all the formats set in `autoFormats` property.
///
/// - Parameters:
/// - string: date expressed as string.
/// - suggestedFormat: optional format of the date expressed by the string (set it if you can in order to optimize the parse task).
/// - region: region in which the date is expressed.
/// - Returns: parsed absolute `Date`, `nil` if parse fails.
public static func parse(string: String, format: String?, region: Region) -> Date? {
let formats = (format != nil ? [format!] : DateFormats.autoFormats)
return DateFormats.parse(string: string, formats: formats, region: region)
}
public static func parse(string: String, formats: [String], region: Region) -> Date? {
let formatter = DateFormatter.sharedFormatter(forRegion: region)
var parsedDate: Date?
for format in formats {
formatter.dateFormat = format
formatter.locale = region.locale
if let date = formatter.date(from: string) {
parsedDate = date
break
}
}
return parsedDate
}
}
// MARK: - Calendar Extension
public extension Calendar.Component {
internal static func toSet(_ src: [Calendar.Component]) -> Set<Calendar.Component> {
var l: Set<Calendar.Component> = []
src.forEach { l.insert($0) }
return l
}
internal var nsCalendarUnit: NSCalendar.Unit {
switch self {
case .era: return NSCalendar.Unit.era
case .year: return NSCalendar.Unit.year
case .month: return NSCalendar.Unit.month
case .day: return NSCalendar.Unit.day
case .hour: return NSCalendar.Unit.hour
case .minute: return NSCalendar.Unit.minute
case .second: return NSCalendar.Unit.second
case .weekday: return NSCalendar.Unit.weekday
case .weekdayOrdinal: return NSCalendar.Unit.weekdayOrdinal
case .quarter: return NSCalendar.Unit.quarter
case .weekOfMonth: return NSCalendar.Unit.weekOfMonth
case .weekOfYear: return NSCalendar.Unit.weekOfYear
case .yearForWeekOfYear: return NSCalendar.Unit.yearForWeekOfYear
case .nanosecond: return NSCalendar.Unit.nanosecond
case .calendar: return NSCalendar.Unit.calendar
case .timeZone: return NSCalendar.Unit.timeZone
@unknown default:
fatalError("Unsupported type \(self)")
}
}
}
/// Rounding mode for dates.
/// Round off/up (ceil) or down (floor) target date.
public enum RoundDateMode {
case to5Mins
case to10Mins
case to30Mins
case toMins(_: Int)
case toCeil5Mins
case toCeil10Mins
case toCeil30Mins
case toCeilMins(_: Int)
case toFloor5Mins
case toFloor10Mins
case toFloor30Mins
case toFloorMins(_: Int)
}
/// Related type enum to get derivated date from a receiver date.
public enum DateRelatedType {
case startOfDay
case endOfDay
case startOfWeek
case endOfWeek
case startOfMonth
case endOfMonth
case tomorrow
case tomorrowAtStart
case yesterday
case yesterdayAtStart
case nearestMinute(minute: Int)
case nearestHour(hour :Int)
case nextWeekday(_: WeekDay)
case nextDSTDate
case prevMonth
case nextMonth
case prevWeek
case nextWeek
case nextYear
case prevYear
case nextDSTTransition
}
public struct TimeCalculationOptions {
/// Specifies the technique the search algorithm uses to find result
public var matchingPolicy: Calendar.MatchingPolicy
/// Specifies the behavior when multiple matches are found
public var repeatedTimePolicy: Calendar.RepeatedTimePolicy
/// Specifies the direction in time to search
public var direction: Calendar.SearchDirection
public init(matching: Calendar.MatchingPolicy = .nextTime,
timePolicy: Calendar.RepeatedTimePolicy = .first,
direction: Calendar.SearchDirection = .forward) {
self.matchingPolicy = matching
self.repeatedTimePolicy = timePolicy
self.direction = direction
}
}
// MARK: - compactMap for Swift 4.0 (not necessary > 4.0)
#if swift(>=4.1)
#else
extension Collection {
func compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
return try flatMap(transform)
}
}
#endif
// MARK: - Foundation Bundle
private class BundleFinder {}
extension Foundation.Bundle {
/// Returns the resource bundle associated with the current Swift module.
/// This is used instead of `module` to allows compatibility outside the SwiftPM environment (ie. CocoaPods).
static var appModule: Bundle? = {
let bundleName = "SwiftDate_SwiftDate"
let candidates = [
// Bundle should be present here when the package is linked into an App.
Bundle.main.resourceURL,
// Bundle should be present here when the package is linked into a framework.
Bundle(for: BundleFinder.self).resourceURL,
// For command-line tools.
Bundle.main.bundleURL,
]
for candidate in candidates {
let bundlePath = candidate?.appendingPathComponent(bundleName + ".bundle")
if let bundle = bundlePath.flatMap(Bundle.init(url:)) {
return bundle
}
}
return nil
}()
}
| gpl-3.0 | 7bfc5414daba0f0f80a16c78ee5bec00 | 31.47093 | 134 | 0.705461 | 3.719614 | false | false | false | false |
PureSwift/BlueZ | Sources/BluetoothLinux/HCI.swift | 2 | 9875 | //
// HCI.swift
// BluetoothLinux
//
// Created by Alsey Coleman Miller on 3/1/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if os(Linux)
import Glibc
#elseif os(macOS) || os(iOS)
import Darwin.C
#endif
import Bluetooth
import CSwiftBluetoothLinux
public extension HCI {
// MARK: - Typealiases
public typealias DeviceFlag = HCIDeviceFlag
public typealias DeviceEvent = HCIDeviceEvent
public typealias ControllerType = HCIControllerType
public typealias BusType = HCIBusType
public typealias IOCTL = HCIIOCTL
}
/// HCI device flags
public enum HCIDeviceFlag: CInt {
case up
case initialized
case running
case passiveScan
case interactiveScan
case authenticated
case encrypt
case inquiry
case raw
public init() { self = .up }
}
/// HCI controller types
public enum HCIControllerType: UInt8 {
case BREDR = 0x00
case AMP = 0x01
}
/// HCI bus types
public enum HCIBusType: CInt {
case Virtual
case USB
case PCCard
case UART
case RS232
case PCI
case SDIO
}
/// HCI dev events
public enum HCIDeviceEvent: CInt {
case Register = 1
case Unregister
case Up
case Down
case Suspend
case Resume
}
/// HCI Packet types
public enum HCIPacketType: UInt8 {
case Command = 0x01
case ACL = 0x02
case SCO = 0x03
case Event = 0x04
case Vendor = 0xff
}
/// HCI Socket Option
public enum HCISocketOption: CInt {
case DataDirection = 1
case Filter = 2
case TimeStamp = 3
}
/// HCI `ioctl()` defines
public struct HCIIOCTL {
private static let H = CInt(UnicodeScalar(unicodeScalarLiteral: "H").value)
/// #define HCIDEVUP _IOW('H', 201, int)
public static let DeviceUp = IOC.IOW(H, 201, CInt.self)
/// #define HCIDEVDOWN _IOW('H', 202, int)
public static let DeviceDown = IOC.IOW(H, 202, CInt.self)
/// #define HCIDEVRESET _IOW('H', 203, int)
public static let DeviceReset = IOC.IOW(H, 203, CInt.self)
/// #define HCIDEVRESTAT _IOW('H', 204, int)
public static let DeviceRestat = IOC.IOW(H, 204, CInt.self)
/// #define HCIGETDEVLIST _IOR('H', 210, int)
public static let GetDeviceList = IOC.IOR(H, 210, CInt.self)
/// #define HCIGETDEVINFO _IOR('H', 211, int)
public static let GetDeviceInfo = IOC.IOR(H, 211, CInt.self)
// TODO: All HCI ioctl defines
/// #define HCIINQUIRY _IOR('H', 240, int)
public static let Inquiry = IOC.IOR(H, 240, CInt.self)
}
// MARK: - Internal Supporting Types
internal struct HCISocketAddress {
var family = sa_family_t()
var deviceIdentifier: UInt16 = 0
var channel: UInt16 = 0
init() { }
}
/* Ioctl requests structures */
/// `hci_dev_req`
internal struct HCIDeviceListItem {
/// uint16_t dev_id;
var identifier: UInt16 = 0
/// uint32_t dev_opt;
var options: UInt32 = 0
init() { }
}
/// `hci_dev_list_req`
internal struct HCIDeviceList {
typealias Item = HCIDeviceListItem
static var maximumCount: Int {
return HCI.maximumDeviceCount
}
/// uint16_t dev_num;
var numberOfDevices: UInt16 = 0
/// struct hci_dev_req dev_req[0]; /* hci_dev_req structures */
/// 16 elements
var list: (HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem, HCIDeviceListItem) = (HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem(), HCIDeviceListItem())
init() { }
subscript (index: Int) -> HCIDeviceListItem {
assert(index < type(of: self).maximumCount, "The request can only contain up to \(type(of: self).maximumCount) devices")
switch index {
case 0: return list.0
case 1: return list.1
case 2: return list.2
case 3: return list.3
case 4: return list.4
case 5: return list.5
case 6: return list.6
case 7: return list.7
case 8: return list.8
case 9: return list.9
case 10: return list.10
case 11: return list.11
case 12: return list.12
case 13: return list.13
case 14: return list.14
case 15: return list.15
default: fatalError("Invalid index \(index)")
}
}
}
extension HCIDeviceList: Collection {
public var count: Int {
return Int(numberOfDevices)
}
/// The start `Index`.
public var startIndex: Int {
return 0
}
/// The end `Index`.
///
/// This is the "one-past-the-end" position, and will always be equal to the `count`.
public var endIndex: Int {
return count
}
public func index(before i: Int) -> Int {
return i - 1
}
public func index(after i: Int) -> Int {
return i + 1
}
}
extension HCIDeviceList: RandomAccessCollection {
public subscript(bounds: Range<Int>) -> Slice<HCIDeviceList> {
return Slice<HCIDeviceList>(base: self, bounds: bounds)
}
public func makeIterator() -> IndexingIterator<HCIDeviceList> {
return IndexingIterator(_elements: self)
}
}
/// `hci_inquiry_req`
internal struct HCIInquiryRequest {
/// uint16_t dev_id;
var identifier: UInt16 = 0
/// uint16_t flags;
var flags: UInt16 = 0
/// uint8_t lap[3];
var lap: (UInt8, UInt8, UInt8) = (0,0,0)
/// uint8_t length;
var length: UInt8 = 0
/// uint8_t num_rsp;
var responseCount: UInt8 = 0
init() { }
}
/// `hci_dev_info`
internal struct HCIDeviceInformation {
/// uint16_t dev_id;
var identifier: UInt16 = 0
/// char name[8];
var name: (CChar, CChar, CChar, CChar, CChar, CChar, CChar, CChar) = (0, 0, 0, 0, 0, 0, 0, 0)
/// bdaddr_t bdaddr;
var address: BluetoothAddress = BluetoothAddress()
/// uint32_t flags;
var flags: UInt32 = 0
/// uint8_t type;
var type: UInt8 = 0
/// uint8_t features[8];
var features: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) = (0, 0, 0, 0, 0, 0, 0, 0)
/// uint32_t pkt_type;
var packetType: UInt32 = 0
/// uint32_t link_policy;
var linkPolicy: UInt32 = 0
/// uint32_t link_mode;
var linkMode: UInt32 = 0
/// uint16_t acl_mtu;
var ACLMaximumTransmissionUnit: UInt16 = 0
/// uint16_t acl_pkts;
var ACLPacketSize: UInt16 = 0
/// uint16_t sco_mtu;
var SCOMaximumTransmissionUnit: UInt16 = 0
/// uint16_t sco_pkts;
var SCOPacketSize: UInt16 = 0
/// struct hci_dev_stats stat;
var stat: HCIDeviceStats = HCIDeviceStats()
init() { }
}
internal struct HCIDeviceStats {
/// uint32_t err_rx;
var errorRX: UInt32 = 0
/// uint32_t err_tx;
var errorTX: UInt32 = 0
/// uint32_t cmd_tx;
var commandTX: UInt32 = 0
/// uint32_t evt_rx;
var eventRX: UInt32 = 0
/// uint32_t acl_tx;
var ALC_TX: UInt32 = 0
/// uint32_t acl_rx;
var ALC_RX: UInt32 = 0
/// uint32_t sco_tx;
var SCO_TX: UInt32 = 0
/// uint32_t sco_rx;
var SCO_RX: UInt32 = 0
/// uint32_t byte_rx;
var byteRX: UInt32 = 0
/// uint32_t byte_tx;
var byteTX: UInt32 = 0
init() { }
}
internal struct HCIFilter {
internal struct Bits {
static let FilterType = CInt(31)
static let Event = CInt(63)
static let OpcodeGroupField = CInt(63)
static let OpcodeCommandField = CInt(127)
}
var typeMask: UInt32 = 0
var eventMask: (UInt32, UInt32) = (0, 0)
var opcode: UInt16 = 0
init() { clear() }
@inline(__always)
mutating func clear() {
memset(&self, 0, MemoryLayout<HCIFilter>.size)
}
@inline(__always)
mutating func setPacketType(_ type: HCIPacketType) {
let bit = type == .Vendor ? 0 : CInt(type.rawValue) & HCIFilter.Bits.FilterType
HCISetBit(bit, &typeMask)
}
@inline(__always)
mutating func setEvent(_ event: UInt8) {
let bit = (CInt(event) & HCIFilter.Bits.Event)
HCISetBit(bit, &eventMask.0)
}
@inline(__always)
mutating func setEvent<T: HCIEvent>(_ event: T) {
setEvent(event.rawValue)
}
@inline(__always)
mutating func setEvent(_ event1: UInt8, _ event2: UInt8, _ event3: UInt8, _ event4: UInt8) {
eventMask.0 = 0
eventMask.0 += UInt32(event4) << 0o30
eventMask.0 += UInt32(event3) << 0o20
eventMask.0 += UInt32(event2) << 0o10
eventMask.0 += UInt32(event1) << 0o00
}
}
| mit | 0718f2b8235d82709ce2f0a269402265 | 23.562189 | 657 | 0.562791 | 4.00081 | false | false | false | false |
1457792186/JWSwift | SwiftLearn/SwiftLearning/SwiftLearning/Learning/集合类型/DataSetClass.swift | 1 | 10023 | //
// DataSetClass.swift
// JSwiftLearnMore
//
// Created by apple on 17/3/8.
// Copyright © 2017年 BP. All rights reserved.
//
import UIKit
class DataSetClass: NSObject {
func show() {
/*
Swift提供了三种集合类型:数组Array、集合Set、字典Dictionary。和ObjC不同的是,由于Swift的强类型,集合中的元素必须是同一类型,而不能像ObjC一样可以存储任何对象类型,并且注意Swift中的集合是值类型而非引用类型(事实上包括String、结构体struct、枚举enum都是值类型)
*/
// MARK: - Array
//声明数组的时候必须确定其类型,下面使用[String]声明一个字符串数组([String]是Array<String>简单表达形式)
//var a:Array<String>=["hello","world"]
var arr:[String]=["hello","world"]
_ = arr[0] //访问数组元素
//下面创建一个Double类型的数组,这里没有使用字面量,当前是一个空数组,当然也可以写成var b:[Double]=[]
var arr_b=[Double]()
for i in arr{
print("arr i=\(i)")
}
//添加元素,Swift中可变类型不再由单独的一个类型来表示,统统使用Array,如果想声明为不可变数组只要使用let定义即可
arr.append("!")
arr+=["I" ,"am" ,"Kenshin"] //追加元素
print("arr.count=\(arr.count)") //结果:a.count=6
arr[3...5]=["I","Love","Swift"] //修改元素,但是注意无法用这种方式添加元素
//a[6]=["."]//这种方式是错误的
arr.insert("New", at: 5) //插入元素:hello world! I Love New Swift
arr.remove(at: 5) //删除指定元素
//使用全局enumerate函数遍历数据索引和元素
for (index,element) in arr.enumerated(){
print("index=\(index),element=\(element)")
}
//使用构造函数限制数组元素个数并且指定默认值,等价于var c=Array(count: 3, repeatedValue: 1),自动推断类型
var arrThreeValue = [Int](repeatElement(1, count: 3))
// MARK: - Set表示没有顺序的集合
//注意集合没有类似于数组的简化形式,例如不能写成var a:[String]=["hello","world"]
var set_a:Set<String>=["hello","world"]
var set_b:Set=[1,2] //类型推断:Set<Int>
set_a.insert("!") //注意这个插入不保证顺序
if !set_a.isEmpty { //判断是否为空
set_a.remove("!")
}
if !set_a.contains("!"){
set_a.insert("!")
}
// MARK: - Dictionary
/*
Dictionary字典同样是没有顺序的,并且在Swift中字典同样要在使用时明确具体的类型。和ObjC中一样,字典必须保证key是唯一的,而这一点就要求在Swift中key必须是可哈希的,不过幸运的是Swift中的基本类型(如Int、Float、Double、Bool、String)都是可哈希的,都可以作为key。
在Swift中集合的可变性不是像ObjC一样由单独的数据类型来控制的,而是通过变量和常量来控制,这一点和其他高级语言比较类似
*/
//通过字面量进行字典初始化,注意等价于var a:Dictionary<Int,String>=[200:"success",404:"not found"]
var dic_a:[Int:String]=[200:"success",404:"not found"]
var dic_b=[200:"success",404:"not found"] //不声明类型,根据值自动推断类型
_ = dic_a[200] //读取字典
dic_a[404]="can not found" //修改
dic_a[500]="internal server error" //添加
//a=[:] //设置为空字典,等价于:a=[Int:String]()
for code in dic_a.keys{
print("code=\(code)")
}
for description in dic_a.values{
print("description=\(description)")
}
for (code,description) in dic_a{
print("code=\(code),description=\(description)")
}
// MARK: - 元组(Tuple)
/*
在开发过程中有时候会希望临时组织一个数据类型,此时可以使用一个结构体或者类,但是由于这个类型并没有那么复杂,如果定义起来又比较麻烦,此时可以考虑使用元组
*/
var point=(x:50,y:100) //自动推断其类型:(Int,Int)
_ = point.x //可以用类似于结构体的方式直接访问元素,结果:50
_ = point.y //结果:100
_ = point.0 //也可以采用类似数组的方式使用下标访问,结果:50
_ = point.1 //结果:100
//元组也可以不指定元素名称,访问的时候只能使用下标
let frame:(Int,Int,Int,Float)=(0,0,100,100.0)
print(frame) //结果:(0, 0, 100, 100.0)
//注意下面的语句是错误的,如果指定了元组的类型则无法指定元素名称
//let frame:(Int,Int,Int,Int)=(x:0,y:0,width:100,height:100)
var size=(width:100,25) //仅仅给其中一个元素命名
_ = size.width //结果:100
_ = size.1 //结果:25
var httpStatus:(Int,String)=(200,"success") //元组的元素类型并不一定相同
var (status,description)=httpStatus //一次性赋值给多个变量,此时status=200,description="success"
//接收元组的其中一个值忽略另一个值使用"_"(注意在Swift中很多情况下使用_忽略某个值或变量)
var (sta,_)=httpStatus
print("sta=\(sta)") //结果:sta=200
/**
* 元组作为函数的参数或返回值,借助元组实现了函数的多个返回值
*/
func request()->(code:Int,description:String){
return (404,"not found")
}
var result=request()
_ = result.0 //结果:404
_ = result.1 //结果:not found
_ = result.code //结果:404
_ = result.description //结果:not found
// MARK: - 可选类型
/*
所谓可选类型就是一个变量或常量可能有值也可能没有值则设置为可选类型。在ObjC中如果一个对象类型没有赋值,则默认为nil,同时nil类型也只能作为对象类型的默认值,对于类似于Int等基本类型则对应0这样的默认值。由于Swift是强类型语言,如果在声明变量或常量时没有进行赋值,Swift并不会默认设置初值(这一点和其他高级语言不太一样,例如C#虽然也有可选类型,但是要求并没有那么严格)
*/
var x:Float? //使用?声明成一个可选类型,如果不赋值默认为nil
x=172.0
var y:Float=60.0
//var z=x+y //注意此句报错,因为Int和Int?根本就是两种不同的类型,在Swift中两种不同的类型不能运算(因为不会自动进行类型转化)
var z=x!+y //使用!进行强制解包
let age="29"
var ageInt = Int(age) //注意ageInt是Int可选类型而不是Int类型(因为String的toInt()方法并不能保证其一定能转化为Int类型)
/*
Swift中类似于Int和Int?并不是同一种类型,不能进行相关运算,如果要运算只能解包;
可选类型其本质就是此类型内部存储分为“Some”和“None”两个部分,如果有值则存储到“Some”中,没有值则为“None”(早期Playground中可以看到两个部分,如今已经取消显示Some等描述了),使用感叹号强制解包的过程就是取出“Some”部分;
既然可选类型有可能有值,也可能没有值那么往往有时候就需要判断。可以使用if直接判断一个可选类型是否为nil,这样一来就可以根据情况进行强制解包(从Some部分取出值的过程);另一个选择就是在判断的同时如果有值则将值赋值给一个临时变量或常量,否则不进入此条件语句,这个过程称之为“可选绑定”
*/
/*可选类型判断*/
var ageT="29"
var ageTInt = Int(ageT) //注意ageInt是Int可选类型而不是Int类型(因为String的toInt()方法并不能保证其一定能转化为Int类型)
if ageTInt==nil {
print("ageInt=nil")
}else{
print("ageInt=\(ageTInt!)") //注意这里使用感叹号!强制解析
}
/**
* 可选类型绑定
* 如果可选类型有值则将值赋值给一个临时变量或者常量(此时此变量或者常量接受的值已经不是可选类型),如果没有值则不执行此条件
*/
if let newAgeT=ageTInt{ //此时newAge可以定义成常量也可以定义成变量
print("newAge=\(newAgeT)") //注意这里并不需要对newAge强制解包
}else{
print("ageInt=nil")
}
/*
通过演示可以看出Swift中的可选绑定如果实际计算不得不进行强制解包,如果一个可选类型从第一次赋值之后就能保证有值那么使用时就不必进行强制解包了,这种情况下可以使用隐式可选解析类型(通过感叹号声明而不是问号)
*/
/*隐式解析可选类型
*/
var age1:Int!=0 //通过感叹号声明隐式解析可选类型,此后使用时虽然是可选类型但是不用强制解包
age1=29
var newAge1:Int=age1 //不用强制解包直接赋值给Int类型(程序会自动解包)
if var tempAge1=age1 {
print("tempAge=\(tempAge1)")
}else{
print("age=nil")
}
}
}
| apache-2.0 | 15ede110b090f91dcb98f67c87e9ddc1 | 31.39801 | 202 | 0.556818 | 3.118774 | false | false | false | false |
misaka14/WTBilibili | WTBilibili/Home-首页/Recommend-推荐/View/WTRecommendCell.swift | 2 | 1914 | //
// WTRecommendCell.swift
// WTBilibili
//
// Created by 无头骑士 GJ on 16/5/4.
// Copyright © 2016年 无头骑士 GJ. All rights reserved.
//
import UIKit
import SnapKit
enum TitleType: String {
case HOT = "热门推荐"
case Live = "正在直播"
case SomeDrama = "番剧推荐"
case Animation = "动画区"
case Music = "音乐区"
case Dance = "舞蹈区"
case Game = "游戏区"
case Kichiku = "鬼畜区"
case Science = "科学区"
case TVPlay = "电视剧更新"
case Movie = "电影区"
case Fashion = "时尚区"
}
class WTRecommendCell: UITableViewCell
{
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var videoListContentView: UIView!
weak var videoListView: WTVideoListCollectionView!
/// 推荐模型
var recommendItem: WTRecommendItem?{
didSet{
titleLabel.text = recommendItem?.title
videoListView.videos = recommendItem?.body
// switch recommendItem!.title {
// case .HOT:
// print("1")
// default:
// print("1")
// }
}
}
// MARK: 系统回调函数
override func awakeFromNib()
{
super.awakeFromNib()
// 设置UI
setupUI()
}
}
// MARK: - 自定义函数
extension WTRecommendCell
{
// MARK: 设置UI
private func setupUI()
{
// 1、添加子控件
let videoListView = WTVideoListCollectionView(frame: CGRectZero, collectionViewLayout: WTVideoListLayout())
videoListContentView.addSubview(videoListView)
self.videoListView = videoListView
// 2、布局子控件
videoListView.snp_makeConstraints { (make) in
make.edges.equalTo(EdgeInsetsMake(0, left: 0, bottom: 0, right: 0))
}
}
}
| apache-2.0 | cef6a75dd26db658164872a32d08ee8f | 20.8875 | 115 | 0.564249 | 3.979545 | false | false | false | false |
czgarrett/SwiftPlaygrounds | Generics.playground/Contents.swift | 1 | 1479 |
//class Foo {
// let barType: Bar.Type
//
// init(barType: Bar.Type) {
// self.barType = barType
// }
//
// func arrayOfOne() -> [Bar] {
// var result = Array<self.barType>()
// }
//}
//
//class Bar {
// var description: String {
// return "I'm a bar"
// }
//
//}
//
//class Pub: Bar {
// override var description: String {
// return "I'm a pub"
// }
//}
//
import Foundation
protocol OrderedSetType {
func typedArray<FilterType>() -> [FilterType]
}
extension NSOrderedSet: OrderedSetType {
func typedArray<FilterType>() -> [FilterType] {
var result: [FilterType] = []
print("Result type is \(type(of: result))")
for item in self.objectEnumerator() {
print("Item type is \(type(of: item))")
if let correctItem = item as? FilterType {
result.append(correctItem)
}
}
return result
}
}
extension Optional where Wrapped: OrderedSetType {
func typedArray<FilterType>() -> [FilterType] {
switch self {
case .none:
return Array<FilterType>()
case .some(let orderedSet):
return orderedSet.typedArray()
}
}
}
let setOfStrings = NSMutableOrderedSet()
setOfStrings.add("String one")
let array: [String] = setOfStrings.typedArray()
let types: [Any.Type] = [String.self, Int.self]
for type in types {
let array = Array<type(of: type).Type>()
}
| mit | 15503f197806fab11a942cf893aae388 | 20.75 | 54 | 0.563895 | 3.725441 | false | false | false | false |
domenicosolazzo/practice-swift | Views/TableViews/Interaction with CollectionViews/Interaction with CollectionViews/ViewController.swift | 1 | 3307 | //
// ViewController.swift
// Interaction with CollectionViews
//
// Created by Domenico Solazzo on 11/05/15.
// License MIT
//
import UIKit
class ViewController: UICollectionViewController {
let allImages = [
UIImage(named: "1"),
UIImage(named: "2"),
UIImage(named: "3")
]
func randomImage() -> UIImage{
let randomNumber = arc4random_uniform(UInt32(allImages.count))
let randomImage = allImages[Int(randomNumber)]
return randomImage!
}
override func viewDidLoad() {
super.viewDidLoad()
let pinch = UIPinchGestureRecognizer(target: self,
action: #selector(ViewController.handlePinches(_:)))
for recognizer in collectionView!.gestureRecognizers! as [UIGestureRecognizer]{
if recognizer is UIPinchGestureRecognizer{
recognizer.require(toFail: pinch)
}
}
collectionView!.addGestureRecognizer(pinch)
}
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
let nib = UINib(nibName: "MyCollectionViewCell", bundle: nil)
collectionView!.register(nib, forCellWithReuseIdentifier: "cell")
collectionView!.backgroundColor = UIColor.white
}
convenience required init?(coder aDecoder: NSCoder) {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumLineSpacing = 20
flowLayout.minimumInteritemSpacing = 10
flowLayout.itemSize = CGSize(width: 80, height: 120);
flowLayout.scrollDirection = .vertical
flowLayout.sectionInset =
UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
self.init(collectionViewLayout: flowLayout)
}
override func numberOfSections(
in collectionView: UICollectionView) -> Int {
/* Between 3 to 6 sections */
return Int(3 + arc4random_uniform(4))
}
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
/* Each section has between 10 to 15 cells */
return Int(10 + arc4random_uniform(6))
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
cell.imageViewBackgroundImage.image = randomImage()
cell.imageViewBackgroundImage.contentMode = .scaleAspectFit
return cell
}
func handlePinches(_ pinch: UIPinchGestureRecognizer){
let defaultLayoutItemSize = CGSize(width: 80, height: 120)
let layout = collectionView!.collectionViewLayout
as! UICollectionViewFlowLayout
layout.itemSize =
CGSize(width: defaultLayoutItemSize.width * pinch.scale,
height: defaultLayoutItemSize.height * pinch.scale)
layout.invalidateLayout()
}
}
| mit | eeb317c3950291d2b31dac30b15cf191 | 30.798077 | 87 | 0.616873 | 5.863475 | false | false | false | false |
RevenueCat/purchases-ios | Sources/Misc/Atomic.swift | 1 | 2527 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// Atomic.swift
//
// Created by Nacho Soto on 11/20/21.
import Foundation
/**
* A generic object that performs all write and read operations atomically.
* Use it to prevent data races when accessing an object.
*
* - Important: The closures aren't re-entrant.
* In other words, `Atomic` instances cannot be used from within the `modify` and `withValue` closures
*
* Usage:
* ```swift
* let foo = Atomic<MyClass>
*
* // read values
* foo.withValue {
* let currentBar = $0.bar
* let currentX = $0.x
* }
*
* // write value
* foo.modify {
* $0.bar = 2
* $0.x = "new X"
* }
* ```
*
* Or for single-line read/writes:
* ```swift
* let currentX = foo.value.x
* foo.value = MyClass()
* ```
**/
internal final class Atomic<T> {
private let lock: Lock
private var _value: T
var value: T {
get { withValue { $0 } }
set { modify { $0 = newValue } }
}
init(_ value: T) {
self._value = value
self.lock = Lock()
}
@discardableResult
func modify<Result>(_ action: (inout T) throws -> Result) rethrows -> Result {
return try lock.perform {
try action(&_value)
}
}
@discardableResult
func withValue<Result>(_ action: (T) throws -> Result) rethrows -> Result {
return try lock.perform {
try action(_value)
}
}
}
// Syntactic sugar that allows initializing an `Atomic` optional value by directly assigning `nil`,
// i.e.: `let foo: Atomic<Foo?> = nil` instead of the more indirect `let foo: Atomic<Foo?> = .init(nil)`
extension Atomic: ExpressibleByNilLiteral where T: OptionalType {
convenience init(nilLiteral: ()) {
self.init(.init(optional: nil))
}
}
// Syntactic sugar that allows initializing an `Atomic` `Bool` by directly assigning its value,
// i.e.: `let foo: Atomic<Bool> = false` instead of the more indirect `let foo: Atomic<Bool> = .init(false)`
extension Atomic: ExpressibleByBooleanLiteral where T == Bool {
convenience init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
// `@unchecked` because of the mutable `_value`, but it's thread-safety is guaranteed with `Lock`.
extension Atomic: @unchecked Sendable {}
| mit | 6dc2e041882e1b2d6c85b321ba65c601 | 24.785714 | 108 | 0.629996 | 3.760417 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/APIClients/CrashlyticsClient.swift | 1 | 3449 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import Foundation
typealias KeyTitle = String
extension KeyTitle {
static var error = "error"
static var occurred = "occurred"
static var resultString = "result string"
fileprivate static var userId = "user_id"
fileprivate static var errorAttributres = "attributes"
fileprivate static var developerDescription = "dev_description"
}
final class CrashlyticsClient {
static func start(with apiKey: String) {
Crashlytics.start(withAPIKey: apiKey)
Fabric.with([Crashlytics.self])
}
static func setupForUser(with toshiID: String) {
Crashlytics.sharedInstance().setUserIdentifier(toshiID)
}
}
final class CrashlyticsLogger {
private static func attributesWithUserID(from attributes: [KeyTitle: Any]?) -> [String: Any] {
var resultAttributes: [String: Any] = [KeyTitle.userId: Cereal.shared.address]
attributes?.forEach { key, value in resultAttributes[key] = value }
return resultAttributes
}
/// Logs the given string to Crashlytics + Answers with the given attributes
/// Useful for diagnosing problems and/or creating a breadcrumb trail of what the user was looking at.
///
/// - Parameters:
/// - string: The string to log.
/// - attributes: (optional) any additional attributes to log with the string
static func log(_ string: String, attributes: [KeyTitle: Any]? = nil) {
CLSLogv("%@", getVaList([string]))
let attributesToSend = attributesWithUserID(from: attributes)
Answers.logCustomEvent(withName: string, customAttributes: attributesToSend)
}
/// Creates a non-fatal error, which shows up in Crashlytics similar to a crash but is filtered differently..
///
/// - Parameters:
/// - description: The description of what happened to be logged in Crashlytics.
/// - error: (optional) Any associated NSError where you want to log domain, code, and LocalizedDescription.
/// - attributes: (optional) any additional attributes to log
static func nonFatal(_ description: String, error: NSError? = nil, attributes: [KeyTitle: Any]? = nil) {
let attributes = attributesWithUserID(from: attributes)
let error = NSError(domain: error?.domain ?? "com.toshi.customnonfatal",
code: error?.code ?? 0,
userInfo: [
KeyTitle.errorAttributres: attributes,
NSLocalizedDescriptionKey: error?.localizedDescription ?? "(none)",
KeyTitle.developerDescription: description
])
Crashlytics.sharedInstance().recordError(error)
}
}
| gpl-3.0 | 02066d7ca311875b9568bd4d875154bd | 40.554217 | 114 | 0.663091 | 4.864598 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/SecureChannel/SecureChannelRouter.swift | 1 | 5902 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import Localization
import PlatformKit
import RxSwift
import ToolKit
import UIComponentsKit
public protocol SecureChannelRouting {
func didScanPairingQRCode(msg: String)
func didReceiveSecureChannelCandidate(_ candidate: SecureChannelConnectionCandidate)
func didReceiveError(_ error: SecureChannelError)
}
final class SecureChannelRouter: SecureChannelRouting {
private typealias LocalizedString = LocalizationConstants.SecureChannel.Alert
private let service: SecureChannelAPI
private let topMostViewControllerProvider: TopMostViewControllerProviding
private let loadingViewPresenter: LoadingViewPresenting
private let alertViewPresenter: AlertViewPresenterAPI
private var disposeBag = DisposeBag()
private let store = SecureChannelCandidateStore()
private weak var nav: UINavigationController?
init(
service: SecureChannelAPI = resolve(),
loadingViewPresenter: LoadingViewPresenting = resolve(),
alertViewPresenter: AlertViewPresenterAPI = resolve(),
topMostViewControllerProvider: TopMostViewControllerProviding = resolve()
) {
self.service = service
self.loadingViewPresenter = loadingViewPresenter
self.alertViewPresenter = alertViewPresenter
self.topMostViewControllerProvider = topMostViewControllerProvider
NotificationCenter.when(.login) { [weak self] _ in
self?.didLogin()
}
}
private func didLogin() {
guard let candidate = store.retrieve() else {
return
}
didReceiveSecureChannelCandidate(candidate)
}
func didScanPairingQRCode(msg: String) {
service.onQRCodeScanned(msg: msg)
.subscribe()
.disposed(by: disposeBag)
}
private func didRejectSecureChannel(to details: SecureChannelConnectionDetails) {
service.didRejectSecureChannel(details: details)
.handleLoaderForLifecycle(loader: loadingViewPresenter)
.observe(on: MainScheduler.asyncInstance)
.subscribe(
onCompleted: { [weak self] in
self?.showResultScreen(state: .denied)
},
onError: { [weak self] _ in
self?.showResultScreen(state: .error)
}
)
.disposed(by: disposeBag)
}
private func didAcceptSecureChannel(to details: SecureChannelConnectionDetails) {
service
.didAcceptSecureChannel(details: details)
.handleLoaderForLifecycle(loader: loadingViewPresenter)
.observe(on: MainScheduler.asyncInstance)
.subscribe(
onCompleted: { [weak self] in
self?.showResultScreen(state: .approved)
},
onError: { [weak self] _ in
self?.showResultScreen(state: .error)
}
)
.disposed(by: disposeBag)
}
func didReceiveSecureChannelCandidate(_ candidate: SecureChannelConnectionCandidate) {
service.isReadyForSecureChannel()
.catchAndReturn(false)
.observe(on: MainScheduler.asyncInstance)
.subscribe(
onSuccess: { [weak self] isReadyForSecureChannel in
self?.didReceiveSecureChannelCandidate(candidate, isReadyForSecureChannel: isReadyForSecureChannel)
}
)
.disposed(by: disposeBag)
}
private func didReceiveSecureChannelCandidate(
_ candidate: SecureChannelConnectionCandidate,
isReadyForSecureChannel: Bool
) {
guard isReadyForSecureChannel else {
store.store(candidate)
showNeedLoginAlert()
return
}
guard nav == nil else {
return
}
showDetailsScreen(with: candidate)
}
func didReceiveError(_ error: SecureChannelError) {
alertViewPresenter.notify(
content: AlertViewContent(
title: LocalizedString.title,
message: error.errorDescription
),
in: nil
)
}
private func showNeedLoginAlert() {
alertViewPresenter.notify(
content: AlertViewContent(
title: LocalizedString.title,
message: LocalizedString.loginRequired
),
in: nil
)
}
private func showResultScreen(state: SecureChannelResultPresenter.State) {
let presenter = SecureChannelResultPresenter(state: state) { [weak self] in
self?.nav?.dismiss(animated: true)
}
let vc = PendingStateViewController(presenter: presenter)
nav?.pushViewController(vc, animated: true)
}
private func showDetailsScreen(with candidate: SecureChannelConnectionCandidate) {
let presenter = SecureChannelDetailsPresenter(
candidate: candidate,
didAcceptSecureChannel: { [weak self] didApproved in
if didApproved {
self?.didAcceptSecureChannel(to: candidate.details)
} else {
self?.didRejectSecureChannel(to: candidate.details)
}
}
)
let root = DetailsScreenViewController(presenter: presenter)
let nav = UINavigationController(rootViewController: root)
self.nav = nav
present(viewController: nav)
}
private func present(viewController: UIViewController) {
guard let topMostViewController = topMostViewControllerProvider.topMostViewController else {
return
}
let base = topMostViewController.presentedViewController ?? topMostViewController
base.present(viewController, animated: true, completion: nil)
}
}
| lgpl-3.0 | f2c08dcbeec763db46d954b910f053b7 | 33.91716 | 119 | 0.639214 | 6.052308 | false | false | false | false |
kevintavog/WatchThis | Source/WatchThis/ShowListWindow.swift | 1 | 1361 | //
//
import AppKit
import Foundation
import RangicCore
class ShowListWindow : NSWindow, NSDraggingDestination
{
func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation
{
Logger.info("Dragging entered")
return folderPaths(sender).count > 0 ? .copy : NSDragOperation()
}
func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation
{
return folderPaths(sender).count > 0 ? .copy : NSDragOperation()
}
func performDragOperation(_ sender: NSDraggingInfo) -> Bool
{
let folderList = folderPaths(sender)
Logger.info("Perform drag operation: \(folderList)")
return true
}
func folderPaths(_ dragInfo: NSDraggingInfo) -> [String]
{
var list = [String]()
if (dragInfo.draggingPasteboard.types?.contains(ShowListController.FilenamesPboardType) != nil) {
if let fileArray = dragInfo.draggingPasteboard.propertyList(forType: ShowListController.FilenamesPboardType) as? [String] {
for file in fileArray {
var isDirectory:ObjCBool = false
if FileManager.default.fileExists(atPath: file, isDirectory: &isDirectory) && isDirectory.boolValue {
list.append(file)
}
}
}
}
return list
}
}
| mit | 6c2c9634d458ded7efad8e21bbf39a90 | 28.586957 | 135 | 0.617928 | 5.097378 | false | false | false | false |
uasys/swift | test/refactoring/CollapseNestedIf/basic.swift | 5 | 1073 | func testCollapseNestedIf() {
let a = 3
if a > 2 {
if a < 10 {}
}
}
func testMultiConditionalNestedIf() {
let a = 3
if a > 2, a != 4 {
if a < 10, a != 5 {}
}
}
func testLetNestedIf() {
let a: Int? = 3
if let b = a {
if b != 5 {}
}
}
func testCaseLetNestedIf() {
let a: Int? = 3
if case .some(let b) = a {
if b != 5 {}
}
}
// RUN: rm -rf %t.result && mkdir -p %t.result
// RUN: %refactor -collapse-nested-if -source-filename %s -pos=3:3 > %t.result/L3-3.swift
// RUN: diff -u %S/Outputs/basic/L3-3.swift.expected %t.result/L3-3.swift
// RUN: %refactor -collapse-nested-if -source-filename %s -pos=9:3 > %t.result/L9-3.swift
// RUN: diff -u %S/Outputs/basic/L9-3.swift.expected %t.result/L9-3.swift
// RUN: %refactor -collapse-nested-if -source-filename %s -pos=15:3 > %t.result/L15-3.swift
// RUN: diff -u %S/Outputs/basic/L15-3.swift.expected %t.result/L15-3.swift
// RUN: %refactor -collapse-nested-if -source-filename %s -pos=21:3 > %t.result/L21-3.swift
// RUN: diff -u %S/Outputs/basic/L21-3.swift.expected %t.result/L21-3.swift
| apache-2.0 | f6c84fe004cd7a12c4af179e577d0d16 | 31.515152 | 91 | 0.621622 | 2.489559 | false | true | false | false |
badoo/Chatto | Chatto/sources/ChatController/BaseChatViewController.swift | 1 | 19926 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 ReplyActionHandler: AnyObject {
func handleReply(for: ChatItemProtocol)
}
public protocol ChatViewControllerProtocol: ChatMessagesCollectionHolderProtocol, ChatInputBarPresentingController {
func configure(style: ChatViewControllerStyle)
}
public final class BaseChatViewController: UIViewController {
public typealias ChatMessagesViewControllerProtocol = ChatMessagesViewProtocol & UIViewController
private let messagesViewController: ChatMessagesViewControllerProtocol
private let configuration: Configuration
private let keyboardUpdatesHandler: KeyboardUpdatesHandlerProtocol
private let collectionViewEventsHandlers: [CollectionViewEventsHandling]
private let viewEventsHandlers: [ViewPresentationEventsHandling]
public var collectionView: UICollectionView { self.messagesViewController.collectionView }
public let inputBarContainer: UIView = UIView(frame: .zero)
private(set) public lazy var inputContainerBottomConstraint: NSLayoutConstraint = self.makeInputContainerBottomConstraint()
public let inputContentContainer: UIView = UIView(frame: .zero)
public var chatItemCompanionCollection: ChatItemCompanionCollection {
self.messagesViewController.chatItemCompanionCollection
}
private var isAdjustingInputContainer: Bool = false
private var previousBoundsUsedForInsetsAdjustment: CGRect?
public var layoutConfiguration: ChatLayoutConfigurationProtocol = ChatLayoutConfiguration.defaultConfiguration {
didSet {
self.adjustCollectionViewInsets(shouldUpdateContentOffset: false)
}
}
public var inputContentBottomMargin: CGFloat {
return self.inputContainerBottomConstraint.constant
}
private var inputContainerBottomBaseOffset: CGFloat = 0 {
didSet { self.updateInputContainerBottomConstraint() }
}
private var inputContainerBottomAdditionalOffset: CGFloat = 0 {
didSet { self.updateInputContainerBottomConstraint() }
}
private var allContentFits: Bool {
let collectionView = self.collectionView
let inputHeightWithKeyboard = self.view.bounds.height - self.inputBarContainer.frame.minY
let insetTop = self.view.safeAreaInsets.top + self.layoutConfiguration.contentInsets.top
let insetBottom = self.layoutConfiguration.contentInsets.bottom + inputHeightWithKeyboard
let availableHeight = collectionView.bounds.height - (insetTop + insetBottom)
let contentSize = collectionView.collectionViewLayout.collectionViewContentSize
return availableHeight >= contentSize.height
}
// MARK: - Init
public init(messagesViewController: ChatMessagesViewControllerProtocol,
collectionViewEventsHandlers: [CollectionViewEventsHandling],
keyboardUpdatesHandler: KeyboardUpdatesHandlerProtocol,
viewEventsHandlers: [ViewPresentationEventsHandling],
configuration: Configuration = .default) {
self.messagesViewController = messagesViewController
self.collectionViewEventsHandlers = collectionViewEventsHandlers
self.keyboardUpdatesHandler = keyboardUpdatesHandler
self.viewEventsHandlers = viewEventsHandlers
self.configuration = configuration
super.init(nibName: nil, bundle: nil)
}
required public init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
public override func loadView() { // swiftlint:disable:this prohibited_super_call
self.view = BaseChatViewControllerView() // http://stackoverflow.com/questions/24596031/uiviewcontroller-with-inputaccessoryview-is-not-deallocated
self.view.backgroundColor = UIColor.white
}
override public func viewDidLoad() {
super.viewDidLoad()
self.setupCollectionView()
self.addInputBarContainer()
self.addInputContentContainer()
self.setupKeyboardTracker()
self.setupTapGestureRecognizer()
self.refreshContent()
self.viewEventsHandlers.forEach {
$0.onViewDidLoad()
}
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.keyboardUpdatesHandler.startTracking()
self.viewEventsHandlers.forEach {
$0.onViewWillAppear()
}
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.viewEventsHandlers.forEach {
$0.onViewDidAppear()
}
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.keyboardUpdatesHandler.stopTracking()
self.viewEventsHandlers.forEach {
$0.onViewWillDisappear()
}
}
override public func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.viewEventsHandlers.forEach {
$0.onViewDidDisappear()
}
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.adjustCollectionViewInsets(shouldUpdateContentOffset: true)
self.keyboardUpdatesHandler.adjustLayoutIfNeeded()
self.updateInputContainerBottomBaseOffset()
self.viewEventsHandlers.forEach {
$0.onViewDidLayoutSubviews()
}
}
// MARK: - Setup
private func setupTapGestureRecognizer() {
let collectionView = self.collectionView
collectionView.addGestureRecognizer(
UITapGestureRecognizer(target: self, action: #selector(BaseChatViewController.userDidTapOnCollectionView))
)
}
@objc
private func userDidTapOnCollectionView() {
guard self.configuration.endsEditingWhenTappingOnChatBackground else {
return
}
self.view.endEditing(true)
self.viewEventsHandlers.forEach {
$0.onDidEndEditing()
}
}
private func setupCollectionView() {
self.addChild(self.messagesViewController)
defer { self.messagesViewController.didMove(toParent: self) }
self.view.addSubview(self.messagesViewController.view)
self.messagesViewController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.view.topAnchor.constraint(equalTo: self.messagesViewController.view.topAnchor),
self.view.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: self.messagesViewController.view.trailingAnchor),
self.view.bottomAnchor.constraint(equalTo: self.messagesViewController.view.bottomAnchor),
self.view.safeAreaLayoutGuide.leadingAnchor.constraint(equalTo: self.messagesViewController.view.leadingAnchor)
])
}
private func addInputBarContainer() {
self.inputBarContainer.translatesAutoresizingMaskIntoConstraints = false
self.inputBarContainer.backgroundColor = .white
self.view.addSubview(self.inputBarContainer)
let guide = self.view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
self.inputBarContainer.topAnchor.constraint(greaterThanOrEqualTo: guide.topAnchor),
self.inputBarContainer.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
self.inputBarContainer.trailingAnchor.constraint(equalTo: guide.trailingAnchor)
])
self.view.addConstraint(self.inputContainerBottomConstraint)
}
private func makeInputContainerBottomConstraint() -> NSLayoutConstraint {
return self.view.bottomAnchor.constraint(equalTo: self.inputBarContainer.bottomAnchor)
}
private func addInputContentContainer() {
self.inputContentContainer.translatesAutoresizingMaskIntoConstraints = false
self.inputContentContainer.backgroundColor = .white
self.view.addSubview(self.inputContentContainer)
NSLayoutConstraint.activate([
self.view.bottomAnchor.constraint(equalTo: self.inputContentContainer.bottomAnchor),
self.view.leadingAnchor.constraint(equalTo: self.inputContentContainer.leadingAnchor),
self.view.trailingAnchor.constraint(equalTo: self.inputContentContainer.trailingAnchor),
self.inputContentContainer.topAnchor.constraint(equalTo: self.inputBarContainer.bottomAnchor)
])
}
private func updateInputContainerBottomBaseOffset() {
let offset = self.view.safeAreaInsets.bottom
if self.inputContainerBottomBaseOffset != offset {
self.inputContainerBottomBaseOffset = offset
}
}
private func setupKeyboardTracker() {
(self.view as? BaseChatViewControllerViewProtocol)?.bmaInputAccessoryView = self.keyboardUpdatesHandler.keyboardTrackingView
}
private func updateInputContainerBottomConstraint() {
self.inputContainerBottomConstraint.constant = max(self.inputContainerBottomBaseOffset, self.inputContainerBottomAdditionalOffset)
self.view.setNeedsLayout()
}
private func adjustCollectionViewInsets(shouldUpdateContentOffset: Bool) {
guard self.isViewLoaded else { return }
let collectionView = self.collectionView
let isInteracting = collectionView.panGestureRecognizer.numberOfTouches > 0
let isBouncingAtTop = isInteracting && collectionView.contentOffset.y < -collectionView.contentInset.top
if isBouncingAtTop { return }
let inputHeightWithKeyboard = self.view.bounds.height - self.inputBarContainer.frame.minY
let newInsetBottom = self.layoutConfiguration.contentInsets.bottom + inputHeightWithKeyboard
let insetBottomDiff = newInsetBottom - collectionView.contentInset.bottom
let newInsetTop = self.view.safeAreaInsets.top + self.layoutConfiguration.contentInsets.top
let contentSize = collectionView.collectionViewLayout.collectionViewContentSize
let prevContentOffsetY = collectionView.contentOffset.y
let boundsHeightDiff: CGFloat = {
guard shouldUpdateContentOffset, let lastUsedBounds = self.previousBoundsUsedForInsetsAdjustment else {
return 0
}
let diff = lastUsedBounds.height - collectionView.bounds.height
// When collectionView is scrolled to bottom and height increases,
// collectionView adjusts its contentOffset automatically
let isScrolledToBottom = contentSize.height <= collectionView.bounds.maxY - collectionView.contentInset.bottom
return isScrolledToBottom ? max(0, diff) : diff
}()
self.previousBoundsUsedForInsetsAdjustment = collectionView.bounds
let newContentOffsetY: CGFloat = {
let minOffset = -newInsetTop
let maxOffset = contentSize.height - (collectionView.bounds.height - newInsetBottom)
let targetOffset = prevContentOffsetY + insetBottomDiff + boundsHeightDiff
return max(min(maxOffset, targetOffset), minOffset)
}()
collectionView.contentInset = {
var currentInsets = collectionView.contentInset
currentInsets.bottom = newInsetBottom
currentInsets.top = newInsetTop
return currentInsets
}()
collectionView.chatto_setVerticalScrollIndicatorInsets({
var currentInsets = collectionView.scrollIndicatorInsets
currentInsets.bottom = self.layoutConfiguration.scrollIndicatorInsets.bottom + inputHeightWithKeyboard
currentInsets.top = self.view.safeAreaInsets.top + self.layoutConfiguration.scrollIndicatorInsets.top
return currentInsets
}())
guard shouldUpdateContentOffset else { return }
let inputIsAtBottom = self.view.bounds.maxY - self.inputBarContainer.frame.maxY <= 0
if self.allContentFits {
collectionView.contentOffset.y = -collectionView.contentInset.top
} else if !isInteracting || inputIsAtBottom {
collectionView.contentOffset.y = newContentOffsetY
}
}
// MARK: - ChatMessagesViewControllerDelegate
public func chatMessagesViewControllerShouldAnimateCellOnDisplay(_ : ChatMessagesViewController) -> Bool {
return !self.isAdjustingInputContainer
}
// Proxy APIs
public func refreshContent(completionBlock: (() -> Void)? = nil) {
self.messagesViewController.refreshContent(completionBlock: completionBlock)
}
public var isScrolledAtBottom: Bool {
return self.collectionView.isScrolledAtBottom()
}
public func scrollToBottom(animated: Bool) {
self.messagesViewController.scrollToBottom(animated: animated)
}
public func autoLoadMoreContentIfNeeded() {
self.messagesViewController.autoLoadMoreContentIfNeeded()
}
}
extension BaseChatViewController: ChatMessagesViewControllerDelegate {
public func chatMessagesViewController(_: ChatMessagesViewController,
scrollViewDidEndDragging scrollView: UIScrollView,
willDecelerate decelerate: Bool) {
self.collectionViewEventsHandlers.forEach {
$0.onScrollViewDidEndDragging(scrollView, decelerate: decelerate)
}
}
public func chatMessagesViewController(_ viewController: ChatMessagesViewController, onDisplayCellWithIndexPath indexPath: IndexPath) {
self.collectionViewEventsHandlers.forEach {
$0.onCollectionView(
viewController.collectionView,
didDisplayCellWithIndexPath: indexPath,
companionCollection: self.chatItemCompanionCollection
)
}
}
public func chatMessagesViewController(_ viewController: ChatMessagesViewController, didUpdateItemsWithUpdateType updateType: UpdateType) {
self.collectionViewEventsHandlers.forEach {
$0.onCollectionView(
viewController.collectionView,
didUpdateItemsWithUpdateType: updateType
)
}
}
public func chatMessagesViewController(_ viewController: ChatMessagesViewController, didScroll scrollView: UIScrollView) {
self.collectionViewEventsHandlers.forEach {
$0.onScrollViewDidScroll(scrollView)
}
}
public func chatMessagesViewController(_ : ChatMessagesViewController, willEndDragging scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
self.collectionViewEventsHandlers.forEach {
$0.onScrollViewWillEndDragging(
scrollView,
velocity: velocity,
targetContentOffset: targetContentOffset
)
}
}
public func chatMessagesViewController(_ : ChatMessagesViewController, willBeginDragging scrollView: UIScrollView) {
self.collectionViewEventsHandlers.forEach {
$0.onScrollViewWillBeginDragging(scrollView)
}
}
}
extension BaseChatViewController: ChatMessagesCollectionHolderProtocol {
public func scrollToItem(withId id: String, position: UICollectionView.ScrollPosition, animated: Bool) {
self.scrollToItem(
withId: id,
position: position,
animated: animated,
spotlight: false
)
}
public func scrollToItem(withId itemId: String,
position: UICollectionView.ScrollPosition = .centeredVertically,
animated: Bool = false,
spotlight: Bool = false) {
self.messagesViewController.scroll(
toItemId: itemId,
position: position,
animated: animated,
spotlight: spotlight
)
// Programmatic scroll don't trigger autoloading, so, we need to trigger it manually
self.autoLoadMoreContentIfNeeded()
}
}
extension BaseChatViewController: ChatInputBarPresentingController {
public var maximumInputSize: CGSize {
return self.view.bounds.size
}
public func setup(inputView: UIView) {
self.inputBarContainer.subviews.forEach { $0.removeFromSuperview() }
inputView.translatesAutoresizingMaskIntoConstraints = false
self.inputBarContainer.addSubview(inputView)
NSLayoutConstraint.activate([
self.inputBarContainer.topAnchor.constraint(equalTo: inputView.topAnchor),
self.inputBarContainer.bottomAnchor.constraint(equalTo: inputView.bottomAnchor),
self.inputBarContainer.leadingAnchor.constraint(equalTo: inputView.leadingAnchor),
self.inputBarContainer.trailingAnchor.constraint(equalTo: inputView.trailingAnchor)
])
}
public func changeInputContentBottomMargin(to value: CGFloat, animation: ChatInputBarAnimationProtocol?, completion: (() -> Void)?) {
self.isAdjustingInputContainer = true
self.inputContainerBottomAdditionalOffset = value
if let animation = animation {
animation.animate(view: self.view, completion: completion)
} else {
self.view.layoutIfNeeded()
completion?()
}
self.isAdjustingInputContainer = false
}
}
extension BaseChatViewController: ChatViewControllerProtocol {
public func configure(style: ChatViewControllerStyle) {
self.inputContentContainer.backgroundColor = style.inputBarBackgroundColor
self.messagesViewController.configure(
backgroundColor: style.messagesBackgroundColor
)
}
}
public extension BaseChatViewController {
struct Configuration {
public var endsEditingWhenTappingOnChatBackground: Bool
public init(endsEditingWhenTappingOnChatBackground: Bool) {
self.endsEditingWhenTappingOnChatBackground = endsEditingWhenTappingOnChatBackground
}
}
}
public extension BaseChatViewController.Configuration {
static var `default`: Self {
return .init(
endsEditingWhenTappingOnChatBackground: true
)
}
}
public struct ChatViewControllerStyle {
public var inputBarBackgroundColor: UIColor
public var messagesBackgroundColor: UIColor
public init(
inputBarBackgroundColor: UIColor,
messagesBackgroundColor: UIColor
) {
self.inputBarBackgroundColor = inputBarBackgroundColor
self.messagesBackgroundColor = messagesBackgroundColor
}
}
public extension ChatViewControllerStyle {
static var `default`: Self {
return .init(
inputBarBackgroundColor: .white,
messagesBackgroundColor: ChatMessagesViewController.Style.default.backgroundColor
)
}
}
| mit | 3b175670ddb4a779936c301f0785e1cf | 38.772455 | 202 | 0.715347 | 6.1557 | false | false | false | false |
vector-im/vector-ios | Config/AppConfiguration.swift | 1 | 2689 | //
// Copyright 2020 Vector Creations Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// AppConfiguration is CommonConfiguration plus configurations dedicated to the app
class AppConfiguration: CommonConfiguration {
// MARK: - Global settings
override func setupSettings() {
super.setupSettings()
setupAppSettings()
}
private func setupAppSettings() {
// Enable CallKit for app
MXKAppSettings.standard()?.isCallKitEnabled = true
// Get modular widget events in rooms histories
MXKAppSettings.standard()?.addSupportedEventTypes([kWidgetMatrixEventTypeString,
kWidgetModularEventTypeString])
// Hide undecryptable messages that were sent while the user was not in the room
MXKAppSettings.standard()?.hidePreJoinedUndecryptableEvents = true
// Enable long press on event in bubble cells
MXKRoomBubbleTableViewCell.disableLongPressGesture(onEvent: false)
// Each room member will be considered as a potential contact.
MXKContactManager.shared().contactManagerMXRoomSource = MXKContactManagerMXRoomSource.all
// Use UIKit BackgroundTask for handling background tasks in the SDK
MXSDKOptions.sharedInstance().backgroundModeHandler = MXUIKitBackgroundModeHandler()
// Enable key backup on app
MXSDKOptions.sharedInstance().enableKeyBackupWhenStartingMXCrypto = true
}
// MARK: - Per matrix session settings
override func setupSettings(for matrixSession: MXSession) {
super.setupSettings(for: matrixSession)
setupWidgetReadReceipts(for: matrixSession)
}
private func setupWidgetReadReceipts(for matrixSession: MXSession) {
var acknowledgableEventTypes = matrixSession.acknowledgableEventTypes ?? []
acknowledgableEventTypes.append(kWidgetMatrixEventTypeString)
acknowledgableEventTypes.append(kWidgetModularEventTypeString)
matrixSession.acknowledgableEventTypes = acknowledgableEventTypes
}
}
| apache-2.0 | 39126a301d582f6eaa202c921f8c6611 | 37.971014 | 97 | 0.704723 | 5.487755 | false | true | false | false |
vector-im/vector-ios | Riot/Modules/KeyVerification/User/Start/UserVerificationStartViewModel.swift | 1 | 6825 | // File created from ScreenTemplate
// $ createScreen.sh Start UserVerificationStart
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
enum UserVerificationStartViewModelError: Error {
case keyVerificationRequestExpired
}
struct UserVerificationStartViewData {
let userId: String
let userDisplayName: String?
let userAvatarURL: String?
}
final class UserVerificationStartViewModel: UserVerificationStartViewModelType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let roomMember: MXRoomMember
private let verificationManager: MXKeyVerificationManager
private let keyVerificationService: KeyVerificationService
private var keyVerificationRequest: MXKeyVerificationRequest?
private var viewData: UserVerificationStartViewData {
return UserVerificationStartViewData(userId: self.roomMember.userId, userDisplayName: self.roomMember.displayname, userAvatarURL: self.roomMember.avatarUrl)
}
// MARK: Public
weak var viewDelegate: UserVerificationStartViewModelViewDelegate?
weak var coordinatorDelegate: UserVerificationStartViewModelCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession, roomMember: MXRoomMember) {
self.session = session
self.verificationManager = session.crypto.keyVerificationManager
self.roomMember = roomMember
self.keyVerificationService = KeyVerificationService()
}
// MARK: - Public
func process(viewAction: UserVerificationStartViewAction) {
switch viewAction {
case .loadData:
self.loadData()
case .startVerification:
self.startVerification()
case .cancel:
self.cancelKeyVerificationRequest()
self.coordinatorDelegate?.userVerificationStartViewModelDidCancel(self)
}
}
// MARK: - Private
private func loadData() {
self.update(viewState: .loaded(self.viewData))
}
private func startVerification() {
self.update(viewState: .verificationPending)
self.verificationManager.requestVerificationByDM(withUserId: self.roomMember.userId,
roomId: nil,
fallbackText: "",
methods: self.keyVerificationService.supportedKeyVerificationMethods(),
success: { [weak self] (keyVerificationRequest) in
guard let self = self else {
return
}
self.keyVerificationRequest = keyVerificationRequest
self.update(viewState: .loaded(self.viewData))
self.registerKeyVerificationRequestDidChangeNotification(for: keyVerificationRequest)
}, failure: { [weak self] error in
self?.update(viewState: .error(error))
})
}
private func update(viewState: UserVerificationStartViewState) {
self.viewDelegate?.userVerificationStartViewModel(self, didUpdateViewState: viewState)
}
private func cancelKeyVerificationRequest() {
guard let keyVerificationRequest = self.keyVerificationRequest else {
return
}
keyVerificationRequest.cancel(with: MXTransactionCancelCode.user(), success: nil, failure: nil)
}
// MARK: - MXKeyVerificationRequestDidChange
private func registerKeyVerificationRequestDidChangeNotification(for keyVerificationRequest: MXKeyVerificationRequest) {
NotificationCenter.default.addObserver(self, selector: #selector(keyVerificationRequestDidChange(notification:)), name: .MXKeyVerificationRequestDidChange, object: keyVerificationRequest)
}
private func unregisterKeyVerificationRequestDidChangeNotification() {
NotificationCenter.default.removeObserver(self, name: .MXKeyVerificationRequestDidChange, object: nil)
}
@objc private func keyVerificationRequestDidChange(notification: Notification) {
guard let keyVerificationRequest = notification.object as? MXKeyVerificationByDMRequest else {
return
}
guard let currentKeyVerificationRequest = self.keyVerificationRequest, keyVerificationRequest.requestId == currentKeyVerificationRequest.requestId else {
return
}
switch keyVerificationRequest.state {
case MXKeyVerificationRequestStateAccepted:
self.unregisterKeyVerificationRequestDidChangeNotification()
self.coordinatorDelegate?.userVerificationStartViewModel(self, otherDidAcceptRequest: currentKeyVerificationRequest)
case MXKeyVerificationRequestStateReady:
self.unregisterKeyVerificationRequestDidChangeNotification()
self.coordinatorDelegate?.userVerificationStartViewModel(self, otherDidAcceptRequest: currentKeyVerificationRequest)
case MXKeyVerificationRequestStateCancelled:
guard let reason = keyVerificationRequest.reasonCancelCode else {
return
}
self.unregisterKeyVerificationRequestDidChangeNotification()
self.update(viewState: .cancelled(reason))
case MXKeyVerificationRequestStateCancelledByMe:
guard let reason = keyVerificationRequest.reasonCancelCode else {
return
}
self.unregisterKeyVerificationRequestDidChangeNotification()
self.update(viewState: .cancelledByMe(reason))
case MXKeyVerificationRequestStateExpired:
self.unregisterKeyVerificationRequestDidChangeNotification()
self.update(viewState: .error(UserVerificationStartViewModelError.keyVerificationRequestExpired))
default:
break
}
}
}
| apache-2.0 | eb9aa9f4d7ce9efd027a23cf50ce0546 | 41.924528 | 195 | 0.658168 | 6.907895 | false | false | false | false |
abertelrud/swift-package-manager | Tests/WorkspaceTests/InitTests.swift | 2 | 14948 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import SPMTestSupport
import TSCBasic
import PackageModel
import Workspace
class InitTests: XCTestCase {
// MARK: TSCBasic package creation for each package type.
func testInitPackageEmpty() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending(component: "Foo")
let name = path.basename
try fs.createDirectory(path)
// Create the package
let initPackage = try InitPackage(
name: name,
packageType: .empty,
destinationPath: path,
fileSystem: localFileSystem
)
var progressMessages = [String]()
initPackage.progressReporter = { message in
progressMessages.append(message)
}
try initPackage.writePackageStructure()
// Not picky about the specific progress messages, just checking that we got some.
XCTAssertGreaterThan(progressMessages.count, 0)
// Verify basic file system content that we expect in the package
let manifest = path.appending(component: "Package.swift")
XCTAssertFileExists(manifest)
let manifestContents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(manifestContents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
XCTAssertMatch(manifestContents, .contains(packageWithNameAndDependencies(with: name)))
XCTAssertFileExists(path.appending(component: "README.md"))
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources")), [])
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Tests")), [])
}
}
func testInitPackageExecutable() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending(component: "Foo")
let name = path.basename
try fs.createDirectory(path)
// Create the package
let initPackage = try InitPackage(
name: name,
packageType: .executable,
destinationPath: path,
fileSystem: localFileSystem
)
var progressMessages = [String]()
initPackage.progressReporter = { message in
progressMessages.append(message)
}
try initPackage.writePackageStructure()
// Not picky about the specific progress messages, just checking that we got some.
XCTAssertGreaterThan(progressMessages.count, 0)
// Verify basic file system content that we expect in the package
let manifest = path.appending(component: "Package.swift")
XCTAssertFileExists(manifest)
let manifestContents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(manifestContents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
let readme = path.appending(component: "README.md")
XCTAssertFileExists(readme)
let readmeContents: String = try localFileSystem.readFileContents(readme)
XCTAssertMatch(readmeContents, .prefix("# Foo\n"))
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources").appending(component: "Foo")), ["Foo.swift"])
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Tests")).sorted(), ["FooTests"])
// If we have a compiler that supports `-entry-point-function-name`, we try building it (we need that flag now).
#if swift(>=5.5)
XCTAssertBuilds(path)
let triple = try UserToolchain.default.triple
let binPath = path.appending(components: ".build", triple.platformBuildPathComponent(), "debug")
#if os(Windows)
XCTAssertFileExists(binPath.appending(component: "Foo.exe"))
#else
XCTAssertFileExists(binPath.appending(component: "Foo"))
#endif
XCTAssertFileExists(binPath.appending(components: "Foo.swiftmodule"))
#endif
}
}
func testInitPackageLibrary() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending(component: "Foo")
let name = path.basename
try fs.createDirectory(path)
// Create the package
let initPackage = try InitPackage(
name: name,
packageType: .library,
destinationPath: path,
fileSystem: localFileSystem
)
var progressMessages = [String]()
initPackage.progressReporter = { message in
progressMessages.append(message)
}
try initPackage.writePackageStructure()
// Not picky about the specific progress messages, just checking that we got some.
XCTAssertGreaterThan(progressMessages.count, 0)
// Verify basic file system content that we expect in the package
let manifest = path.appending(component: "Package.swift")
XCTAssertFileExists(manifest)
let manifestContents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(manifestContents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
let readme = path.appending(component: "README.md")
XCTAssertFileExists(readme)
let readmeContents: String = try localFileSystem.readFileContents(readme)
XCTAssertMatch(readmeContents, .prefix("# Foo\n"))
XCTAssertEqual(try fs.getDirectoryContents(path.appending(component: "Sources").appending(component: "Foo")), ["Foo.swift"])
let tests = path.appending(component: "Tests")
XCTAssertEqual(try fs.getDirectoryContents(tests).sorted(), ["FooTests"])
let testFile = tests.appending(component: "FooTests").appending(component: "FooTests.swift")
let testFileContents: String = try localFileSystem.readFileContents(testFile)
XCTAssertTrue(testFileContents.hasPrefix("import XCTest"), """
Validates formatting of XCTest source file, in particular that it does not contain leading whitespace:
\(testFileContents)
""")
XCTAssertMatch(testFileContents, .contains("func testExample() throws"))
// Try building it
XCTAssertBuilds(path)
let triple = try UserToolchain.default.triple
XCTAssertFileExists(path.appending(components: ".build", triple.platformBuildPathComponent(), "debug", "Foo.swiftmodule"))
}
}
func testInitPackageSystemModule() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending(component: "Foo")
let name = path.basename
try fs.createDirectory(path)
// Create the package
let initPackage = try InitPackage(
name: name,
packageType: .systemModule,
destinationPath: path,
fileSystem: localFileSystem
)
var progressMessages = [String]()
initPackage.progressReporter = { message in
progressMessages.append(message)
}
try initPackage.writePackageStructure()
// Not picky about the specific progress messages, just checking that we got some.
XCTAssertGreaterThan(progressMessages.count, 0)
// Verify basic file system content that we expect in the package
let manifest = path.appending(component: "Package.swift")
XCTAssertFileExists(manifest)
let manifestContents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(manifestContents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
XCTAssertMatch(manifestContents, .contains(packageWithNameAndDependencies(with: name)))
XCTAssert(fs.exists(path.appending(component: "README.md")))
XCTAssert(fs.exists(path.appending(component: "module.modulemap")))
}
}
func testInitManifest() throws {
try testWithTemporaryDirectory { tmpPath in
let fs = localFileSystem
let path = tmpPath.appending(component: "Foo")
let name = path.basename
try fs.createDirectory(path)
// Create the package
let initPackage = try InitPackage(
name: name,
packageType: InitPackage.PackageType.manifest,
destinationPath: path,
fileSystem: localFileSystem
)
var progressMessages = [String]()
initPackage.progressReporter = { message in
progressMessages.append(message)
}
try initPackage.writePackageStructure()
// Not picky about the specific progress messages, just checking that we got some.
XCTAssertGreaterThan(progressMessages.count, 0)
// Verify basic file system content that we expect in the package
let manifest = path.appending(component: "Package.swift")
XCTAssertFileExists(manifest)
let manifestContents: String = try localFileSystem.readFileContents(manifest)
let version = InitPackage.newPackageToolsVersion
let versionSpecifier = "\(version.major).\(version.minor)"
XCTAssertMatch(manifestContents, .prefix("// swift-tools-version:\(version < .v5_4 ? "" : " ")\(versionSpecifier)\n"))
}
}
// MARK: Special case testing
func testInitPackageNonc99Directory() throws {
try withTemporaryDirectory(removeTreeOnDeinit: true) { tempDirPath in
XCTAssertDirectoryExists(tempDirPath)
// Create a directory with non c99name.
let packageRoot = tempDirPath.appending(component: "some-package")
let packageName = packageRoot.basename
try localFileSystem.createDirectory(packageRoot)
XCTAssertDirectoryExists(packageRoot)
// Create the package
let initPackage = try InitPackage(
name: packageName,
packageType: .library,
destinationPath: packageRoot,
fileSystem: localFileSystem
)
initPackage.progressReporter = { message in }
try initPackage.writePackageStructure()
// Try building it.
XCTAssertBuilds(packageRoot)
let triple = try UserToolchain.default.triple
XCTAssertFileExists(packageRoot.appending(components: ".build", triple.platformBuildPathComponent(), "debug", "some_package.swiftmodule"))
}
}
func testNonC99NameExecutablePackage() throws {
throw XCTSkip("This test fails to find XCTAssertEqual; rdar://101868275")
try withTemporaryDirectory(removeTreeOnDeinit: true) { tempDirPath in
XCTAssertDirectoryExists(tempDirPath)
let packageRoot = tempDirPath.appending(component: "Foo")
try localFileSystem.createDirectory(packageRoot)
XCTAssertDirectoryExists(packageRoot)
// Create package with non c99name.
let initPackage = try InitPackage(
name: "package-name",
packageType: .executable,
destinationPath: packageRoot,
fileSystem: localFileSystem
)
try initPackage.writePackageStructure()
#if os(macOS)
XCTAssertSwiftTest(packageRoot)
#else
XCTAssertBuilds(packageRoot)
#endif
}
}
func testPlatforms() throws {
try withTemporaryDirectory(removeTreeOnDeinit: true) { tempDirPath in
var options = InitPackage.InitPackageOptions(packageType: .library)
options.platforms = [
.init(platform: .macOS, version: PlatformVersion("10.15")),
.init(platform: .iOS, version: PlatformVersion("12")),
.init(platform: .watchOS, version: PlatformVersion("2.1")),
.init(platform: .tvOS, version: PlatformVersion("999")),
]
let packageRoot = tempDirPath.appending(component: "Foo")
try localFileSystem.removeFileTree(packageRoot)
try localFileSystem.createDirectory(packageRoot)
let initPackage = try InitPackage(
name: "Foo",
options: options,
destinationPath: packageRoot,
fileSystem: localFileSystem
)
try initPackage.writePackageStructure()
let contents: String = try localFileSystem.readFileContents(packageRoot.appending(component: "Package.swift"))
XCTAssertMatch(contents, .contains(#"platforms: [.macOS(.v10_15), .iOS(.v12), .watchOS("2.1"), .tvOS("999.0")],"#))
}
}
private func packageWithNameAndDependencies(with name: String) -> String {
return """
let package = Package(
name: "\(name)",
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
]
)
"""
}
}
| apache-2.0 | f3e5448877612fb2f24a280b8be8821f | 43.888889 | 150 | 0.608911 | 5.880409 | false | true | false | false |
alejandrogarin/ADGCoreDataKit | Source/CoreDataContext.swift | 1 | 5969 | //
// CoreDataContext.swift
// ADGCoreDataKit
//
// Created by Alejandro Diego Garin
// The MIT License (MIT)
//
// Copyright (c) 2015 Alejandro Garin @alejandrogarin
//
// 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 CoreData
public protocol CoreDataContextDelegate: class {
func coreDataContextObjectsDidChangeNotification(_ notification: Notification)
func coreDataContextObjectContextDidSaveNotification(_ notification: Notification)
}
public class CoreDataContext: NSObject {
let objectContext : NSManagedObjectContext
let persistentCoordinator: NSPersistentStoreCoordinator
public weak var delegate : CoreDataContextDelegate?
public var hasChanges: Bool {
return self.objectContext.hasChanges
}
internal init(usingPersistentStoreCoordinator storeCoordinator : NSPersistentStoreCoordinator, concurrencyType type : NSManagedObjectContextConcurrencyType) {
persistentCoordinator = storeCoordinator
objectContext = NSManagedObjectContext(concurrencyType: type)
objectContext.persistentStoreCoordinator = storeCoordinator
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(objectsDidChangeNotification), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: objectContext)
NotificationCenter.default.addObserver(self, selector: #selector(objectContextDidSaveNotification), name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: objectContext)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil)
}
public func objectContextDidSaveNotification(_ notification: Notification) {
self.delegate?.coreDataContextObjectsDidChangeNotification(notification)
}
public func objectsDidChangeNotification(_ notification: Notification) {
self.delegate?.coreDataContextObjectsDidChangeNotification(notification)
}
public func fetch(byManagedObjectId objectId: NSManagedObjectID) throws -> NSManagedObject {
return try objectContext.existingObject(with: objectId)
}
public func find(entityName: String, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, page: Int? = nil, pageSize: Int? = nil) throws -> [AnyObject] {
let request = self.createFetchRequest(forEntityName: entityName, predicate: predicate, sortDescriptors: sortDescriptors, page: page, pageSize: pageSize)
return try objectContext.fetch(request)
}
public func count(rowsForEntityName entityName: String, predicate: NSPredicate?) throws -> Int {
let request = self.createFetchRequest(forEntityName: entityName, predicate: predicate)
return try objectContext.count(for: request)
}
public func insert(withEntityName entityName: String) -> NSManagedObject {
return NSEntityDescription.insertNewObject(forEntityName: entityName, into: self.objectContext)
}
public func delete(byId objectId: String) throws {
let managedObjectId = try self.managedObjectIdFromStringObjectId(objectId)
try self.delete(managedObject: self.fetch(byManagedObjectId: managedObjectId))
}
public func delete(managedObject: NSManagedObject) -> Void {
objectContext.delete(managedObject)
}
public func save() throws {
try objectContext.save()
}
public func rollback() {
objectContext.rollback()
}
public func reset() {
objectContext.reset()
}
public func performBlock(_ block: @escaping () -> Void) {
objectContext.perform(block)
}
public func managedObjectIdFromStringObjectId(_ objectId: String) throws -> NSManagedObjectID {
guard let url = URL(string: objectId), let managedObjectId = self.objectContext.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: url) else {
throw CoreDataKitError.managedObjectIdNotFound
}
return managedObjectId;
}
private func createFetchRequest(forEntityName entityName : String, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, page: Int? = nil, pageSize: Int? = nil) -> NSFetchRequest<NSManagedObject> {
let request = NSFetchRequest<NSManagedObject>()
request.sortDescriptors = sortDescriptors
request.predicate = predicate
request.entity = NSEntityDescription.entity(forEntityName: entityName, in: self.objectContext)
if let page = page, let pageSize = pageSize {
request.fetchLimit = pageSize;
request.fetchOffset = page * pageSize
}
return request
}
}
| mit | 7c06d5653d8efb243cea5bc42733b59e | 43.879699 | 222 | 0.735299 | 5.588951 | false | false | false | false |
davidengelhardt/PressGestureRecognizer | PressGestureRecognizer/PressGestureRecognizer.swift | 1 | 3831 | //
// PressGestureRecognizer.swift
// PressGestureRecognizer
//
// Created by David Engelhardt on 6/6/16.
// Copyright © 2016 Viacom. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
import GameController
public class PressGestureRecognizer: UIGestureRecognizer {
public enum Direction {
case Up
case Down
case Left
case Right
}
private var edgeThreshold: Float = 0.5
private var siriRemotePad: GCMicroGamepad?
private var directionToRecognize: Direction!
public init(target: AnyObject?, action: Selector, direction: Direction, edgeThreshold: Float = 0.5) {
super.init(target: target, action: action)
self.directionToRecognize = direction
self.edgeThreshold = edgeThreshold
registerForGameControllerNotifications()
}
//MARK: Touches & Presses
override public func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent) {
for press in presses {
switch press.type {
case .Select:
var edgeCondition: Bool
if let remotePadXValue = siriRemotePad?.dpad.xAxis.value,
let remotePadYValue = siriRemotePad?.dpad.yAxis.value {
switch directionToRecognize! {
case .Up:
edgeCondition = remotePadYValue > edgeThreshold
case .Down:
edgeCondition = remotePadYValue < -edgeThreshold
case .Right:
edgeCondition = remotePadXValue > edgeThreshold
case .Left:
edgeCondition = remotePadXValue < -edgeThreshold
}
if edgeCondition {
state = .Began
} else {
state = .Failed
}
}
default:
print("clicked something else")
state = .Failed
}
}
}
override public func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent) {
super.pressesEnded(presses, withEvent: event)
state = .Ended
}
override public func pressesChanged(presses: Set<UIPress>, withEvent event: UIPressesEvent) {
super.pressesChanged(presses, withEvent: event)
state = .Changed
}
override public func pressesCancelled(presses: Set<UIPress>, withEvent event: UIPressesEvent) {
super.pressesCancelled(presses, withEvent: event)
state = .Cancelled
}
//MARK: Siri Remote
func registerForGameControllerNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(handleControllerDidConnectNotification), name: GCControllerDidConnectNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(handleControllerDidDisconnectNotification), name: GCControllerDidDisconnectNotification, object: nil)
}
func handleControllerDidConnectNotification() {
setupRemoteControlPad()
}
func handleControllerDidDisconnectNotification() {
}
func setupRemoteControlPad() {
let controllerList = GCController.controllers()
if controllerList.count < 1 {
print("No controller found: PressGestureRecognizer will not work")
} else {
if let pad = controllerList.first?.microGamepad {
siriRemotePad = pad
siriRemotePad!.reportsAbsoluteDpadValues = true
}
}
}
}
| mit | 6dfd91802b854c11f8326381d82bf321 | 32.596491 | 184 | 0.58799 | 5.919629 | false | false | false | false |
crazypoo/PTools | Pods/KakaJSON/Sources/KakaJSON/Metadata/Type/FunctionType.swift | 1 | 1119 | //
// FunctionType.swift
// KakaJSON
//
// Created by MJ Lee on 2019/8/1.
// Copyright © 2019 MJ Lee. All rights reserved.
//
public class FunctionType: BaseType, LayoutType {
private(set) var layout: UnsafeMutablePointer<FunctionLayout>!
public private(set) var `throws`: Bool = false
public private(set) var returnType: Any.Type = Any.self
public private(set) var argumentTypes: [Any.Type]?
override func build() {
super.build()
layout = builtLayout()
`throws` = (layout.pointee.flags & 0x01000000) != 0
returnType = layout.pointee.parameters.item(0)
let argumentsCount = layout.pointee.flags & 0x00FFFFFF
guard argumentsCount > 0 else { return }
var arr = [Any.Type]()
for i in 1...argumentsCount {
arr.append(layout.pointee.parameters.item(i))
}
argumentTypes = arr
}
override public var description: String {
return "\(name) { kind = \(kind), argumentTypes = \(argumentTypes ?? []), returnType = \(returnType), throws = \(`throws`) }"
}
}
| mit | ce4ce0d8be3c1c505e6927178773d688 | 30.942857 | 133 | 0.609123 | 4.125461 | false | false | false | false |
xcodeswift/xcproj | Tests/XcodeProjTests/Utils/PBXBatchUpdaterTests.swift | 1 | 7087 | import Foundation
import PathKit
import XCTest
@testable import XcodeProj
class PBXBatchUpdaterTests: XCTestCase {
func test_addFile_useMainProjectGroup() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(fileName)")
try createFile(at: filePath)
let file = try updater.addFile(to: project, at: filePath)
let fileFullPath = try file.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
fileFullPath,
filePath
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, 1)
}
func test_addFile_withSubgroups() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
let subgroupNames = (0 ... 5).map { _ in UUID().uuidString }
let expectedGroupCount = 1 + subgroupNames.count
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let subgroupPath = subgroupNames.joined(separator: "/")
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(subgroupPath)/\(fileName)")
try createFile(at: filePath)
let file = try updater.addFile(to: project, at: filePath)
let fileFullPath = try file.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
fileFullPath,
filePath
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, expectedGroupCount)
}
func test_addFile_byFileName() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
let mainGroup = project.mainGroup!
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(fileName)")
try createFile(at: filePath)
let file = try updater.addFile(to: mainGroup, fileName: fileName)
let fileFullPath = try file.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
fileFullPath,
filePath
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, 1)
}
func test_addFile_alreadyExisted() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
let mainGroup = project.mainGroup!
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(fileName)")
try createFile(at: filePath)
let firstFile = try updater.addFile(to: project, at: filePath)
let secondFile = try updater.addFile(to: mainGroup, fileName: fileName)
let firstFileFullPath = try firstFile.fullPath(sourceRoot: sourceRoot)
let secondFileFullPath = try secondFile.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
firstFileFullPath,
filePath
)
XCTAssertEqual(
secondFileFullPath,
filePath
)
XCTAssertEqual(
firstFile,
secondFile
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, 1)
}
func test_addFile_alreadyExistedWithSubgroups() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
let subgroupNames = (0 ... 5).map { _ in UUID().uuidString }
let expectedGroupCount = 1 + subgroupNames.count
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let subgroupPath = subgroupNames.joined(separator: "/")
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(subgroupPath)/\(fileName)")
try createFile(at: filePath)
let firstFile = try updater.addFile(to: project, at: filePath)
let parentGroup = proj.groups.first(where: { $0.path == subgroupNames.last! })!
let secondFile = try updater.addFile(to: parentGroup, fileName: fileName)
let firstFileFullPath = try firstFile.fullPath(sourceRoot: sourceRoot)
let secondFileFullPath = try secondFile.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
firstFileFullPath,
filePath
)
XCTAssertEqual(
secondFileFullPath,
filePath
)
XCTAssertEqual(
firstFile,
secondFile
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, expectedGroupCount)
}
private func fillAndCreateProj(sourceRoot _: Path, mainGroupPath: String) -> PBXProj {
let proj = PBXProj.fixture()
let fileref = PBXFileReference(sourceTree: .group,
fileEncoding: 1,
explicitFileType: "sourcecode.swift",
lastKnownFileType: nil,
path: "path")
proj.add(object: fileref)
let group = PBXGroup(children: [fileref],
sourceTree: .group,
name: "group",
path: mainGroupPath)
proj.add(object: group)
let project = PBXProject.fixture(mainGroup: group)
proj.add(object: project)
return proj
}
private func createFile(at filePath: Path) throws {
let directoryURL = filePath.url.deletingLastPathComponent()
try FileManager.default.createDirectory(
at: directoryURL,
withIntermediateDirectories: true
)
try Data().write(to: filePath.url)
}
}
| mit | cd053351ac7e407676285d3f24b8b70a | 37.93956 | 99 | 0.583039 | 5.567164 | false | false | false | false |
SolarSwiftem/solarswiftem.github.io | solutions/swift/Answers6/Answers6/main.swift | 1 | 546 | import Foundation
//1
func myName() {
print("Nadia")
}
for var i = 0; i < 20; i++ {
myName()
}
//2
func addThreeNumbers(n1: Int, n2: Int, n3: Int) -> Int {
return n1 + n2 + n3
}
print(addThreeNumbers(123, n2: 321, n3: 231))
//3
func numbers1To100() -> [Int] {
var array = [Int]()
for var i = 1; i <= 100; i++ {
array.append(i)
}
return array
}
func arrayTimes4(array: [Int]) -> [Int] {
var fours = [Int]()
for i in array {
fours.append(i * 4)
}
return fours
}
var fourTimes = arrayTimes4(numbers1To100())
print(fourTimes) | apache-2.0 | 8c8fb58ffa281ce217e6e115c6ba1aa7 | 12.675 | 56 | 0.600733 | 2.323404 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.