repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jalehman/rottentomatoes
|
refs/heads/master
|
RottenTomatoes/MovieDetailViewController.swift
|
gpl-2.0
|
1
|
//
// MovieDetailViewController.swift
// RottenTomatoes
//
// Created by Josh Lehman on 2/5/15.
// Copyright (c) 2015 Josh Lehman. All rights reserved.
//
import UIKit
import Bond
class MovieDetailViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var posterImageView: UIImageView!
@IBOutlet weak var detailsView: UIView!
@IBOutlet weak var detailsViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var criticScoreLabel: UILabel!
@IBOutlet weak var audienceScoreLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var synopsisTextView: UITextView!
private var showFullDetails: Bool = false
private let viewModel: MovieViewModel
private let BOTTOM_CONSTRAINT_OFFSET: CGFloat = -300.0
init(viewModel: MovieViewModel) {
self.viewModel = viewModel
super.init(nibName: "MovieDetailViewController", bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
detailsViewBottomConstraint.constant = BOTTOM_CONSTRAINT_OFFSET
bindViewModel()
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBar.alpha = 0.95
}
@IBAction func detailsSwipeUp(sender: AnyObject) {
if !showFullDetails {
detailsViewBottomConstraint.constant = 0
UIView.animateWithDuration(0.5, animations: {
self.view.layoutIfNeeded()
})
showFullDetails = true
}
}
@IBAction func detailsSwipeDown(sender: AnyObject) {
if showFullDetails {
detailsViewBottomConstraint.constant = BOTTOM_CONSTRAINT_OFFSET
UIView.animateWithDuration(0.5, animations: {
self.view.layoutIfNeeded()
})
showFullDetails = false
}
}
func bindViewModel() {
self.title = viewModel.title
self.titleLabel.text = "\(viewModel.title) (\(viewModel.year))"
self.criticScoreLabel.text = "Critics Score: \(viewModel.criticScore)"
self.audienceScoreLabel.text = "Audience Score: \(viewModel.audienceScore)"
synopsisTextView.text = viewModel.synopsis
ratingLabel.text = viewModel.rating
// Definitely the easiest way to do this.
posterImageView.setImageWithURL(viewModel.thumbnailURL)
posterImageView.setImageWithURL(viewModel.imageURL)
}
}
|
b0d9cd451ec6b20c19f7c1900955ad0f
| 30.654762 | 83 | 0.657014 | false | false | false | false |
pennlabs/penn-mobile-ios
|
refs/heads/main
|
PennMobile/More Tab/PAC Code/PacCodeNetworkManager.swift
|
mit
|
1
|
//
// PacCodeNetworkManager.swift
// PennMobile
//
// Created by CHOI Jongmin on 1/3/2020.
// Copyright © 2020 PennLabs. All rights reserved.
//
import SwiftSoup
class PacCodeNetworkManager {
static let instance = PacCodeNetworkManager()
private init() {}
}
extension PacCodeNetworkManager: PennAuthRequestable {
private var pacURL: String {
return "https://penncard.apps.upenn.edu/penncard/jsp/fast2.do?fastStart=pacExpress"
}
private var shibbolethUrl: String {
return "https://penncard.apps.upenn.edu/penncard/jsp/fast2.do/Shibboleth.sso/SAML2/POST"
}
func getPacCode(callback: @escaping (_ result: Result<String, NetworkingError>) -> Void ) {
makeAuthRequest(targetUrl: pacURL, shibbolethUrl: shibbolethUrl) { (data, _, error) in
guard let data = data, let html = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else {
if let error = error as? NetworkingError {
callback(.failure(error))
} else {
callback(.failure(.other))
}
return
}
do {
let pacCode = try self.findPacCode(from: html as String)
return callback(.success(pacCode))
} catch {
return callback(.failure(.parsingError))
}
}
}
private func findPacCode(from html: String) throws -> String {
let doc: Document = try SwiftSoup.parse(html)
guard let element: Element = try doc.getElementsByClass("msgbody").first() else {
throw NetworkingError.parsingError
}
// Stores ["Name", name in caps, "PennId", Penn ID, "Current PAC", PAC Code]
var identity = [String]()
do {
for row in try element.select("tr") {
for col in try row.select("td") {
let colContent = try col.text()
identity.append(colContent)
}
}
} catch {
throw NetworkingError.parsingError
}
// PAC Code is stored in the 5th index of the array
if identity.count == 6 {
return identity[5]
} else {
throw NetworkingError.parsingError
}
}
}
|
d240182121f3263b5c07c99da3bafa67
| 29.447368 | 114 | 0.569576 | false | false | false | false |
banxi1988/BXPopover
|
refs/heads/master
|
Example/Pods/BXModel/Pod/Classes/SimpleTableViewAdapter.swift
|
mit
|
1
|
//
// SimpleTableViewAdapter.swift
// Youjia
//
// Created by Haizhen Lee on 15/11/11.
// Copyright © 2015年 xiyili. All rights reserved.
//
import UIKit
public class BXBasicItemTableViewCell:UITableViewCell{
public class var cellStyle : UITableViewCellStyle{
return .Default
}
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: self.dynamicType.cellStyle, reuseIdentifier: reuseIdentifier)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public class BXBasicItemValue1TableViewCell:BXBasicItemTableViewCell{
public static override var cellStyle : UITableViewCellStyle{
return .Value1
}
}
public class BXBasicItemValue2TableViewCell:BXBasicItemTableViewCell{
public static override var cellStyle : UITableViewCellStyle{
return .Value2
}
}
public class BXBasicItemSubtitleTableViewCell:BXBasicItemTableViewCell{
public static override var cellStyle : UITableViewCellStyle{
return .Subtitle
}
}
extension BXBasicItemTableViewCell:BXBindable{
public func bind(item:BXBasicItemAware){
textLabel?.text = item.bx_text
detailTextLabel?.text = item.bx_detailText
}
}
public class SimpleTableViewAdapter<T:BXBasicItemAware>:SimpleGenericTableViewAdapter<T,BXBasicItemTableViewCell>{
public let cellStyle:UITableViewCellStyle
public var cellAccessoryType:UITableViewCellAccessoryType = .None
public init(tableView: UITableView, items: [T] = [], cellStyle:UITableViewCellStyle = .Value2) {
self.cellStyle = cellStyle
super.init(tableView: tableView, items: items)
tableView.registerClass(cellClass, forCellReuseIdentifier: reuseIdentifier)
}
var cellClass:BXBasicItemTableViewCell.Type{
switch cellStyle{
case .Default:return BXBasicItemTableViewCell.self
case .Value1:return BXBasicItemValue1TableViewCell.self
case .Value2:return BXBasicItemValue2TableViewCell.self
case .Subtitle:return BXBasicItemSubtitleTableViewCell.self
}
}
public override func configureCell(cell: BXBasicItemTableViewCell , atIndexPath indexPath: NSIndexPath) {
cell.accessoryType = cellAccessoryType
super.configureCell(cell, atIndexPath: indexPath)
}
}
|
52609c027f50e3ccc06886d1be3b0d46
| 31.093333 | 114 | 0.73483 | false | false | false | false |
ifyoudieincanada/above-average
|
refs/heads/master
|
above-average/CourseViewController.swift
|
gpl-3.0
|
1
|
//
// CourseViewController.swift
// above-average
//
// Created by Kyra Drake on 1/15/16.
// Copyright © 2016 Kyra Drake. All rights reserved.
//
import UIKit
class CourseViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var courseMenuButton: UIBarButtonItem!
@IBOutlet weak var courseIdentifierLabel: UILabel!
@IBOutlet weak var courseNameLabel: UILabel!
@IBOutlet weak var courseAverageLabel: UILabel!
@IBOutlet weak var courseAssignmentsTable: UITableView!
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return semesterArray[semesterArrayIndex].courses[courseIndex].assignments.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.textLabel?.text = semesterArray[semesterArrayIndex].courses[courseIndex].assignments[indexPath.row].name + " " + String(semesterArray[semesterArrayIndex].courses[courseIndex].assignments[indexPath.row].percentage)
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
courseIdentifierLabel.text = semesterArray[semesterArrayIndex].courses[courseIndex].identifier
courseNameLabel.text = semesterArray[semesterArrayIndex].courses[courseIndex].name
courseAverageLabel.text = String(semesterArray[semesterArrayIndex].courses[courseIndex].overallPercent)
/*
if self.revealViewController() != nil {
courseMenuButton.target = self.revealViewController()
courseMenuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
f46c5cf315e5125af1957010c536d54d
| 33.046875 | 227 | 0.689307 | false | false | false | false |
Dylan-Feng/PitchPerfect
|
refs/heads/master
|
PitchPerfect/PlaySoundsViewController+Audio.swift
|
gpl-3.0
|
1
|
//
// playSoundsViewController+Audio.swift
// PitchPerfect
//
// Copyright © 2016 Udacity. All rights reserved.
//
import UIKit
import AVFoundation
// MARK: - PlaySoundsViewController: AVAudioPlayerDelegate
extension playSoundsViewController: AVAudioPlayerDelegate {
// MARK: Alerts
struct Alerts {
static let DismissAlert = "Dismiss"
static let RecordingDisabledTitle = "Recording Disabled"
static let RecordingDisabledMessage = "You've disabled this app from recording your microphone. Check Settings."
static let RecordingFailedTitle = "Recording Failed"
static let RecordingFailedMessage = "Something went wrong with your recording."
static let AudioRecorderError = "Audio Recorder Error"
static let AudioSessionError = "Audio Session Error"
static let AudioRecordingError = "Audio Recording Error"
static let AudioFileError = "Audio File Error"
static let AudioEngineError = "Audio Engine Error"
}
// MARK: PlayingState (raw values correspond to sender tags)
enum PlayingState { case playing, notPlaying }
// MARK: Audio Functions
func setupAudio() {
// initialize (recording) audio file
do {
audioFile = try AVAudioFile(forReading: recordedAudioURL as URL)
} catch {
showAlert(Alerts.AudioFileError, message: String(describing: error))
}
}
func playSound(rate: Float? = nil, pitch: Float? = nil, echo: Bool = false, reverb: Bool = false) {
// initialize audio engine components
audioEngine = AVAudioEngine()
// node for playing audio
audioPlayerNode = AVAudioPlayerNode()
audioEngine.attach(audioPlayerNode)
// node for adjusting rate/pitch
let changeRatePitchNode = AVAudioUnitTimePitch()
if let pitch = pitch {
changeRatePitchNode.pitch = pitch
}
if let rate = rate {
changeRatePitchNode.rate = rate
}
audioEngine.attach(changeRatePitchNode)
// node for echo
let echoNode = AVAudioUnitDistortion()
echoNode.loadFactoryPreset(.multiEcho1)
audioEngine.attach(echoNode)
// node for reverb
let reverbNode = AVAudioUnitReverb()
reverbNode.loadFactoryPreset(.cathedral)
reverbNode.wetDryMix = 50
audioEngine.attach(reverbNode)
// connect nodes
if echo == true && reverb == true {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, echoNode, reverbNode, audioEngine.outputNode)
} else if echo == true {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, echoNode, audioEngine.outputNode)
} else if reverb == true {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, reverbNode, audioEngine.outputNode)
} else {
connectAudioNodes(audioPlayerNode, changeRatePitchNode, audioEngine.outputNode)
}
// schedule to play and start the engine!
audioPlayerNode.stop()
audioPlayerNode.scheduleFile(audioFile, at: nil) {
var delayInSeconds: Double = 0
if let lastRenderTime = self.audioPlayerNode.lastRenderTime, let playerTime = self.audioPlayerNode.playerTime(forNodeTime: lastRenderTime) {
if let rate = rate {
delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate) / Double(rate)
} else {
delayInSeconds = Double(self.audioFile.length - playerTime.sampleTime) / Double(self.audioFile.processingFormat.sampleRate)
}
}
// schedule a stop timer for when audio finishes playing
self.stopTimer = Timer(timeInterval: delayInSeconds, target: self, selector: #selector(playSoundsViewController.stopAudio), userInfo: nil, repeats: false)
RunLoop.main.add(self.stopTimer!, forMode: RunLoopMode.defaultRunLoopMode)
}
do {
try audioEngine.start()
} catch {
showAlert(Alerts.AudioEngineError, message: String(describing: error))
return
}
// play the recording!
audioPlayerNode.play()
}
func stopAudio() {
if let audioPlayerNode = audioPlayerNode {
audioPlayerNode.stop()
}
if let stopTimer = stopTimer {
stopTimer.invalidate()
}
configureUI(.notPlaying)
if let audioEngine = audioEngine {
audioEngine.stop()
audioEngine.reset()
}
}
// MARK: Connect List of Audio Nodes
func connectAudioNodes(_ nodes: AVAudioNode...) {
for x in 0..<nodes.count-1 {
audioEngine.connect(nodes[x], to: nodes[x+1], format: audioFile.processingFormat)
}
}
// MARK: UI Functions
func configureUI(_ playState: PlayingState) {
switch(playState) {
case .playing:
setPlayButtonsEnabled(false)
stopButton.isEnabled = true
case .notPlaying:
setPlayButtonsEnabled(true)
stopButton.isEnabled = false
}
}
func setPlayButtonsEnabled(_ enabled: Bool) {
slowButton.isEnabled = enabled
HighPitchButton.isEnabled = enabled
fastButton.isEnabled = enabled
LowPitchButton.isEnabled = enabled
echoButton.isEnabled = enabled
reverbButton.isEnabled = enabled
}
func showAlert(_ title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Alerts.DismissAlert, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
|
49b14270bbc5be42ff40e9a8d5157b33
| 34.852941 | 166 | 0.61936 | false | false | false | false |
jlecomte/EarthquakeTracker
|
refs/heads/master
|
EarthquakeTracker/Seismometer/SeismoModel.swift
|
mit
|
1
|
//
// SeismoModel.swift
// EarthquakeTracker
//
// Created by Andrew Folta on 10/11/14.
// Copyright (c) 2014 Andrew Folta. All rights reserved.
//
import UIKit
import CoreMotion
let SEISMO_UPDATE_INTERVAL = 1.0 / 20.0
@objc protocol SeismoModelDelegate {
func reportMagnitude(magnitude: Double)
func reportNoAccelerometer()
}
@objc class SeismoModel {
var delegate: SeismoModelDelegate?
init() {}
// start listening for seismic activity
func start() {
var first = true
if motionManager == nil {
motionManager = CMMotionManager()
}
if !motionManager!.accelerometerAvailable {
delegate?.reportNoAccelerometer()
return
}
motionManager!.accelerometerUpdateInterval = SEISMO_UPDATE_INTERVAL
motionManager!.startAccelerometerUpdatesToQueue(NSOperationQueue(), withHandler: {
(data: CMAccelerometerData?, error: NSError?) -> Void in
if error != nil {
// FUTURE -- handle error
self.motionManager!.stopAccelerometerUpdates()
}
if data != nil {
var magnitude = sqrt(
(data!.acceleration.x * data!.acceleration.x) +
(data!.acceleration.y * data!.acceleration.y) +
(data!.acceleration.z * data!.acceleration.z)
)
if first {
self.lastMagnitude = magnitude
first = false
}
dispatch_async(dispatch_get_main_queue(), {
self.delegate?.reportMagnitude(magnitude - self.lastMagnitude)
self.lastMagnitude = magnitude
})
}
})
}
// stop listening for seismic activity
func stop() {
motionManager?.stopAccelerometerUpdates()
}
private var motionManager: CMMotionManager?
private var lastMagnitude = 0.0
}
|
17922c83f46d5f23e7e1562e281e3e4a
| 27.342857 | 90 | 0.572077 | false | false | false | false |
almazrafi/Metatron
|
refs/heads/master
|
Tests/MetatronTests/MPEG/MPEGXingHeaderTest.swift
|
mit
|
1
|
//
// MPEGXingHeaderTest.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// 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 XCTest
@testable import Metatron
extension MPEGXingHeader {
// MARK: Initializers
fileprivate init?(fromData data: [UInt8], range: inout Range<UInt64>) {
let stream = MemoryStream(data: data)
guard stream.openForReading() else {
return nil
}
self.init(fromStream: stream, range: &range)
}
}
class MPEGXingHeaderTest: XCTestCase {
// MARK: Instance Methods
func testCaseA() {
var header = MPEGXingHeader()
XCTAssert(!header.isValid)
header.bitRateMode = MPEGBitRateMode.variable
header.framesCount = 123
header.bytesCount = 123
header.tableOfContent = Array<UInt8>(repeating: 123, count: 100)
header.quality = 123
XCTAssert(header.isValid)
guard let data = header.toData() else {
return XCTFail()
}
XCTAssert(!data.isEmpty)
let prefixData = Array<UInt8>(repeating: 123, count: 123)
let suffixData = Array<UInt8>(repeating: 231, count: 231)
var range = Range<UInt64>(123..<(123 + UInt64(data.count)))
guard let otherHeader = MPEGXingHeader(fromData: prefixData + data + suffixData, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 123)
XCTAssert(range.upperBound == 123 + UInt64(data.count))
XCTAssert(otherHeader.isValid)
XCTAssert(otherHeader.bitRateMode == header.bitRateMode)
XCTAssert(otherHeader.framesCount == header.framesCount!)
XCTAssert(otherHeader.bytesCount == header.bytesCount!)
guard let otherTableOfContent = otherHeader.tableOfContent else {
return XCTFail()
}
XCTAssert(otherTableOfContent == header.tableOfContent!)
XCTAssert(otherHeader.quality == header.quality!)
}
func testCaseB() {
var header = MPEGXingHeader()
XCTAssert(!header.isValid)
header.bitRateMode = MPEGBitRateMode.constant
header.framesCount = 123
header.bytesCount = 123
header.tableOfContent = Array<UInt8>(repeating: 123, count: 100)
header.quality = 0
XCTAssert(header.isValid)
guard let data = header.toData() else {
return XCTFail()
}
XCTAssert(!data.isEmpty)
let prefixData = Array<UInt8>(repeating: 123, count: 123)
let suffixData = Array<UInt8>(repeating: 231, count: 231)
var range = Range<UInt64>(123..<(354 + UInt64(data.count)))
guard let otherHeader = MPEGXingHeader(fromData: prefixData + data + suffixData, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 123)
XCTAssert(range.upperBound == 123 + UInt64(data.count))
XCTAssert(otherHeader.isValid)
XCTAssert(otherHeader.bitRateMode == header.bitRateMode)
XCTAssert(otherHeader.framesCount == header.framesCount!)
XCTAssert(otherHeader.bytesCount == header.bytesCount!)
guard let otherTableOfContent = otherHeader.tableOfContent else {
return XCTFail()
}
XCTAssert(otherTableOfContent == header.tableOfContent!)
XCTAssert(otherHeader.quality == header.quality!)
}
func testCaseC() {
var header = MPEGXingHeader()
XCTAssert(!header.isValid)
header.bitRateMode = MPEGBitRateMode.variable
header.framesCount = 1
header.bytesCount = 1
header.tableOfContent = Array<UInt8>(repeating: 123, count: 100)
header.quality = 123
XCTAssert(header.isValid)
guard let data = header.toData() else {
return XCTFail()
}
XCTAssert(!data.isEmpty)
guard let otherHeader = MPEGXingHeader(fromData: data) else {
return XCTFail()
}
XCTAssert(otherHeader.isValid)
XCTAssert(otherHeader.bitRateMode == header.bitRateMode)
XCTAssert(otherHeader.framesCount == header.framesCount!)
XCTAssert(otherHeader.bytesCount == header.bytesCount!)
guard let otherTableOfContent = otherHeader.tableOfContent else {
return XCTFail()
}
XCTAssert(otherTableOfContent == header.tableOfContent!)
XCTAssert(otherHeader.quality == header.quality!)
}
func testCaseD() {
var header = MPEGXingHeader()
XCTAssert(!header.isValid)
header.bitRateMode = MPEGBitRateMode.variable
header.framesCount = nil
header.bytesCount = nil
header.tableOfContent = nil
header.quality = nil
XCTAssert(header.isValid)
guard let data = header.toData() else {
return XCTFail()
}
XCTAssert(!data.isEmpty)
guard let otherHeader = MPEGXingHeader(fromData: data) else {
return XCTFail()
}
XCTAssert(otherHeader.isValid)
XCTAssert(otherHeader.bitRateMode == header.bitRateMode)
XCTAssert(otherHeader.framesCount == nil)
XCTAssert(otherHeader.bytesCount == nil)
XCTAssert(otherHeader.tableOfContent == nil)
XCTAssert(otherHeader.quality == nil)
}
func testCaseE() {
var header = MPEGXingHeader()
XCTAssert(!header.isValid)
header.bitRateMode = MPEGBitRateMode.constant
header.framesCount = nil
header.bytesCount = nil
header.tableOfContent = nil
header.quality = nil
XCTAssert(!header.isValid)
XCTAssert(header.toData() == nil)
}
func testCaseF() {
var header = MPEGXingHeader()
XCTAssert(!header.isValid)
header.bitRateMode = MPEGBitRateMode.variable
header.framesCount = 123
header.bytesCount = 123
header.tableOfContent = [1, 2, 3]
header.quality = 123
XCTAssert(!header.isValid)
XCTAssert(header.toData() == nil)
}
func testCaseG() {
var header = MPEGXingHeader()
XCTAssert(!header.isValid)
header.bitRateMode = MPEGBitRateMode.variable
header.framesCount = 0
header.bytesCount = 0
header.tableOfContent = Array<UInt8>(repeating: 123, count: 100)
header.quality = 123
XCTAssert(!header.isValid)
XCTAssert(header.toData() == nil)
}
}
|
3ba182e63f06c43171f81726c946d31c
| 25.459649 | 110 | 0.643018 | false | false | false | false |
seyton/2048
|
refs/heads/master
|
NumberTiles/Views/TileView.swift
|
mit
|
1
|
//
// TileView.swift
// NumberTiles
//
// Created by Wesley Matlock on 11/25/15.
// Copyright © 2015 insoc.net. All rights reserved.
//
import UIKit
class TileView: UIView {
var value: Int = 0 {
didSet {
backgroundColor = appearanceDelegate.tileColor(value)
}
}
unowned let appearanceDelegate: AppearanceProviderProtocol
let numberLabel: UILabel
init(position: CGPoint, width: CGFloat, value v: Int, radius: CGFloat, appearanceDelegate d: AppearanceProviderProtocol) {
appearanceDelegate = d
numberLabel = UILabel(frame: CGRectMake(0, 0, width, width))
numberLabel.textAlignment = .Center
numberLabel.minimumScaleFactor = 0.5
numberLabel.font = appearanceDelegate.fontForNumbers()
super.init(frame: CGRectMake(position.x, position.y, width, width))
addSubview(numberLabel)
layer.cornerRadius = radius
value = v
backgroundColor = appearanceDelegate.tileColor(value)
numberLabel.textColor = appearanceDelegate.numberColor(value)
numberLabel.text = "\(value)"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
6c6c8d24ec1bcc5ea21b2a6280097215
| 26.021277 | 126 | 0.651181 | false | false | false | false |
Ares42/Portfolio
|
refs/heads/dev
|
ARHome/Pods/SwiftyJSON/Source/SwiftyJSON.swift
|
apache-2.0
|
21
|
// SwiftyJSON.swift
//
// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang
//
// 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
// MARK: - Error
// swiftlint:disable line_length
/// Error domain
@available(*, deprecated, message: "ErrorDomain is deprecated. Use `SwiftyJSONError.errorDomain` instead.", renamed: "SwiftyJSONError.errorDomain")
public let ErrorDomain: String = "SwiftyJSONErrorDomain"
/// Error code
@available(*, deprecated, message: "ErrorUnsupportedType is deprecated. Use `SwiftyJSONError.unsupportedType` instead.", renamed: "SwiftyJSONError.unsupportedType")
public let ErrorUnsupportedType: Int = 999
@available(*, deprecated, message: "ErrorIndexOutOfBounds is deprecated. Use `SwiftyJSONError.indexOutOfBounds` instead.", renamed: "SwiftyJSONError.indexOutOfBounds")
public let ErrorIndexOutOfBounds: Int = 900
@available(*, deprecated, message: "ErrorWrongType is deprecated. Use `SwiftyJSONError.wrongType` instead.", renamed: "SwiftyJSONError.wrongType")
public let ErrorWrongType: Int = 901
@available(*, deprecated, message: "ErrorNotExist is deprecated. Use `SwiftyJSONError.notExist` instead.", renamed: "SwiftyJSONError.notExist")
public let ErrorNotExist: Int = 500
@available(*, deprecated, message: "ErrorInvalidJSON is deprecated. Use `SwiftyJSONError.invalidJSON` instead.", renamed: "SwiftyJSONError.invalidJSON")
public let ErrorInvalidJSON: Int = 490
public enum SwiftyJSONError: Int, Swift.Error {
case unsupportedType = 999
case indexOutOfBounds = 900
case elementTooDeep = 902
case wrongType = 901
case notExist = 500
case invalidJSON = 490
}
extension SwiftyJSONError: CustomNSError {
/// return the error domain of SwiftyJSONError
public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" }
/// return the error code of SwiftyJSONError
public var errorCode: Int { return self.rawValue }
/// return the userInfo of SwiftyJSONError
public var errorUserInfo: [String: Any] {
switch self {
case .unsupportedType:
return [NSLocalizedDescriptionKey: "It is an unsupported type."]
case .indexOutOfBounds:
return [NSLocalizedDescriptionKey: "Array Index is out of bounds."]
case .wrongType:
return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]
case .notExist:
return [NSLocalizedDescriptionKey: "Dictionary key does not exist."]
case .invalidJSON:
return [NSLocalizedDescriptionKey: "JSON is invalid."]
case .elementTooDeep:
return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."]
}
}
}
// MARK: - JSON Type
/**
JSON's type definitions.
See http://www.json.org
*/
public enum Type: Int {
case number
case string
case bool
case array
case dictionary
case null
case unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `[]` by default.
- returns: The created JSON
*/
public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws {
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(jsonObject: object)
}
/**
Creates a JSON object
- note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)`
- parameter object: the object
- returns: the created JSON object
*/
public init(_ object: Any) {
switch object {
case let object as Data:
do {
try self.init(data: object)
} catch {
self.init(jsonObject: NSNull())
}
default:
self.init(jsonObject: object)
}
}
/**
Parses the JSON string into a JSON object
- parameter json: the JSON string
- returns: the created JSON object
*/
public init(parseJSON jsonString: String) {
if let data = jsonString.data(using: .utf8) {
self.init(data)
} else {
self.init(NSNull())
}
}
/**
Creates a JSON from JSON string
- parameter json: Normal json string like '{"a":"b"}'
- returns: The created JSON
*/
@available(*, deprecated, message: "Use instead `init(parseJSON: )`")
public static func parse(_ json: String) -> JSON {
return json.data(using: String.Encoding.utf8)
.flatMap { try? JSON(data: $0) } ?? JSON(NSNull())
}
/**
Creates a JSON using the object.
- parameter jsonObject: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
fileprivate init(jsonObject: Any) {
self.object = jsonObject
}
/**
Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONs getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
*/
public mutating func merge(with other: JSON) throws {
try self.merge(with: other, typecheck: true)
}
/**
Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONS getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
- returns: New merged JSON
*/
public func merged(with other: JSON) throws -> JSON {
var merged = self
try merged.merge(with: other, typecheck: true)
return merged
}
/**
Private woker function which does the actual merging
Typecheck is set to true for the first recursion level to prevent total override of the source JSON
*/
fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws {
if self.type == other.type {
switch self.type {
case .dictionary:
for (key, _) in other {
try self[key].merge(with: other[key], typecheck: false)
}
case .array:
self = JSON(self.arrayValue + other.arrayValue)
default:
self = other
}
} else {
if typecheck {
throw SwiftyJSONError.wrongType
} else {
self = other
}
}
}
/// Private object
fileprivate var rawArray: [Any] = []
fileprivate var rawDictionary: [String: Any] = [:]
fileprivate var rawString: String = ""
fileprivate var rawNumber: NSNumber = 0
fileprivate var rawNull: NSNull = NSNull()
fileprivate var rawBool: Bool = false
/// JSON type, fileprivate setter
public fileprivate(set) var type: Type = .null
/// Error in JSON, fileprivate setter
public fileprivate(set) var error: SwiftyJSONError?
/// Object in JSON
public var object: Any {
get {
switch self.type {
case .array:
return self.rawArray
case .dictionary:
return self.rawDictionary
case .string:
return self.rawString
case .number:
return self.rawNumber
case .bool:
return self.rawBool
default:
return self.rawNull
}
}
set {
error = nil
switch unwrap(newValue) {
case let number as NSNumber:
if number.isBool {
type = .bool
self.rawBool = number.boolValue
} else {
type = .number
self.rawNumber = number
}
case let string as String:
type = .string
self.rawString = string
case _ as NSNull:
type = .null
case nil:
type = .null
case let array as [Any]:
type = .array
self.rawArray = array
case let dictionary as [String: Any]:
type = .dictionary
self.rawDictionary = dictionary
default:
type = .unknown
error = SwiftyJSONError.unsupportedType
}
}
}
/// The static null JSON
@available(*, unavailable, renamed:"null")
public static var nullJSON: JSON { return null }
public static var null: JSON { return JSON(NSNull()) }
}
/// Private method to unwarp an object recursively
private func unwrap(_ object: Any) -> Any {
switch object {
case let json as JSON:
return unwrap(json.object)
case let array as [Any]:
return array.map(unwrap)
case let dictionary as [String: Any]:
var unwrappedDic = dictionary
for (k, v) in dictionary {
unwrappedDic[k] = unwrap(v)
}
return unwrappedDic
default:
return object
}
}
public enum Index<T: Any>: Comparable {
case array(Int)
case dictionary(DictionaryIndex<String, T>)
case null
static public func == (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)):
return left == right
case (.dictionary(let left), .dictionary(let right)):
return left == right
case (.null, .null): return true
default:
return false
}
}
static public func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)):
return left < right
case (.dictionary(let left), .dictionary(let right)):
return left < right
default:
return false
}
}
}
public typealias JSONIndex = Index<JSON>
public typealias JSONRawIndex = Index<Any>
extension JSON: Swift.Collection {
public typealias Index = JSONRawIndex
public var startIndex: Index {
switch type {
case .array:
return .array(rawArray.startIndex)
case .dictionary:
return .dictionary(rawDictionary.startIndex)
default:
return .null
}
}
public var endIndex: Index {
switch type {
case .array:
return .array(rawArray.endIndex)
case .dictionary:
return .dictionary(rawDictionary.endIndex)
default:
return .null
}
}
public func index(after i: Index) -> Index {
switch i {
case .array(let idx):
return .array(rawArray.index(after: idx))
case .dictionary(let idx):
return .dictionary(rawDictionary.index(after: idx))
default:
return .null
}
}
public subscript (position: Index) -> (String, JSON) {
switch position {
case .array(let idx):
return (String(idx), JSON(self.rawArray[idx]))
case .dictionary(let idx):
let (key, value) = self.rawDictionary[idx]
return (key, JSON(value))
default:
return ("", JSON.null)
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public enum JSONKey {
case index(Int)
case key(String)
}
public protocol JSONSubscriptType {
var jsonKey: JSONKey { get }
}
extension Int: JSONSubscriptType {
public var jsonKey: JSONKey {
return JSONKey.index(self)
}
}
extension String: JSONSubscriptType {
public var jsonKey: JSONKey {
return JSONKey.key(self)
}
}
extension JSON {
/// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error.
fileprivate subscript(index index: Int) -> JSON {
get {
if self.type != .array {
var r = JSON.null
r.error = self.error ?? SwiftyJSONError.wrongType
return r
} else if self.rawArray.indices.contains(index) {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r.error = SwiftyJSONError.indexOutOfBounds
return r
}
}
set {
if self.type == .array &&
self.rawArray.indices.contains(index) &&
newValue.error == nil {
self.rawArray[index] = newValue.object
}
}
}
/// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error.
fileprivate subscript(key key: String) -> JSON {
get {
var r = JSON.null
if self.type == .dictionary {
if let o = self.rawDictionary[key] {
r = JSON(o)
} else {
r.error = SwiftyJSONError.notExist
}
} else {
r.error = self.error ?? SwiftyJSONError.wrongType
}
return r
}
set {
if self.type == .dictionary && newValue.error == nil {
self.rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
fileprivate subscript(sub sub: JSONSubscriptType) -> JSON {
get {
switch sub.jsonKey {
case .index(let index): return self[index: index]
case .key(let key): return self[key: key]
}
}
set {
switch sub.jsonKey {
case .index(let index): self[index: index] = newValue
case .key(let key): self[key: key] = newValue
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
Example:
```
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
```
The same as: let name = json[9]["list"]["person"]["name"]
- parameter path: The target json's path.
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0:
return
case 1:
self[sub:path[0]].object = newValue.object
default:
var aPath = path
aPath.remove(at: 0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Any)...) {
var dictionary = [String: Any](minimumCapacity: elements.count)
for (k, v) in elements {
dictionary[k] = v
}
self.init(dictionary as Any)
}
}
extension JSON: Swift.ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Any...) {
self.init(elements as Any)
}
}
extension JSON: Swift.ExpressibleByNilLiteral {
@available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions")
public init(nilLiteral: ()) {
self.init(NSNull() as Any)
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: Any) {
if JSON(rawValue).type == .unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: Any {
return self.object
}
public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data {
guard JSONSerialization.isValidJSONObject(self.object) else {
throw SwiftyJSONError.invalidJSON
}
return try JSONSerialization.data(withJSONObject: self.object, options: opt)
}
public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? {
do {
return try _rawString(encoding, options: [.jsonSerialization: opt])
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
public func rawString(_ options: [writingOptionsKeys: Any]) -> String? {
let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8
let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10
do {
return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth)
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? {
guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON }
switch self.type {
case .dictionary:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try self.rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let dict = self.object as? [String: Any?] else {
return nil
}
let body = try dict.keys.map { key throws -> String in
guard let value = dict[key] else {
return "\"\(key)\": null"
}
guard let unwrappedValue = value else {
return "\"\(key)\": null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw SwiftyJSONError.elementTooDeep
}
if nestedValue.type == .string {
return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return "\"\(key)\": \(nestedString)"
}
}
return "{\(body.joined(separator: ","))}"
} catch _ {
return nil
}
case .array:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try self.rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let array = self.object as? [Any?] else {
return nil
}
let body = try array.map { value throws -> String in
guard let unwrappedValue = value else {
return "null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw SwiftyJSONError.invalidJSON
}
if nestedValue.type == .string {
return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return nestedString
}
}
return "[\(body.joined(separator: ","))]"
} catch _ {
return nil
}
case .string:
return self.rawString
case .number:
return self.rawNumber.stringValue
case .bool:
return self.rawBool.description
case .null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible {
public var description: String {
if let string = self.rawString(options: .prettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
if self.type == .array {
return self.rawArray.map { JSON($0) }
} else {
return nil
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
return self.array ?? []
}
//Optional [Any]
public var arrayObject: [Any]? {
get {
switch self.type {
case .array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String: JSON]? {
if self.type == .dictionary {
var d = [String: JSON](minimumCapacity: rawDictionary.count)
for (key, value) in rawDictionary {
d[key] = JSON(value)
}
return d
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String: JSON] {
return self.dictionary ?? [:]
}
//Optional [String : Any]
public var dictionaryObject: [String: Any]? {
get {
switch self.type {
case .dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON { // : Swift.Bool
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .bool:
return self.rawBool
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = newValue as Bool
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .bool:
return self.rawBool
case .number:
return self.rawNumber.boolValue
case .string:
return ["true", "y", "t", "yes", "1"].contains { self.rawString.caseInsensitiveCompare($0) == .orderedSame }
default:
return false
}
}
set {
self.object = newValue
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .string:
return self.object as? String
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = NSString(string: newValue)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .string:
return self.object as? String ?? ""
case .number:
return self.rawNumber.stringValue
case .bool:
return (self.object as? Bool).map { String($0) } ?? ""
default:
return ""
}
}
set {
self.object = NSString(string: newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .number:
return self.rawNumber
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
default:
return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .string:
let decimal = NSDecimalNumber(string: self.object as? String)
if decimal == NSDecimalNumber.notANumber { // indicates parse error
return NSDecimalNumber.zero
}
return decimal
case .number:
return self.object as? NSNumber ?? NSNumber(value: 0)
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
default:
return NSNumber(value: 0.0)
}
}
set {
self.object = newValue
}
}
}
// MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .null:
return self.rawNull
default:
return nil
}
}
set {
self.object = NSNull()
}
}
public func exists() -> Bool {
if let errorValue = error, (400...1000).contains(errorValue.errorCode) {
return false
}
return true
}
}
// MARK: - URL
extension JSON {
//Optional URL
public var url: URL? {
get {
switch self.type {
case .string:
// Check for existing percent escapes first to prevent double-escaping of % character
if self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil {
return Foundation.URL(string: self.rawString)
} else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
// We have to use `Foundation.URL` otherwise it conflicts with the variable name.
return Foundation.URL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int: Int? {
get {
return self.number?.intValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.uintValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.uintValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.int8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: Int(newValue))
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.int8Value
}
set {
self.object = NSNumber(value: Int(newValue))
}
}
public var uInt8: UInt8? {
get {
return self.number?.uint8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.uint8Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.int16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.int16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.uint16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.uint16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.int32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.int32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.uint32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.uint32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.int64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.int64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.uint64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.uint64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
}
// MARK: - Comparable
extension JSON: Swift.Comparable {}
public func == (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber == rhs.rawNumber
case (.string, .string):
return lhs.rawString == rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func <= (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber <= rhs.rawNumber
case (.string, .string):
return lhs.rawString <= rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func >= (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber >= rhs.rawNumber
case (.string, .string):
return lhs.rawString >= rhs.rawString
case (.bool, .bool):
return lhs.rawBool == rhs.rawBool
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func > (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber > rhs.rawNumber
case (.string, .string):
return lhs.rawString > rhs.rawString
default:
return false
}
}
public func < (lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber < rhs.rawNumber
case (.string, .string):
return lhs.rawString < rhs.rawString
default:
return false
}
}
private let trueNumber = NSNumber(value: true)
private let falseNumber = NSNumber(value: false)
private let trueObjCType = String(cString: trueNumber.objCType)
private let falseObjCType = String(cString: falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber {
fileprivate var isBool: Bool {
let objCType = String(cString: self.objCType)
if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) {
return true
} else {
return false
}
}
}
func == (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == .orderedSame
}
}
func != (lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
func < (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == .orderedAscending
}
}
func > (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == ComparisonResult.orderedDescending
}
}
func <= (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != .orderedDescending
}
}
func >= (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != .orderedAscending
}
}
public enum writingOptionsKeys {
case jsonSerialization
case castNilToNSNull
case maxObjextDepth
case encoding
}
|
e8f349786e7ad5ec7a3244a8e40cbae4
| 26.645848 | 266 | 0.556653 | false | false | false | false |
M2Mobi/Marky-Mark
|
refs/heads/master
|
markymark/Classes/Layout Builders/UIView/Views/RemoteImageView.swift
|
mit
|
1
|
//
// Created by Jim van Zummeren on 08/05/16.
// Copyright © 2016 M2mobi. All rights reserved.
//
import Foundation
import UIKit
/*
* Image view that can retrieve images from a remote http location
*/
open class RemoteImageView: UIImageView {
public let file: String
public let altText: String
public init(file: String, altText: String) {
self.file = file
self.altText = altText
super.init(frame: CGRect.zero)
contentMode = .scaleAspectFit
if let image = UIImage(named: file) {
self.image = image
self.addAspectConstraint()
} else if let url = URL(string: file) {
loadImageFromURL(url.addHTTPSIfSchemeIsMissing())
} else {
print("Should display alt text instead: \(altText)")
}
}
// MARK: Private
private func loadImageFromURL(_ url: URL) {
DispatchQueue.global(qos: .default).async {
let data = try? Data(contentsOf: url)
DispatchQueue.main.async(execute: {
if let data = data, let image = UIImage(data: data) {
self.image = image
self.addAspectConstraint()
}
})
}
}
private func addAspectConstraint() {
if let image = image {
let constraint = NSLayoutConstraint(
item: self,
attribute: .height,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: image.size.height / image.size.width,
constant: 0
)
self.addConstraint(constraint)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
5ba2dc900bc2cd7aa940d3d7fe2922e7
| 23.702703 | 69 | 0.550875 | false | false | false | false |
superman-coder/pakr
|
refs/heads/master
|
pakr/pakr/Model/Parking/Business.swift
|
apache-2.0
|
1
|
//
// Business.swift
// pakr
//
// Created by Huynh Quang Thao on 4/11/16.
// Copyright © 2016 Pakr. All rights reserved.
//
import Foundation
class Business: NSObject, ParseNestedObjectProtocol {
/// Private constants
let PKBusinessName = "business_name"
let PKBusinessDesc = "business_desc"
let PKBusinessPhone = "business_phone"
let businessName: String!
let businessDescription: String!
let telephone: String!
init(businessName: String!, businessDescription: String!, telephone: String!) {
self.businessName = businessName
self.businessDescription = businessDescription
self.telephone = telephone
}
required init(dict: NSDictionary) {
self.businessName = dict[PKBusinessName] as! String
self.businessDescription = dict[PKBusinessDesc] as! String
self.telephone = dict[PKBusinessPhone] as! String
}
func toDictionary() -> NSDictionary {
var dict: [String:String] = [:]
dict[PKBusinessName] = businessName
dict[PKBusinessDesc] = businessDescription
dict[PKBusinessPhone] = telephone
return dict
}
}
|
8d2143fde52641f7cff5437a9595f179
| 27.585366 | 83 | 0.665529 | false | false | false | false |
Hansoncoder/SpriteDemo
|
refs/heads/master
|
SpriteKitDemo/SpriteKitDemo/HSGameScene.swift
|
apache-2.0
|
1
|
//
// HSGameScene.swift
// SpriteKitDemo
//
// Created by Hanson on 16/5/9.
// Copyright © 2016年 Hanson. All rights reserved.
//
import SpriteKit
class HSGameScene: SKScene {
var contentCreated: Bool?
override func didMoveToView(view: SKView) {
if let create = contentCreated where create { return }
backgroundColor = SKColor.blueColor()
scaleMode = .AspectFill
addChild(newHelloNode())
}
func newHelloNode() -> SKLabelNode {
let helloNode = SKLabelNode()
helloNode.name = "HelloNode"
helloNode.text = "Hello Scene"
helloNode.fontSize = 10
helloNode.position = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame))
return helloNode
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let helloNode = childNodeWithName("HelloNode") {
helloNode.name = nil
let moveUp = SKAction.moveByX(0, y: 100, duration: 0.5)
let zoom = SKAction.scaleTo(2.0, duration: 0.25)
let pause = SKAction.waitForDuration(0.5)
let fadeAway = SKAction.fadeInWithDuration(0.5)
let remove = SKAction.removeFromParent()
let moveSequence = SKAction.sequence([moveUp,zoom,pause,fadeAway,remove])
helloNode.runAction(moveSequence) { [unowned self] in
let spaceshipScene = SpaceshipScene(size: self.size)
// 转场动画
// let fade = SKTransition.fadeWithDuration(0.5) // 淡化
// let cross = SKTransition.crossFadeWithDuration(0.5) // 淡化
// let doors = SKTransition.doorwayWithDuration(0.5) // 开门
let flip = SKTransition.flipHorizontalWithDuration(0.5) // 翻转
self.view?.presentScene(spaceshipScene, transition: flip)
}
}
}
}
|
831910abdf2551646ac80f97b0ed152b
| 31.868852 | 85 | 0.577057 | false | false | false | false |
tomburns/ios
|
refs/heads/master
|
FiveCalls/Pods/Pantry/Pantry/Mirror+Serialization.swift
|
mit
|
1
|
//
// Mirror+Serialization.swift
// Pantry
//
// Created by Ian Keen on 12/12/2015.
// Copyright © 2015 That Thing in Swift. All rights reserved.
//
import Foundation
extension Mirror {
/**
Dictionary representation
Returns the dictioanry representation of the current `Mirror`
_Adapted from [@IanKeen](https://gist.github.com/IanKeen/3a6c3b9a42aaf9fea982)_
- returns: [String: Any]
*/
func toDictionary() -> [String: Any] {
let output = self.children.reduce([:]) { (result: [String: Any], child) in
guard let key = child.label else { return result }
var actualValue = child.value
var childMirror = Mirror(reflecting: child.value)
if let style = childMirror.displayStyle, style == .optional && childMirror.children.count > 0 {
// unwrap Optional type first
actualValue = childMirror.children.first!.value
childMirror = Mirror(reflecting: childMirror.children.first!.value)
}
if let style = childMirror.displayStyle, style == .collection {
// collections need to be unwrapped, children tested and
// toDictionary called on each
let converted: [Any] = childMirror.children
.map { collectionChild in
if let convertable = collectionChild.value as? Storable {
return convertable.toDictionary() as Any
} else {
return collectionChild.value as Any
}
}
return combine(result, addition: [key: converted as Any])
} else {
// non-collection types, toDictionary or just cast default types
if let value = actualValue as? Storable {
return combine(result, addition: [key: value.toDictionary() as Any])
} else {
if let style = childMirror.displayStyle, style == .optional,
childMirror.children.first == nil {
actualValue = NSNull()
}
return combine(result, addition: [key: actualValue as Any])
}
}
}
if let superClassMirror = self.superclassMirror {
return combine(output, addition: superClassMirror.toDictionary())
}
return output
}
// convenience for combining dictionaries
fileprivate func combine(_ from: [String: Any], addition: [String: Any]) -> [String: Any] {
var result = [String: Any]()
[from, addition].forEach { dict in
dict.forEach { result[$0.0] = $0.1 }
}
return result
}
}
|
a8d70d7e07f80397677e75d718ec1713
| 38.985915 | 107 | 0.543149 | false | false | false | false |
Fenrikur/ef-app_ios
|
refs/heads/master
|
Eurofurence/Director/AppWindowWireframe.swift
|
mit
|
1
|
import UIKit.UIViewController
import UIKit.UIWindow
struct AppWindowWireframe: WindowWireframe {
static var shared: AppWindowWireframe = {
guard let window = UIApplication.shared.delegate?.window, let unwrappedWindow = window else { fatalError("Application has no window") }
return AppWindowWireframe(window: unwrappedWindow)
}()
private let containerViewController: ContainerViewController
public init(window: UIWindow) {
containerViewController = ContainerViewController()
window.rootViewController = containerViewController
}
func setRoot(_ viewController: UIViewController) {
containerViewController.swapRoot(to: viewController)
}
private class ContainerViewController: UIViewController {
private var currentRoot: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .pantone330U
}
func swapRoot(to newRoot: UIViewController) {
embedChild(newRoot)
UIView.animate(withDuration: 0.25, animations: {
newRoot.view.alpha = 1
self.currentRoot?.view.alpha = 0
}, completion: { (_) in
newRoot.didMove(toParent: self)
self.unembedChild(self.currentRoot)
self.currentRoot = newRoot
})
}
private func embedChild(_ newRoot: UIViewController) {
newRoot.willMove(toParent: self)
newRoot.view.alpha = 0
view.addSubview(newRoot.view)
NSLayoutConstraint.activate([newRoot.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
newRoot.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
newRoot.view.topAnchor.constraint(equalTo: view.topAnchor),
newRoot.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
addChild(newRoot)
}
private func unembedChild(_ oldRoot: UIViewController?) {
oldRoot?.willMove(toParent: nil)
oldRoot?.view.removeFromSuperview()
oldRoot?.removeFromParent()
oldRoot?.didMove(toParent: nil)
}
}
}
|
590a3b696ef69aac54ca38ef50318e0f
| 35.454545 | 143 | 0.598919 | false | false | false | false |
notohiro/NowCastMapView
|
refs/heads/master
|
NowCastMapView/TileCache.swift
|
mit
|
1
|
//
// TileCache.swift
// NowCastMapView
//
// Created by Hiroshi Noto on 2017/05/07.
// Copyright © 2017 Hiroshi Noto. All rights reserved.
//
import Foundation
/**
A `TileCacheProvider` protocol defines a way to request a `Tile`.
*/
public protocol TileCacheProvider {
var baseTime: BaseTime { get }
/**
Returns tiles within given MapRect. The `Tile.image` object will be nil if it's not downloaded.
Call `resume()` method to obtain image file from internet.
- Parameter request: The request you need to get tiles.
- Returns: The tiles within given request.
*/
func tiles(with request: TileModel.Request) throws -> [Tile]
}
open class TileCache {
public let baseTime: BaseTime
public var cache = Set<Tile>()
public var cacheByURL = [URL: Tile]()
open private(set) lazy var model: TileModel = TileModel(baseTime: self.baseTime, delegate: self)
open private(set) weak var delegate: TileModelDelegate?
private let semaphore = DispatchSemaphore(value: 1)
deinit {
model.cancelAll()
}
internal init(baseTime: BaseTime, delegate: TileModelDelegate?) {
self.baseTime = baseTime
self.delegate = delegate
}
}
extension TileCache: TileCacheProvider {
open func tiles(with request: TileModel.Request) throws -> [Tile] {
var ret = [Tile]()
var needsRequest = false
guard let newCoordinates = request.coordinates.intersecting(TileModel.serviceAreaCoordinates) else {
throw NCError.outOfService
}
let newRequest = TileModel.Request(range: request.range,
scale: request.scale,
coordinates: newCoordinates,
withoutProcessing: request.withoutProcessing)
let zoomLevel = ZoomLevel(zoomScale: request.scale)
guard let originModifiers = Tile.Modifiers(zoomLevel: zoomLevel, coordinate: newRequest.coordinates.origin) else {
let reason = NCError.TileFailedReason.modifiersInitializationFailedCoordinate(zoomLevel: zoomLevel, coordinate: newRequest.coordinates.origin)
throw NCError.tileFailed(reason: reason)
}
guard let terminalModifiers = Tile.Modifiers(zoomLevel: zoomLevel, coordinate: newRequest.coordinates.terminal) else {
let reason = NCError.TileFailedReason.modifiersInitializationFailedCoordinate(zoomLevel: zoomLevel, coordinate: newRequest.coordinates.terminal)
throw NCError.tileFailed(reason: reason)
}
for index in request.range {
for latMod in originModifiers.latitude ... terminalModifiers.latitude {
for lonMod in originModifiers.longitude ... terminalModifiers.longitude {
guard let mods = Tile.Modifiers(zoomLevel: zoomLevel, latitude: latMod, longitude: lonMod) else {
let reason = NCError.TileFailedReason.modifiersInitializationFailedMods(zoomLevel: zoomLevel, latitiude: latMod, longitude: lonMod)
throw NCError.tileFailed(reason: reason)
}
guard let url = URL(baseTime: baseTime, index: index, modifiers: mods) else {
throw NCError.tileFailed(reason: .urlInitializationFailed)
}
if let cachedTile = cacheByURL[url] {
ret.append(cachedTile)
} else {
needsRequest = true
}
}
}
}
if needsRequest {
let newRequest = TileModel.Request(range: request.range,
scale: request.scale,
coordinates: request.coordinates,
withoutProcessing: true)
let task = try model.tiles(with: newRequest, completionHandler: nil)
task.resume()
}
return ret
}
}
extension TileCache: TileModelDelegate {
public func tileModel(_ model: TileModel, task: TileModel.Task, added tile: Tile) {
semaphore.wait()
cache.insert(tile)
cacheByURL[tile.url] = tile
semaphore.signal()
delegate?.tileModel(model, task: task, added: tile)
}
public func tileModel(_ model: TileModel, task: TileModel.Task, failed url: URL, error: Error) {
delegate?.tileModel(model, task: task, failed: url, error: error)
}
}
|
c1ff375723de46abed50fd522eaa3b8e
| 33.856 | 153 | 0.643333 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
refs/heads/master
|
Steps4Impact/Animators/AlertModalAnimations.swift
|
bsd-3-clause
|
1
|
/**
* 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 UIKit
class AlertModalTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController,
presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return AlertModalPresentationController(presentedViewController: presented, presenting: presenting)
}
func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let coordinator = AlertModalAnimationCoordinator()
coordinator.isPresenting = true
return coordinator
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let coordinator = AlertModalAnimationCoordinator()
coordinator.isPresenting = false
return coordinator
}
}
class AlertModalPresentationController: UIPresentationController {
private let backgroundView = UIView()
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
backgroundView.backgroundColor = Style.Colors.black
backgroundView.alpha = 0
}
override func presentationTransitionWillBegin() {
guard let containerView = containerView else { return }
backgroundView.frame = containerView.frame
containerView.insertSubview(backgroundView, at: 0)
presentedViewController.transitionCoordinator?.animate(alongsideTransition: { [weak self] (_) in
self?.backgroundView.alpha = 0.7
}, completion: nil)
}
override func dismissalTransitionWillBegin() {
presentedViewController.transitionCoordinator?.animate(alongsideTransition: { [weak self] (_) in
self?.backgroundView.backgroundColor = Style.Colors.Background
self?.backgroundView.alpha = 0
}, completion: nil)
}
}
class AlertModalAnimationCoordinator: NSObject, UIViewControllerAnimatedTransitioning {
var isPresenting: Bool = false
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let animatedView = transitionContext.view(forKey: isPresenting ? .to : .from) else { return }
let containerView = transitionContext.containerView
let bottomOfScreenPoint = CGPoint(x: containerView.center.x,
y: containerView.frame.maxY + animatedView.frame.size.height)
if isPresenting {
animatedView.center = bottomOfScreenPoint
containerView.addSubview(animatedView)
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
animatedView.center = self.isPresenting ? containerView.center : bottomOfScreenPoint
}, completion: { (completed) in
transitionContext.completeTransition(completed)
if !self.isPresenting {
animatedView.removeFromSuperview()
}
})
}
}
|
1686b858acf400251ce7b478a15ec719
| 43.780952 | 117 | 0.756487 | false | false | false | false |
cnbin/LayerPlayer
|
refs/heads/master
|
LayerPlayer/UIImage+TileCutter.swift
|
mit
|
3
|
//
// UIImage+TileCutter.swift
// LayerPlayer
//
// Created by Scott Gardner on 7/27/14.
// Copyright (c) 2014 Scott Gardner. All rights reserved.
//
// Adapted from Nick Lockwood's Terminal app in his book, iOS Core Animation: Advanced Techniques
// http://www.informit.com/store/ios-core-animation-advanced-techniques-9780133440751
//
import UIKit
extension UIImage {
class func saveTileOfSize(size: CGSize, name: String) -> () {
let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as String
let filePath = "\(cachesPath)/\(name)_0_0.png"
let fileManager = NSFileManager.defaultManager()
let fileExists = fileManager.fileExistsAtPath(filePath)
if fileExists == false {
var tileSize = size
let scale = Float(UIScreen.mainScreen().scale)
if let image = UIImage(named: "\(name).jpg") {
let imageRef = image.CGImage
let totalColumns = Int(ceilf(Float(image.size.width / tileSize.width)) * scale)
let totalRows = Int(ceilf(Float(image.size.height / tileSize.height)) * scale)
let partialColumnWidth = Int(image.size.width % tileSize.width)
let partialRowHeight = Int(image.size.height % tileSize.height)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
for y in 0..<totalRows {
for x in 0..<totalColumns {
if partialRowHeight > 0 && y + 1 == totalRows {
tileSize.height = CGFloat(partialRowHeight)
}
if partialColumnWidth > 0 && x + 1 == totalColumns {
tileSize.width = CGFloat(partialColumnWidth)
}
let xOffset = CGFloat(x) * tileSize.width
let yOffset = CGFloat(y) * tileSize.height
let point = CGPoint(x: xOffset, y: yOffset)
let tileImageRef = CGImageCreateWithImageInRect(imageRef, CGRect(origin: point, size: tileSize))
let imageData = UIImagePNGRepresentation(UIImage(CGImage: tileImageRef))
let path = "\(cachesPath)/\(name)_\(x)_\(y).png"
imageData?.writeToFile(path, atomically: false)
}
}
})
}
}
}
}
|
16be6c225a727445192524f469208b45
| 38.5 | 110 | 0.616325 | false | false | false | false |
moonagic/MagicOcean
|
refs/heads/master
|
MagicOcean/ViewControllers/Add/AddNewDroplet.swift
|
mit
|
1
|
//
// AddNewDroplet.swift
// MagicOcean
//
// Created by Wu Hengmin on 16/6/19.
// Copyright © 2016年 Wu Hengmin. All rights reserved.
//
import UIKit
import Alamofire
import MBProgressHUD
import UnsplashPhotoPicker
@objc public protocol AddDropletDelegate {
func didAddDroplet()
}
class AddNewDroplet: UITableViewController, UITextFieldDelegate, SelectImageDelegate, SelectSizeDelegate, SelectRegionDelegate, SelectSSHKeyDelegate {
@IBOutlet weak var hostnameField: UITextField!
@IBOutlet weak var imageField: UITextField!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var memoryAndCPULabel: UILabel!
@IBOutlet weak var diskLabel: UILabel!
@IBOutlet weak var transferLabel: UILabel!
@IBOutlet weak var regionField: UITextField!
@IBOutlet weak var SSHKeyField: UITextField!
@IBOutlet weak var privateNetworkingSwitch: UISwitch!
@IBOutlet weak var backupsSwitch: UISwitch!
@IBOutlet weak var ipv6Switch: UISwitch!
@IBOutlet weak var coverImage: UIImageView!
@IBOutlet weak var coverImageTag: UILabel!
var sizeDic:SizeTeplete!
var imageDic:ImageTeplete!
var regionDic:RegionTeplete!
var sshkeyDic:SSHKeyTeplete!
weak var delegate: AddDropletDelegate?
private var imageDataTask: URLSessionDataTask?
override func viewDidLoad() {
super.viewDidLoad()
setStatusBarAndNavigationBar(navigation: self.navigationController!)
self.hostnameField.delegate = self
// self.priceLabel.text = "$ 0.00"
self.memoryAndCPULabel.text = "0MB / 0CPUs"
self.diskLabel.text = "0GB SSD"
self.transferLabel.text = "Transfer 0TB"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
@IBAction func cancellPressed(sender: AnyObject) {
self.dismiss(animated: true) {
}
}
@IBAction func selectCoverImageButtonPressed(_ sender: Any) {
let alertController:UIAlertController=UIAlertController(title: "Select cover image", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
alertController.addAction(UIAlertAction(title: "Photo Libray", style: UIAlertAction.Style.default){
(alertAction)->Void in
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.modalPresentationStyle = .overFullScreen
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
self.present(imagePicker, animated: true, completion: nil)
})
alertController.addAction(UIAlertAction(title: "Camera", style: UIAlertAction.Style.default){
(alertAction)->Void in
let imagePicker: UIImagePickerController = UIImagePickerController()
imagePicker.modalPresentationStyle = .overFullScreen
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = UIImagePickerController.SourceType.camera
self.present(imagePicker, animated: true, completion: nil)
})
alertController.addAction(UIAlertAction(title: "form Unsplash", style: UIAlertAction.Style.default){
(alertAction)->Void in
let configuration = UnsplashPhotoPickerConfiguration(
accessKey: "7c3f947507aefaa8c5008400d78288fd13d62f32c999f4a743478b41a54f35a1",
secretKey: "66a8e97f1f6315fefaf73df0897019801f7ded66bf6aed2739be95fb26c0a8de",
allowsMultipleSelection: false
)
let unsplashPhotoPicker = UnsplashPhotoPicker(configuration: configuration)
unsplashPhotoPicker.photoPickerDelegate = self
self.present(unsplashPhotoPicker, animated: true, completion: nil)
})
alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel,handler:nil))
self.present(alertController, animated: true, completion: nil)
}
@IBAction func savePressed(sender: AnyObject) {
if self.hostnameField.text == "" {
makeTextToast(message: "Hostname can not be blank!", view: self.view.window!)
return
}
if self.sizeDic == nil {
makeTextToast(message: "You must select size!", view: self.view.window!)
return
}
if self.imageDic == nil {
makeTextToast(message: "You must select image!", view: self.view.window!)
return
}
if self.regionDic == nil {
makeTextToast(message: "You must select region!", view: self.view.window!)
return
}
// curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer b7d03a6947b217efb6f3ec3bd3504582" -d '{"name":"example.com","region":"nyc3","size":"512mb","image":"ubuntu-14-04-x64","ssh_keys":null,"backups":false,"ipv6":true,"user_data":null,"private_networking":null}' "https://api.digitalocean.com/v2/droplets"
let Headers = [
"Content-Type": "application/json",
"Authorization": "Bearer "+Account.sharedInstance.Access_Token
]
let name:String = self.hostnameField.text!
let size:String = self.sizeDic.slug
let image:String = self.imageDic.slug
let region:String = self.regionDic.slug
var keyarr:[Int] = Array<Int>()
if sshkeyDic != nil {
keyarr = [sshkeyDic.id]
}
let parameters:Parameters = [
"name":name,
"region":region,
"size":size,
"image":image,
"ssh_keys":keyarr,
"backups":self.backupsSwitch.isOn,
"ipv6":self.ipv6Switch.isOn,
// "user_data": nil,
"private_networking":self.privateNetworkingSwitch.isOn
]
print(dictionary2JsonString(dic: parameters))
let hud:MBProgressHUD = MBProgressHUD.init(view: self.view.window!)
self.view.window?.addSubview(hud)
hud.mode = MBProgressHUDMode.indeterminate
hud.show(animated: true)
hud.removeFromSuperViewOnHide = true
weak var weakSelf = self
Alamofire.request(BASE_URL+URL_DROPLETS, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: Headers).responseJSON { response in
if let strongSelf = weakSelf {
let dic = response.result.value as! NSDictionary
print("response=\(dic)")
DispatchQueue.main.async {
hud.hide(animated: true)
if let message = dic.value(forKey: "message") {
print(message)
makeTextToast(message: message as! String, view: strongSelf.view.window!)
} else {
strongSelf.delegate?.didAddDroplet()
strongSelf.dismiss(animated: true, completion: {
})
}
}
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "selectimage" {
let nv:UINavigationController = segue.destination as! UINavigationController
let vc:ImageTableView = nv.topViewController as! ImageTableView
vc.delegate = self
} else if segue.identifier == "selectsize" {
let nv:UINavigationController = segue.destination as! UINavigationController
let vc:SizeTableView = nv.topViewController as! SizeTableView
vc.delegate = self
} else if segue.identifier == "selectregion" {
let nv:UINavigationController = segue.destination as! UINavigationController
let vc:RegionTableView = nv.topViewController as! RegionTableView
vc.delegate = self
} else if segue.identifier == "selectkey" {
let nv:UINavigationController = segue.destination as! UINavigationController
let vc:SSHKeyTableView = nv.topViewController as! SSHKeyTableView
vc.delegate = self
}
}
// MARK: - delegate of ImageTableView
func didSelectImage(image: ImageTeplete) {
self.imageDic = image
weak var weakSelf = self
DispatchQueue.main.async {
weakSelf!.imageField.text = self.imageDic.slug
}
}
// MARK: - delegate of SizeTableView
func didSelectSize(size: SizeTeplete) {
self.sizeDic = size
weak var weakSelf = self
DispatchQueue.main.async {
if let strongSelf = weakSelf {
// strongSelf.priceLabel.text = "$\(String(format: "%.2f", Float(size.price)))"
strongSelf.memoryAndCPULabel.text = "\(size.memory)MB / \(size.vcpus)CPUs"
strongSelf.diskLabel.text = "\(size.disk)GB SSD"
strongSelf.transferLabel.text = "Transfer \(size.transfer)TB"
}
}
}
// MARK: - delegate of RegionTableView
func didSelectRegion(region: RegionTeplete) {
self.regionDic = region
weak var weakSelf = self
DispatchQueue.main.async {
if let strongSelf = weakSelf {
strongSelf.regionField.text = region.slug
}
}
}
// MARK: - delegate of SSHKeyTableView
func didSelectSSHKey(key: SSHKeyTeplete) {
self.sshkeyDic = key
weak var weakSelf = self
DispatchQueue.main.async {
if let strongSelf = weakSelf {
strongSelf.SSHKeyField.text = key.name
}
}
}
// MARK: - delegate of UITextField
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.count == 0 {
return true
}
let nStr:NSString = NSString(format: "\(string)" as NSString)
let uchar:unichar = nStr.character(at: 0)
if uchar >= NSString(format: "a").character(at: 0) && uchar <= NSString(format: "z").character(at: 0) {
return true
}
if uchar >= NSString(format: "A").character(at: 0) && uchar <= NSString(format: "Z").character(at: 0) {
return true
}
if uchar >= NSString(format: "1").character(at: 0) && uchar <= NSString(format: "0").character(at: 0) {
return true
}
if uchar == NSString(format: "-").character(at: 0) {
return true
}
return false
}
}
extension AddNewDroplet: UnsplashPhotoPickerDelegate {
func unsplashPhotoPicker(_ photoPicker: UnsplashPhotoPicker, didSelectPhotos photos: [UnsplashPhoto]) {
print("Unsplash photo picker did select \(photos.count) photo(s)")
guard let url = photos[0].urls[.regular] else { return }
imageDataTask = URLSession.shared.dataTask(with: url) { [weak self] (data, _, error) in
guard let strongSelf = self else { return }
strongSelf.imageDataTask = nil
guard let data = data, let image = UIImage(data: data), error == nil else { return }
DispatchQueue.main.async {
UIView.transition(with: strongSelf.coverImage, duration: 0.25, options: [.transitionCrossDissolve], animations: {
strongSelf.coverImage.image = image
}, completion: nil)
strongSelf.coverImageTag.isHidden = true
}
}
imageDataTask?.resume()
}
func unsplashPhotoPickerDidCancel(_ photoPicker: UnsplashPhotoPicker) {
print("Unsplash photo picker did cancel")
}
}
extension AddNewDroplet: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var image : UIImage!
image = (info[UIImagePickerController.InfoKey.originalImage] as! UIImage)
self.coverImage.image = image
coverImageTag.isHidden = true
picker.dismiss(animated: true) {
}
}
}
|
dd39cfd43691102d422ca9cf0d069452
| 37.553571 | 342 | 0.612398 | false | false | false | false |
aboutsajjad/Bridge
|
refs/heads/master
|
Bridge/API/URLSession.swift
|
mit
|
1
|
//
// URLSession.swift
// Bridge
//
// Created by Sajjad Aboutalebi on 3/9/18.
// Copyright © 2018 Sajjad Aboutalebi. All rights reserved.
//
import Foundation
extension URLSession {
func synchronousDataTask(with url: URL) -> (Data?, URLResponse?, Error?) {
var data: Data?
var response: URLResponse?
var error: Error?
let semaphore = DispatchSemaphore(value: 0)
let dataTask = self.dataTask(with: url) {
data = $0
response = $1
error = $2
semaphore.signal()
}
dataTask.resume()
_ = semaphore.wait(timeout: .distantFuture)
return (data, response, error)
}
}
|
6d3a880af7073f30d461c2f88a0412f5
| 22.15625 | 78 | 0.54251 | false | false | false | false |
dsantosp12/DResume
|
refs/heads/master
|
Sources/App/Models/Link.swift
|
mit
|
1
|
//
// User.swift
// App
//
// Created by Daniel Santos on 10/2/17.
//
import Vapor
import FluentProvider
import HTTP
final class Link: Model {
let storage = Storage()
var url: String
let portfolioID: Identifier?
static let urlKey = "url"
static let portfolioIDKey = "portfolio_id"
init(url: String, portfolio: Portfolio) {
self.url = url
self.portfolioID = portfolio.id
}
init(row: Row) throws {
self.url = try row.get(Link.urlKey)
self.portfolioID = try row.get(Portfolio.foreignIdKey)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Link.urlKey, self.url)
try row.set(Portfolio.foreignIdKey, self.portfolioID)
return row
}
func update(with json: JSON) throws {
let link = try Link(json: json)
self.url = link.url
try self.save()
}
}
// MARK: Relation
extension Link {
var owner: Parent<Link, Portfolio> {
return parent(id: self.portfolioID)
}
}
// MARK: JSON
extension Link: JSONRepresentable {
convenience init(json: JSON) throws {
let portfolioID: Identifier = try json.get(Link.portfolioIDKey)
guard let portfolio = try Portfolio.find(portfolioID) else {
throw Abort.badRequest
}
try self.init(url: json.get(Link.urlKey), portfolio: portfolio)
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Link.idKey, self.id)
try json.set(Link.urlKey, self.url)
try json.set(Link.portfolioIDKey, self.portfolioID)
return json
}
}
// MARK: HTTP
extension Link: ResponseRepresentable { }
extension Link: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string(Link.urlKey)
builder.parent(Portfolio.self)
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
|
b4fef8b5792c21bd85e69486db6e3d20
| 19.178947 | 67 | 0.652061 | false | false | false | false |
stuffrabbit/SwiftCoAP
|
refs/heads/master
|
Example_Projects/SwiftCoAPServerExample/SwiftCoAPServerExample/TimeResourceModel.swift
|
mit
|
1
|
//
// TimeResourceModel.swift
// SwiftCoAPServerExample
//
// Created by Wojtek Kordylewski on 23.06.15.
// Copyright (c) 2015 Wojtek Kordylewski. All rights reserved.
//
import UIKit
class TimeResourceModel: SCResourceModel {
//Individual Properties
var myText: String {
didSet {
self.dataRepresentation = myText.data(using: String.Encoding.utf8) //update observable Data anytime myText is changed
}
}
weak var server: SCServer!
var observeTimer: Timer!
//
init(name: String, allowedRoutes: UInt, text: String, server: SCServer!) {
self.myText = text
self.server = server
super.init(name: name, allowedRoutes: allowedRoutes)
//Starting Updates for Observe
self.observeTimer = Timer(timeInterval: 5.0, target: self, selector: #selector(TimeResourceModel.updateObservableData), userInfo: nil, repeats: true)
RunLoop.current.add(self.observeTimer, forMode: RunLoop.Mode.common)
self.observable = true
self.dataRepresentation = myText.data(using: String.Encoding.utf8)
}
@objc func updateObservableData() {
myText = "Observe Time: \(Date())"
server.updateRegisteredObserversForResource(self)
}
override func dataForGet(queryDictionary: [String : String], options: [Int : [Data]]) -> (statusCode: SCCodeValue, payloadData: Data?, contentFormat: SCContentFormat?)? {
return (SCCodeValue(classValue: 2, detailValue: 05)!, myText.data(using: String.Encoding.utf8), .plain)
}
}
|
99c50777eab6037b45abb67b9d37ea48
| 37.02439 | 174 | 0.677999 | false | false | false | false |
tranhieutt/Swiftz
|
refs/heads/master
|
SwiftzTests/ArrowExtSpec.swift
|
bsd-3-clause
|
1
|
//
// ArrowExtSpec.swift
// Swiftz
//
// Created by Robert Widmann on 8/16/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
import Swiftz
import SwiftCheck
import XCTest
class ArrowExtSpec : XCTestCase {
func testProperties() {
property("Arrow obeys the Functor identity law") <- forAll { (x : ArrowOf<Int, Int>) in
return forAll { (pt : Int) in
return (identity <^> x.getArrow)(pt) == identity(x.getArrow)(pt)
}
}
property("Arrow obeys the Functor composition law") <- forAll { (f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>, x : ArrowOf<Int, Int>) in
return forAll { (pt : Int) in
return ((f.getArrow • g.getArrow) <^> x.getArrow)(pt) == (f.getArrow <^> g.getArrow <^> x.getArrow)(pt)
}
}
property("Arrow obeys the Applicative identity law") <- forAll { (x : ArrowOf<Int, Int>) in
return forAll { (pt : Int) in
return (const(identity) <*> x.getArrow)(pt) == x.getArrow(pt)
}
}
property("Arrow obeys the first Applicative composition law") <- forAll { (fl : ArrowOf<Int8, ArrowOf<Int8, Int8>>, gl : ArrowOf<Int8, ArrowOf<Int8, Int8>>, xl : ArrowOf<Int8, Int8>) in
let x = xl.getArrow
let f = { $0.getArrow } • fl.getArrow
let g = { $0.getArrow } • gl.getArrow
return forAll { (pt : Int8) in
return (curry(•) <^> f <*> g <*> x)(pt) == (f <*> (g <*> x))(pt)
}
}
property("Arrow obeys the second Applicative composition law") <- forAll { (fl : ArrowOf<Int8, ArrowOf<Int8, Int8>>, gl : ArrowOf<Int8, ArrowOf<Int8, Int8>>, xl : ArrowOf<Int8, Int8>) in
let x = xl.getArrow
let f = { $0.getArrow } • fl.getArrow
let g = { $0.getArrow } • gl.getArrow
return forAll { (pt : Int8) in
return (const(curry(•)) <*> f <*> g <*> x)(pt) == (f <*> (g <*> x))(pt)
}
}
property("Arrow obeys the Monad left identity law") <- forAll { (a : Int, fa : ArrowOf<Int, ArrowOf<Int, Int>>) in
let f = { $0.getArrow } • fa.getArrow
return forAll { (pt : Int) in
return (const(a) >>- f)(pt) == f(a)(pt)
}
}
property("Arrow obeys the Monad right identity law") <- forAll { (m : ArrowOf<Int, Int>) in
return forAll { (pt : Int) in
return (m.getArrow >>- const)(pt) == m.getArrow(pt)
}
}
property("Arrow obeys the Monad associativity law") <- forAll { (fa : ArrowOf<Int, ArrayOf<Int>>, ga : ArrowOf<Int, ArrayOf<Int>>) in
let f = { $0.getArray } • fa.getArrow
let g = { $0.getArray } • ga.getArrow
return forAll { (m : Array<Int>) in
return ((m >>- f) >>- g) == (m >>- { x in f(x) >>- g })
}
}
}
}
|
177b06a5d35e6a034692423c6a603b05
| 33.643836 | 188 | 0.595097 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
test/Interpreter/SDK/objc_bridge_cast.swift
|
apache-2.0
|
13
|
// RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: rdar80079617
// Test dynamic casts that bridge value types through the runtime.
import Foundation
func genericForcedCast<T, U>(_ a: T) -> U {
return a as! U
}
func genericConditionalCast<T, U>(_ a: T) -> U? {
return a as? U
}
func testForcedValueToObjectBridging() {
// CHECK: ---Forced value to object bridging---
print("---Forced value to object bridging---")
let array: [String] = ["Hello", "World"]
// Forced bridging (exact)
// CHECK-NEXT: (
// CHECK-NEXT: Hello,
// CHECK-NEXT: World
// CHECK-NEXT: )
print(genericForcedCast(array) as NSArray)
// Forced bridging (superclass)
// CHECK-NEXT: (
// CHECK-NEXT: Hello,
// CHECK-NEXT: World
// CHECK-NEXT: )
print(genericForcedCast(array) as NSObject)
// Forced bridging (AnyObject)
// CHECK-NEXT: (
// CHECK-NEXT: Hello,
// CHECK-NEXT: World
// CHECK-NEXT: )
print(genericForcedCast(array) as NSObject)
// Forced bridging (existential success)
// CHECK-NEXT: (
// CHECK-NEXT: Hello,
// CHECK-NEXT: World
// CHECK-NEXT: )
print(genericForcedCast(array) as NSCoding)
print("Done")
}
// CHECK: Done
testForcedValueToObjectBridging()
func testConditionalValueToObjectBridging() {
// CHECK: ---Conditional value to object bridging---
print("---Conditional value to object bridging---")
let array: [String] = ["Hello", "World"]
// Conditional bridging (exact)
// CHECK-NEXT: (
// CHECK-NEXT: Hello,
// CHECK-NEXT: World
// CHECK-NEXT: )
if let nsArray = (genericConditionalCast(array) as NSArray?) {
print("\(nsArray)")
} else {
print("Not an NSArray")
}
// Conditional bridging (superclass)
// CHECK-NEXT: (
// CHECK-NEXT: Hello,
// CHECK-NEXT: World
// CHECK-NEXT: )
if let nsObject = (genericConditionalCast(array) as NSObject?) {
print("\(nsObject)")
} else {
print("Not an NSObject")
}
// Conditional bridging (AnyObject)
// CHECK-NEXT: (
// CHECK-NEXT: Hello,
// CHECK-NEXT: World
// CHECK-NEXT: )
if let anyObject = (genericConditionalCast(array) as AnyObject?) {
print("\(anyObject)")
} else {
print("Not an AnyObject")
}
// Conditional bridging (existential success)
// CHECK-NEXT: (
// CHECK-NEXT: Hello,
// CHECK-NEXT: World
// CHECK-NEXT: )
if let coding = (genericConditionalCast(array) as NSCoding?) {
print("\(coding)")
} else {
print("Not an NSCoding")
}
// CHECK-NEXT: XMLParserDelegate
if let delegate = (genericConditionalCast(array) as XMLParserDelegate?) {
print("\(delegate)")
} else {
print("Not an XMLParserDelegate")
}
// Conditional bridging (unrelated class)
// CHECK-NEXT: Not an NSString
if let nsString = (genericConditionalCast(array) as NSString?) {
print("\(nsString)")
} else {
print("Not an NSString")
}
print("Done")
}
// CHECK: Done
testConditionalValueToObjectBridging()
func testForcedObjectToValueBridging() {
// CHECK: ---Forced object to value bridging---
print("---Forced object to value bridging---")
let nsArray: NSArray = ["Hello", "World"]
// Forced bridging (exact)
// CHECK: ["Hello", "World"]
print(genericForcedCast(nsArray) as [String])
// Forced bridging (superclass)
// CHECK: ["Hello", "World"]
let nsObject: NSObject = nsArray
print(genericForcedCast(nsObject) as [String])
// Forced bridging (AnyObject)
// CHECK: ["Hello", "World"]
let anyObject: AnyObject = nsArray
print(genericForcedCast(anyObject) as [String])
// Forced bridging (existential success)
let nsCoding: NSCoding = nsArray
print(genericForcedCast(nsCoding) as [String])
print("Done")
}
// CHECK: Done
testForcedObjectToValueBridging()
func testConditionalObjectToValueBridging() {
// CHECK: ---Conditional object to value bridging---
print("---Conditional object to value bridging---")
let nsArray: NSArray = ["Hello", "World"]
let nsObject: NSObject = nsArray
let anyObject: AnyObject = nsArray
let nsCoding: NSCoding = nsArray
let nsString: NSString = "Hello"
// Conditional bridging (exact)
// CHECK: ["Hello", "World"]
if let arr = (genericConditionalCast(nsArray) as [String]?) {
print(arr)
} else {
print("Not a [String]")
}
// Conditional bridging (superclass)
// CHECK: ["Hello", "World"]
if let arr = (genericConditionalCast(nsObject) as [String]?) {
print(arr)
} else {
print("Not a [String]")
}
// Conditional bridging (AnyObject)
// CHECK: ["Hello", "World"]
if let arr = (genericConditionalCast(anyObject) as [String]?) {
print(arr)
} else {
print("Not a [String]")
}
// Conditional bridging (existential success)
// CHECK: ["Hello", "World"]
if let arr = (genericConditionalCast(nsCoding) as [String]?) {
print(arr)
} else {
print("Not a [String]")
}
// Conditional bridging (existential failure)
// Not a [Int]
if let arr = (genericConditionalCast(nsCoding) as [Int]?) {
print(arr)
} else {
print("Not a [String]")
}
// Conditional bridging (unrelated class type)
// CHECK: Not a [String]
if let arr = (genericConditionalCast(nsString) as [String]?) {
print(arr)
} else {
print("Not a [String]")
}
// Conditional bridging (unrelated element type)
// CHECK: Not a [Int]
if let arr = (genericConditionalCast(nsArray) as [Int]?) {
print(arr)
} else {
print("Not a [Int]")
}
print("Done")
}
// CHECK: Done
testConditionalObjectToValueBridging()
// rdar://problem/22587077
class Canary: NSObject {
deinit {
print("died")
}
}
var CanaryAssocObjectHandle = 0
class ImmortalCanary: NSObject {
deinit {
print("oh noes")
}
}
var ImmortalCanaryAssocObjectHandle = 0
func testValueToObjectBridgingInSwitch() {
autoreleasepool {
let string = "hello, this is a string that won't be tagged"
let nsString = string as NSString
objc_setAssociatedObject(nsString, &CanaryAssocObjectHandle, Canary(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
switch nsString as AnyObject {
case let s as String:
print("Got string \(s)")
default:
print("Not a string")
}
}
#if !(arch(i386) || arch(arm) || arch(arm64_32))
// Small strings should be immortal on new enough 64-bit Apple platforms.
if #available(macOS 10.10, *) {
autoreleasepool {
let string = "hello"
let nsString = string as NSString
objc_setAssociatedObject(
nsString, &ImmortalCanaryAssocObjectHandle, ImmortalCanary(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
#endif // 64-bit
print("Done")
}
// CHECK: died
// CHECK-NOT: oh noes
// CHECK: Done
testValueToObjectBridgingInSwitch()
|
63066a467657d1a0ac971c0beaa52867
| 23.654545 | 75 | 0.651327 | false | false | false | false |
hooliooo/Rapid
|
refs/heads/master
|
Source/UICollectionView Helpers/DataSource.swift
|
mit
|
1
|
//
// Kio
// Copyright (c) Julio Miguel Alorro
//
// Licensed under the MIT license. See LICENSE file.
//
//
import struct Foundation.IndexPath
import class UIKit.UICollectionView
import protocol UIKit.UICollectionViewDataSource
import class UIKit.UICollectionViewCell
/**
DataSource is the class that adopts the UICollectionViewDataSource protcol and manages the boilerplate set up for
using UICollectionView
*/
open class DataSource<Provider: DataProvider, Cell: ConfigurableCell<Provider.Element>>: KioObject, UICollectionViewDataSource {
// MARK: Initializers
/**
Initializer for the DataSource instance
- parameter provider: DataProviding type that contains information regarding the array it manages
- parameter collectionView: UICollectionView instance to be managed
*/
public init(provider: Provider, collectionView: UICollectionView) {
self._provider = provider
self._collectionView = collectionView
super.init()
self.setup()
}
// MARK: Stored Properties
/**
Instance constant of Provider
*/
private let _provider: Provider
/**
Instance constant of the collectionView
*/
private unowned let _collectionView: UICollectionView
// MARK: Computed Properties
/**
Returns the Provider instance that carries the collection for the collectionView. Get-only property.
*/
open var provider: Provider {
return self._provider
}
/**
Returns the UICollectionView instance. Get-only property.
*/
open var collectionView: UICollectionView {
return self._collectionView
}
// MARK: - Instance Methods
/**
The setup method is boilerplate code that assigns the collectionView's dataSource as self and
registers the specified cell to the collectionView with a given identifier
*/
open func setup() {
self._collectionView.dataSource = self
self._collectionView.register(Cell.self, forCellWithReuseIdentifier: Cell.identifier)
}
// MARK: - UICollectionViewDataSource Methods
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return self._provider.numberOfSections()
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self._provider.numberOfItems(in: section)
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// swiftlint:disable:next force_cast
let cell: Cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.identifier, for: indexPath) as! Cell
let object: Provider.Element = self.provider.element(at: indexPath)!
cell.configure(with: object)
return cell
}
}
|
4e3192ad55422d8702a234b09c09fb9c
| 32 | 128 | 0.713178 | false | false | false | false |
crewupinc/vapor-postgresql
|
refs/heads/master
|
Sources/VaporPostgreSQL/Query.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Formbound
//
// 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.
public protocol Query: QueryComponentsConvertible {}
extension Query {
public func execute(_ db: DatabaseConnection) throws -> Result {
return try db.execute(self)
}
}
public protocol TableQuery: Query {
var tableName: String { get }
}
public protocol ModelQuery: TableQuery {
associatedtype ModelType: Model
}
extension ModelQuery where Self: SelectQuery {
public func fetchAll(_ db: DatabaseConnection) throws -> [ModelType] {
return try db.execute(self).map { try ModelType(row: $0) }
}
public func fetchOne(_ db: DatabaseConnection) throws -> ModelType? {
var new = self
new.offset = 0
new.limit = 1
return try db.execute(new).map { try ModelType(row: $0) }.first
}
public func orderBy(_ values: [ModelOrderBy<ModelType>]) -> Self {
return orderBy(values.map { $0.normalize })
}
public func orderBy(_ values: ModelOrderBy<ModelType>...) -> Self {
return orderBy(values)
}
}
public struct Limit: QueryComponentsConvertible {
public let value: Int
public init(_ value: Int) {
self.value = value
}
public var queryComponents: QueryComponents {
return QueryComponents(strings: ["LIMIT", String(value)])
}
}
extension Limit: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.value = value
}
}
public struct Offset: QueryComponentsConvertible {
public let value: Int
public init(_ value: Int) {
self.value = value
}
public var queryComponents: QueryComponents {
return QueryComponents(strings: ["OFFSET", String(value)])
}
}
extension Offset: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.value = value
}
}
public enum OrderBy: QueryComponentsConvertible {
case ascending(String)
case descending(String)
public var queryComponents: QueryComponents {
switch self {
case .ascending(let field):
return QueryComponents(strings: [field, "ASC"])
case .descending(let field):
return QueryComponents(strings: [field, "DESC"])
}
}
}
public enum DeclaredFieldOrderBy {
case ascending(DeclaredField)
case descending(DeclaredField)
public var normalize: OrderBy {
switch self {
case .ascending(let field):
return .ascending(field.qualifiedName)
case .descending(let field):
return .descending(field.qualifiedName)
}
}
}
public enum ModelOrderBy<T: Model> {
case ascending(T.Field)
case descending(T.Field)
public var normalize: DeclaredFieldOrderBy {
switch self {
case .ascending(let field):
return .ascending(T.field(field))
case .descending(let field):
return .descending(T.field(field))
}
}
}
extension Sequence where Self.Iterator.Element == OrderBy {
public var queryComponents: QueryComponents {
return QueryComponents(components: map { $0.queryComponents })
}
}
public protocol FilteredQuery: Query {
var condition: Condition? { get set }
}
extension FilteredQuery {
public func filter(_ condition: Condition) -> Self {
let newCondition: Condition
if let existing = self.condition {
newCondition = .and([existing, condition])
}
else {
newCondition = condition
}
var new = self
new.condition = newCondition
return new
}
}
public struct Join: QueryComponentsConvertible {
public enum JoinType: QueryComponentsConvertible {
case inner
case outer
case left
case right
public var queryComponents: QueryComponents {
switch self {
case .inner:
return "INNER"
case .outer:
return "OUTER"
case .left:
return "LEFT"
case .right:
return "RIGHT"
}
}
}
public let tableName: String
public let types: [JoinType]
public let leftKey: String
public let rightKey: String
public init(_ tableName: String, type: [JoinType], leftKey: String, rightKey: String) {
self.tableName = tableName
self.types = type
self.leftKey = leftKey
self.rightKey = rightKey
}
public var queryComponents: QueryComponents {
return QueryComponents(components: [
types.queryComponents,
"JOIN",
QueryComponents(strings: [
tableName,
"ON",
leftKey,
"=",
rightKey
])
])
}
}
|
4a48daee75a557dc12180a7e27d9c76f
| 25.127358 | 89 | 0.677198 | false | false | false | false |
nodes-ios/NStackSDK
|
refs/heads/master
|
NStackSDK/NStackSDK/Classes/Translations/TranslationUI.swift
|
mit
|
1
|
//
// NOLabel.swift
// Borsen
//
// Created by Kasper Welner on 20/11/14.
// Copyright (c) 2014 Nodes All rights reserved.
//
#if !os(macOS)
import UIKit
import Serpent
import Alamofire
internal func translationString(keyPath: String) -> String? {
if keyPath.characters.isEmpty {
return nil
}
let langDict = TranslationManager.sharedInstance.savedTranslationsDict() as NSDictionary
return langDict.valueForKeyPath(keyPath) as? String
}
@IBDesignable public class NOTextView: UITextView {
@IBInspectable public var translationsKeyPath: NSString = ""
override public func awakeFromNib() {
updateFromLang()
}
func updateFromLang() {
let oldSelectable = self.selectable
let string = translationString(translationsKeyPath as String)
if string != nil {
self.selectable = true
self.text = string
self.selectable = oldSelectable
}
}
}
@IBDesignable public class NOTextField: UITextField {
@IBInspectable public var placeholderTranslationsKeyPath: NSString = ""
override public func awakeFromNib() {
updateFromLang()
}
func updateFromLang() {
let string = translationString(placeholderTranslationsKeyPath as String)
if string != nil {
self.placeholder = string
}
}
}
@IBDesignable public class NOButton: UIButton {
@IBInspectable public var translationsKeyPath: NSString = ""
override public func awakeFromNib() {
updateFromLang()
}
func updateFromLang() {
let string = translationString(translationsKeyPath as String)
if string != nil {
self.setTitle(string, forState: .Normal)
}
}
}
@IBDesignable public class NOSegmentControl: UISegmentedControl {
@IBInspectable public var translationKeyPath1 = ""
@IBInspectable public var translationKeyPath2 = ""
@IBInspectable public var translationKeyPath3 = ""
@IBInspectable public var translationKeyPath4 = ""
override public func awakeFromNib() {
updateFromLang()
}
func updateFromLang() {
if self.numberOfSegments > 0 {
let string1 = translationString(translationKeyPath1)
if let string1 = string1 {
self.setTitle(string1, forSegmentAtIndex: 0)
}
}
if self.numberOfSegments > 1 {
let string2 = translationString(translationKeyPath2)
if string2 != nil {
self.setTitle(string2, forSegmentAtIndex: 1)
}
}
if self.numberOfSegments > 2 {
let string3 = translationString(translationKeyPath3)
if string3 != nil {
self.setTitle(string3, forSegmentAtIndex: 2)
}
}
if self.numberOfSegments > 3 {
let string4 = translationString(translationKeyPath4)
if string4 != nil {
self.setTitle(string4, forSegmentAtIndex: 3)
}
}
}
}
#endif
|
e01b0e1831e3b4ab5541a925833346c3
| 22.5 | 92 | 0.729103 | false | false | false | false |
dkhamsing/osia
|
refs/heads/main
|
Swift/osia/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// osia
//
// Created by Daniel Khamsing on 8/10/17.
// Copyright © 2017 Daniel Khamsing. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let navigationController = UINavigationController()
navigationController.navigationBar.prefersLargeTitles = true
let c = Coordinator(navigationController: navigationController)
c.start()
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = navigationController
window?.makeKeyAndVisible()
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:.
}
}
|
76cff58d90d91b661ec0f7b4cad5dd1d
| 44.982456 | 285 | 0.728729 | false | false | false | false |
urbanthings/urbanthings-sdk-apple
|
refs/heads/master
|
UrbanThingsAPI/Internal/Response/UTImportSource.swift
|
apache-2.0
|
1
|
//
// ImportSource.swift
// UrbanThingsAPI
//
// Created by Mark Woollard on 26/04/2016.
// Copyright © 2016 UrbanThings. All rights reserved.
//
import Foundation
class UTImportSource : UTAttribution, ImportSource {
let importSourceID: String
let name: String
let comments: String?
let sourceInfoURL: URL?
let sourceDataURL: URL?
override class var className:String {
return "\(self)"
}
override init(json:[String:Any]) throws {
self.name = try parse(required: json, key: .Name, type: UTImportSource.self)
self.importSourceID = try parse(required:json, key: .ImportSourceID, type: UTImportSource.self)
self.comments = try parse(optional:json, key: .Comment, type: UTImportSource.self)
self.sourceInfoURL = try parse(optional:json, key:. SourceInfoURL, type: UTImportSource.self) { try URL.fromJSON(optional:$0) }
self.sourceDataURL = try parse(optional:json, key:. SourceDataURL, type: UTImportSource.self) { try URL.fromJSON(optional:$0) }
try super.init(json:json)
}
}
|
d5c0a8581e26377a0a554fcd0af52b20
| 34 | 135 | 0.682028 | false | false | false | false |
aroyer/neo4j-ios-patch
|
refs/heads/master
|
Source/Theo/Theo/Session.swift
|
mit
|
2
|
//
// Session.swift
// Cory D. Wiles
//
// Created by Cory D. Wiles on 9/11/14.
// Copyright (c) 2014 Theo. All rights reserved.
//
import Foundation
public class Configuration {
private let requestTimeout: Double = 10
private let resourceTimeout: Double = 20
var sessionConfiguration: NSURLSessionConfiguration
lazy private var cache: NSURLCache = {
let memoryCacheLimit: Int = 10 * 1024 * 1024;
let diskCapacity: Int = 50 * 1024 * 1024;
/**
* http://nsscreencast.com/episodes/91-afnetworking-2-0
*/
let cache:NSURLCache = NSURLCache(memoryCapacity: memoryCacheLimit, diskCapacity: diskCapacity, diskPath: nil)
return cache
}()
init() {
let additionalHeaders: [String:String] = ["Accept": "application/json", "Content-Type": "application/json; charset=UTF-8"]
self.sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
self.sessionConfiguration.requestCachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
self.sessionConfiguration.timeoutIntervalForRequest = self.requestTimeout
self.sessionConfiguration.timeoutIntervalForResource = self.resourceTimeout
self.sessionConfiguration.HTTPAdditionalHeaders = additionalHeaders
// self.sessionConfiguration.URLCache = self.cache
}
}
// TODO: Move all session request to utilize this delegate.
// Right now these are NOT called because I'm setting the URLCredential on the
// session configuration
private class TheoTaskSessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate {
// For Session based challenges
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
println("session based challenge")
}
// For Session Task based challenges
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
println("session task based challenge")
}
}
class Session {
// MARK: Private methods
private let sessionDescription = "com.graphstory.session"
private struct Static {
static var token : dispatch_once_t = 0
static var instance : Session?
}
private let sessionDelegate: TheoTaskSessionDelegate = TheoTaskSessionDelegate()
// MARK: Public properties
var session: NSURLSession
var sessionDelegateQueue: NSOperationQueue = NSOperationQueue.mainQueue()
var configuration: Configuration = Configuration()
// MARK: Structs and class vars
struct SessionParams {
static var queue: NSOperationQueue?
}
class var sharedInstance: Session {
dispatch_once(&Static.token) {
Static.instance = Session(queue: SessionParams.queue)
}
return Static.instance!
}
// MARK: Constructors
/// Designated initializer
///
/// The session delegate is set to nil and will use the "system" provided
/// delegate
///
/// :param: NSOperationQueue? queue
/// :returns: Session
required init(queue: NSOperationQueue?) {
if let operationQueue = queue {
self.sessionDelegateQueue = operationQueue
}
self.session = NSURLSession(configuration: configuration.sessionConfiguration, delegate: nil, delegateQueue: self.sessionDelegateQueue)
self.session.sessionDescription = sessionDescription
}
/// Convenience initializer
///
/// The operation queue param is set to nil which translates to using
/// NSOperationQueue.mainQueue
///
/// :returns: Session
convenience init() {
self.init(queue: nil);
}
}
|
87a29a8d2c9a4275e67c115b681a8564
| 31.352459 | 214 | 0.695718 | false | true | false | false |
Xiomara7/slackers
|
refs/heads/master
|
slackers/APIClient.swift
|
mit
|
1
|
//
// APIClient.swift
// slackers
//
// Created by Xiomara on 11/4/15.
// Copyright © 2015 Xiomara. All rights reserved.
//
import Foundation
import CoreData
class APIClient: AFHTTPRequestOperationManager {
struct URLHosts {
static let production = productionUrl
}
struct Config {
static let URLString = URLHosts.production
}
static let shared = APIClient()
init() {
super.init(baseURL: NSURL(string: Config.URLString))
AFNetworkActivityIndicatorManager.sharedManager().enabled = true
self.responseSerializer = AFHTTPResponseSerializer()
self.responseSerializer.acceptableContentTypes = Set(["application/json", "text/html"])
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
extension APIClient {
func authTeam(token: String, completion: ((success: Bool, error: NSError?) -> Void)?) {
let path = AUTH_PATH
let parameters = ["token": token]
postPath(path, parameters: parameters) { (operation, response) in
if let error = response.error {
if let block = completion {
block(success: false, error: error)
}
return
}
if let block = completion {
let defaults = NSUserDefaults.standardUserDefaults()
let team = String(response.json["team"])
defaults.setObject(team, forKey: "appTitle")
block(success: true, error: nil)
}
}
}
func getUsers(token: String, completion: ((success: Bool, error: NSError?) -> Void)?) {
let path = USERS_PATH
let parameters = ["token": token, "presence": 1]
postPath(path, parameters: parameters as! [String : AnyObject]) { (operation, response) in
if let error = response.error {
if let block = completion {
block(success: false, error: error)
}
return
}
if let block = completion {
let members = response.json["members"]
DataManager.shared.saveMembers(members)
block(success: true, error: nil)
}
}
}
}
|
94f9b6863b5d92b978a18767c9eef956
| 27.654762 | 98 | 0.540922 | false | false | false | false |
rohgar/quick-text-copy
|
refs/heads/master
|
QuickText/Utils.swift
|
gpl-3.0
|
1
|
//
// QTCUtils.swift
// Quick Text Copy
//
// Created by Rohit Gargate on 3/3/19.
// Copyright © 2019 Rovag. All rights reserved.
//
import Cocoa
class Utils {
static func selectFile() -> String? {
// Let the user select the file
let dialog = NSOpenPanel()
dialog.showsResizeIndicator = true
dialog.showsHiddenFiles = false
dialog.canChooseDirectories = false
dialog.canCreateDirectories = false
dialog.allowsMultipleSelection = false
dialog.allowedFileTypes = ["","txt","log","properties", "json"]
var chosenFile = ""
if (dialog.runModal() == NSApplication.ModalResponse.OK) {
let selection = dialog.url
if let _selection = selection {
chosenFile = _selection.path
}
} else {
return nil
}
return chosenFile
}
static func removeExtension(filename: String) -> String {
var name = filename
if (name.contains(".")) {
var array = name.split(separator: ".")
array.remove(at: array.count - 1)
name = array.joined()
}
return name
}
}
|
75afa7042bfee75b3a3e8689afb936a9
| 26.795455 | 78 | 0.551922 | false | false | false | false |
IBM-MIL/GameDoneSwift
|
refs/heads/master
|
GameDoneSwift-iPhone/GameDoneSwift/GameScene.swift
|
apache-2.0
|
1
|
//
// GameScene.swift
// GameDoneSwift
//
// Created by Kyle Craig on 1/29/16.
// Copyright (c) 2016 IBM MIL. All rights reserved.
//
import SpriteKit
import AVFoundation
class GameScene: SKScene {
let kingSpriteName = "king"
let groundSpriteName = "ground"
let backgroundSpriteName = "background"
var king: SKSpriteNode!
var ground: SKSpriteNode!
var background: SKSpriteNode!
var onGround = true
var backgrounds: [SKSpriteNode] = []
let backgroundTime: CFTimeInterval = 1.0
var previousTime: CFTimeInterval = 0
var backgroundTimeCount: CFTimeInterval = 0
var platforms: [SKShapeNode] = []
// Platform Configuration
let platformStartX: CGFloat = 2900.0
let platformHeight: CGFloat = 100.0
let minPlatformWidth: UInt32 = 100
let platformMaxWidthChange: UInt32 = 700
let minPlatformY: UInt32 = 200
let platformMaxYChange: UInt32 = 200
let platformSpacing: CGFloat = 450.0
let platformTime: CFTimeInterval = 0.5
var platformTimeCount: CFTimeInterval = 0
var player: AVAudioPlayer!
var sceneController: GameViewController!
var score = 0
override func didMove(to view: SKView) {
/* Setup your scene here */
guard let king = self.childNode(withName: kingSpriteName) as? SKSpriteNode,
let ground = self.childNode(withName: groundSpriteName) as? SKSpriteNode,
let background = self.childNode(withName: backgroundSpriteName) as? SKSpriteNode
else {
print("Sprites not found.")
return
}
self.king = king
self.ground = ground
self.background = background
setPhysicsBitMasks()
self.physicsWorld.contactDelegate = self
backgrounds.append(self.background)
addNextBG()
do {
let sickBeats = URL(fileURLWithPath: Bundle.main.path(forResource: "sickBeats", ofType: "mp3")!)
player = try AVAudioPlayer(contentsOf: sickBeats)
player.numberOfLoops = -1
player.play()
} catch {
print("Failed to load audio.")
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
/* Called when a touch begins */
jump()
}
override func update(_ currentTime: TimeInterval) {
/* Called before each frame is rendered */
platformTimeCount += currentTime - previousTime
if platformTimeCount > platformTime {
self.addPlatform()
platformTimeCount = 0
}
backgroundTimeCount += currentTime - previousTime
if backgroundTimeCount > backgroundTime {
self.addNextBG()
backgroundTimeCount = 0
}
previousTime = currentTime
}
override func didFinishUpdate() {
/* Called after each update */
movePlayer()
if king.position.y < -200 {
gameOver()
}
score += 1
}
func gameOver() {
self.isPaused = true
presentScore()
}
func presentScore() {
let alert = UIAlertController(title: "Game Over!", message:"Your final score was \(score).", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Try Again!", style: .default) { _ in
self.reset()
})
sceneController.present(alert, animated: true){}
}
func reset() {
self.removeAllChildren()
self.addChild(background)
self.addChild(ground)
self.addChild(king)
self.king.position = CGPoint(x: 200, y: 220)
moveCameraWith(king, offset: 350)
platforms = []
backgrounds = []
backgrounds.append(background)
addNextBG()
score = 0
self.isPaused = false
}
func setPhysicsBitMasks() {
/* Sets up the SKSpriteNode bit masks so they can interact in the physics engine */
self.king.physicsBody?.categoryBitMask = PhysicsBitMasks.player
self.king.physicsBody?.collisionBitMask = PhysicsBitMasks.ground
self.king.physicsBody?.contactTestBitMask = PhysicsBitMasks.ground
self.ground.physicsBody?.categoryBitMask = PhysicsBitMasks.ground
self.ground.physicsBody?.collisionBitMask = PhysicsBitMasks.player
self.ground.physicsBody?.contactTestBitMask = PhysicsBitMasks.player
}
func jump() {
/* Applies a y velocity to the player character */
if onGround {
self.king.physicsBody?.applyImpulse(CGVector(dx: 200.0, dy: 1000.0))
onGround = false
}
}
func movePlayer() {
/* Sets the x velocity of the player character */
self.king.physicsBody?.velocity.dx = 1000.0
moveCameraWith(self.king, offset: 350)
}
func moveCameraWith(_ node: SKNode, offset: CGFloat) {
/* Moves the camera along the x-axis with a specified node and offset */
guard let camera = self.camera else {
print("No camera.")
return
}
camera.position = CGPoint(x: node.position.x + offset, y: 375)
}
func addNextBG() {
/* Adds a new background sprite to backgrounds. */
let nextBG = SKSpriteNode(imageNamed: "background")
nextBG.size = CGSize(width: 1920.0, height: 1080.0)
nextBG.anchorPoint = CGPoint(x: 0.0, y: 0.0)
nextBG.position.x = backgrounds.last!.position.x + backgrounds.last!.frame.width
backgrounds.append(nextBG)
addChild(nextBG)
if backgrounds.count > 100 {
backgrounds.first?.removeFromParent()
backgrounds.removeFirst()
}
}
func platformWithRect(_ rect: CGRect) -> SKShapeNode {
/* Create a new platform node and its physics body. */
let platform = SKShapeNode(rect: rect)
platform.name = "platform"
platform.fillColor = UIColor(red: 206/256, green: 229/256, blue: 139/256, alpha: 1.0)
platform.zPosition = 1
let center = CGPoint(x: platform.frame.origin.x + platform.frame.width/2, y: platform.frame.origin.y + platform.frame.height/2)
platform.physicsBody = SKPhysicsBody(rectangleOf: rect.size, center: center)
platform.physicsBody?.affectedByGravity = false
platform.physicsBody?.allowsRotation = false
platform.physicsBody?.isDynamic = false
platform.physicsBody?.pinned = true
platform.physicsBody?.categoryBitMask = PhysicsBitMasks.ground
platform.physicsBody?.collisionBitMask = PhysicsBitMasks.player
platform.physicsBody?.contactTestBitMask = PhysicsBitMasks.player
return platform
}
func addPlatform() {
/* Add a new platform to the game. */
var x: CGFloat = platformStartX
let y = CGFloat(arc4random_uniform(platformMaxYChange)+minPlatformY)
let width = CGFloat(arc4random_uniform(platformMaxWidthChange)+minPlatformWidth)
if platforms.count > 0 {
let previous = platforms.last!
x = previous.frame.origin.x + previous.frame.width + platformSpacing
}
let rect = CGRect(x: x, y: y, width: width, height: platformHeight)
let platform = platformWithRect(rect)
platforms.append(platform)
addChild(platform)
if platforms.count > 150 {
platforms.first?.removeFromParent()
platforms.removeFirst()
}
}
}
extension GameScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
/* Fires when contact is made between two physics bodies with collision bit masks */
onGround = true
}
}
|
328f10005bb3d468a87f6374dd303e87
| 29.626415 | 135 | 0.597462 | false | false | false | false |
BGDigital/mckuai2.0
|
refs/heads/master
|
mckuai/mckuai/login/Avatar.swift
|
mit
|
1
|
//
// avatar.swift
// mckuai
//
// Created by 夕阳 on 15/2/2.
// Copyright (c) 2015年 XingfuQiu. All rights reserved.
//
import Foundation
import UIKit
class Avatar:UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UIGestureRecognizerDelegate,UzysAssetsPickerControllerDelegate{
var manager = AFHTTPRequestOperationManager()
var imgPrex = "http://cdn.mckuai.com/images/iphone/"
var isNew = false
var isLocationPic = false
var hud:MBProgressHUD?
var chosedAvatar:String?{
didSet{
choseAvatar()
}
}
var avatars = ["0.png","1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png","9.png","10.png","11.png","12.png","13.png","14.png"]
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var avatarList: UICollectionView!
var addPic:UIButton!
override func viewDidLoad() {
initNavigation()
if chosedAvatar == nil {
chosedAvatar = avatars[0]
}else{
choseAvatar()
}
avatarList.dataSource = self
avatarList.delegate = self
avatarList.scrollEnabled = false
//initAddPicButtton()
}
func initAddPicButtton(){
var addLable = UILabel(frame: CGRectMake(20, self.avatarList.frame.size.height + 15,150 , 25))
addLable.text = "选择本地图片"
addLable.textColor = UIColor(red: 0.263, green: 0.263, blue: 0.263, alpha: 1.00)
self.view.addSubview(addLable)
addPic = UIButton(frame: CGRectMake(10,self.avatarList.frame.size.height + 55 , 60, 60))
addPic.setImage(UIImage(named: "addImage"), forState: UIControlState.Normal)
addPic.addTarget(self, action: "addPicAction", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(addPic)
}
@IBAction func addPicAction() {
MobClick.event("headImgPage", attributes: ["type":"addPic","result":"all"])
var appearanceConfig = UzysAppearanceConfig()
appearanceConfig.finishSelectionButtonColor = UIColor.greenColor()
UzysAssetsPickerController.setUpAppearanceConfig(appearanceConfig)
var picker = UzysAssetsPickerController()
picker.delegate = self
picker.maximumNumberOfSelectionVideo = 0;
picker.maximumNumberOfSelectionPhoto = 1;
self.presentViewController(picker, animated: true, completion: nil)
}
func uzysAssetsPickerController(picker: UzysAssetsPickerController!, didFinishPickingAssets assets: [AnyObject]!) {
if(assets.count == 1){
var assets_array = assets as NSArray
assets_array.enumerateObjectsUsingBlock({ obj, index, stop in
// println(index)
var representation:ALAsset = obj as! ALAsset
var returnImg = UIImage(CGImage: representation.thumbnail().takeUnretainedValue())
self.avatar.image = returnImg
self.isLocationPic = true
self.isNew = true
})
}
// if(assets[0].valueForProperty(ALAssetPropertyType).isEqualToString(ALAssetTypePhoto)){
// [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// ALAsset *representation = obj;
//
// UIImage *img = [UIImage imageWithCGImage:representation.defaultRepresentation.fullResolutionImage
// scale:representation.defaultRepresentation.scale
// orientation:(UIImageOrientation)representation.defaultRepresentation.orientation];
//
// }];
// }
}
func uzysAssetsPickerControllerDidExceedMaximumNumberOfSelection(picker: UzysAssetsPickerController!) {
MCUtils.showCustomHUD("亲,你传的图片已达到上限", aType: .Warning)
}
func initNavigation() {
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
let navigationTitleAttribute : NSDictionary = NSDictionary(objectsAndKeys: UIColor.whiteColor(),NSForegroundColorAttributeName)
self.navigationController?.navigationBar.titleTextAttributes = navigationTitleAttribute as [NSObject : AnyObject]
self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor(red: 0.247, green: 0.812, blue: 0.333, alpha: 1.00))
var back = UIBarButtonItem(image: UIImage(named: "nav_back"), style: UIBarButtonItemStyle.Bordered, target: self, action: "backToPage")
back.tintColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = back
self.navigationController?.interactivePopGestureRecognizer.delegate = self // 启用 swipe back
var sendButton = UIBarButtonItem()
sendButton.title = "保存"
sendButton.target = self
sendButton.action = Selector("save")
self.navigationItem.rightBarButtonItem = sendButton
}
func backToPage() {
self.navigationController?.popViewControllerAnimated(true)
}
func postHeadInfoToServer() {
if(chosedAvatar != nil){
let dic = [
"flag" : NSString(string: "headImg"),
"userId": appUserIdSave,
"headImg" : chosedAvatar!
]
manager.POST(saveUser_url,
parameters: dic,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
MobClick.event("headImgPage", attributes: ["type":"savePic","result":"success"])
if(self.hud != nil){
self.hud?.hide(true)
}
MCUtils.showCustomHUD("保存信息成功", aType: .Success)
isLoginout = true
self.navigationController?.popViewControllerAnimated(true)
}else{
if(self.hud != nil){
self.hud?.hide(true)
}
MobClick.event("headImgPage", attributes: ["type":"savePic","result":"error"])
MCUtils.showCustomHUD("保存信息失败", aType: .Error)
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
// println("Error: " + error.localizedDescription)
if(self.hud != nil){
self.hud?.hide(true)
}
MobClick.event("headImgPage", attributes: ["type":"savePic","result":"error"])
MCUtils.showCustomHUD("保存信息失败", aType: .Error)
})
}
}
func save(){
MobClick.event("headImgPage", attributes: ["type":"savePic","result":"all"])
if !isNew {
self.navigationController?.popViewControllerAnimated(true)
return
}
if(self.isLocationPic == true){
hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
hud?.labelText = "保存中..."
manager.POST(upload_url,
parameters:nil,
constructingBodyWithBlock: { (formData:AFMultipartFormData!) in
var key = "fileHeadImg"
var value = "fileNameHeadImg.jpg"
var imageData = UIImageJPEGRepresentation(self.avatar.image, 1.0)
formData.appendPartWithFileData(imageData, name: key, fileName: value, mimeType: "image/jpeg")
},
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
println(json["msg"])
self.chosedAvatar = json["msg"].stringValue
MobClick.event("headImgPage", attributes: ["type":"addPic","result":"success"])
self.postHeadInfoToServer()
}else{
self.hud?.hide(true)
MCUtils.showCustomHUD("图片上传失败,请稍候再试", aType: .Error)
MobClick.event("headImgPage", attributes: ["type":"addPic","result":"error"])
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
// println("Error: " + error.localizedDescription)
self.hud?.hide(true)
MCUtils.showCustomHUD("图片上传失败,请稍候再试", aType: .Error)
MobClick.event("headImgPage", attributes: ["type":"addPic","result":"error"])
})
}else{
hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
hud?.labelText = "保存中"
self.postHeadInfoToServer()
}
}
func choseAvatar(){
if chosedAvatar == nil || self.avatar == nil {
return
}
var a_url = chosedAvatar!.hasPrefix("http://") ? chosedAvatar! : imgPrex + chosedAvatar!
self.avatar.sd_setImageWithURL(NSURL(string: a_url))
// GTUtil.loadImage( a_url, callback: {
// (img:UIImage?)->Void in
// self.avatar.image = img
// })
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
chosedAvatar = avatars[indexPath.row]
isNew = true
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
collectionView.frame.size.height = CGFloat(50 * avatars.count)
return avatars.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var chosing = collectionView.dequeueReusableCellWithReuseIdentifier("avt", forIndexPath: indexPath) as! AvatarHolder
chosing.url = imgPrex + avatars[indexPath.row]
return chosing
}
class func changeAvatar(ctl:UINavigationController,url:String?){
var avatar_view = UIStoryboard(name: "profile_layout", bundle: nil).instantiateViewControllerWithIdentifier("avatar_chose") as! Avatar
avatar_view.chosedAvatar = url
ctl.pushViewController(avatar_view, animated: true)
}
override func viewWillAppear(animated: Bool) {
self.tabBarController?.tabBar.hidden = true
MobClick.beginLogPageView("userInfoSetHeadImg")
}
override func viewWillDisappear(animated: Bool) {
self.tabBarController?.tabBar.hidden = false
MobClick.endLogPageView("userInfoSetHeadImg")
}
}
class AvatarHolder:UICollectionViewCell{
@IBOutlet weak var holder: UIImageView!
var url:String?{
didSet{
self.holder.sd_setImageWithURL(NSURL(string: url!))
}
}
}
|
c222c38b86e877bd70fae7b671c225b2
| 36.677632 | 145 | 0.572776 | false | false | false | false |
gu704823/huobanyun
|
refs/heads/master
|
huobanyun/listCollectionViewController.swift
|
mit
|
1
|
//
// listCollectionViewController.swift
// huobanyun
//
// Created by AirBook on 2017/6/17.
// Copyright © 2017年 AirBook. All rights reserved.
//
import UIKit
import LeanCloud
enum state:String {
case 未开始 = "未开始"
case 进行中 = "进行中"
case 已完成 = "已完成"
}
enum priority:String {
case 低 = "低"
case 中 = "中"
case 高 = "高"
}
class listCollectionViewController: UICollectionViewController {
//拖控件
@IBAction func addzhihang(_ sender: UIBarButtonItem) {
leftbtnonclick()
}
//定义数据
var zhihang:[LCObject] = []
var refreshcontrol = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
refershdata()
// let date = Date()
// let userdefaults = UserDefaults.standard
// let name = userdefaults.object(forKey: "name")!
// addandquery.addtarget(classname: "addtarget", person: ["swift","jaso"], taskdescription: "打印机坏了", taskname: "壮志", finshtime: date, priority: "高", state: "已完成", creatpeople: name as! String)
//query.onsearch(name: "addtarget", classname: "壮志")
// addandquery.creatarea()
// addandquery.queryzhihang()
refreshcontrol.addTarget(self, action: #selector(refershdata), for: .valueChanged)
refreshcontrol.attributedTitle = NSAttributedString(string: "下拉刷新支行")
collectionView?.addSubview(refreshcontrol)
navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: nil)
}
//刷新数据
@objc fileprivate func refershdata(){
refreshcontrol.beginRefreshing()
DispatchQueue.global().async {
query.getdata(classname:"zhihang", completion: { (results) in
self.zhihang = results
self.collectionView?.reloadData()
})
DispatchQueue.main.async {
self.refreshcontrol.endRefreshing()
}
}
}
}
//MARK:-点击事件汇合
extension listCollectionViewController{
//导航左边的按钮点击事件
fileprivate func leftbtnonclick(){
let alertcontroller = UIAlertController(title: "添加支行", message: "请添加支行名称", preferredStyle: .alert)
alertcontroller.addTextField { (textfiled:UITextField) in
textfiled.placeholder = "支行名称"
let cancleanction = UIAlertAction(title: "取消", style: .cancel
, handler: nil)
let okaction = UIAlertAction(title: "确定", style: .default) { (_) in
let name = (alertcontroller.textFields?.first?.text)!
if (name == ""){
let alertcontroller = UIAlertController(title: "警告", message: "请输入正确的支行名称", preferredStyle: .alert)
let okaction = UIAlertAction(title: "知道了", style: .cancel, handler: nil)
alertcontroller.addAction(okaction)
self.present(alertcontroller, animated: true, completion: nil)
return
}else{}
self.adddata(classname: "zhihang", value: name)
//self.collectionView?.reloadData()
}
alertcontroller.addAction(cancleanction)
alertcontroller.addAction(okaction)
self.present(alertcontroller, animated: true, completion: nil)
}
}
func adddata(classname:String,value:String){
let query = LCQuery(className: classname)
query.whereKey("name",.equalTo("\(value)"))
query.getFirst { (results) in
switch results {
case .failure(error: _):
let todoFolder = LCObject(className: classname)
todoFolder.set("name", value: "\(value)")
todoFolder.save({ (result) in
switch results{
case .failure(error: _): break
case .success(object: _): break
}
})
case .success(object: _):
let alertcontroller = UIAlertController(title: "警告", message: "你已经添加了这个支行", preferredStyle: .alert)
let okaction = UIAlertAction(title: "知道了", style: .cancel, handler: nil)
alertcontroller.addAction(okaction)
self.present(alertcontroller, animated: true, completion: nil)
}
}
}
}
//MARK:-collectionview
extension listCollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return zhihang.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listcollectcell", for: indexPath) as! listCollectionViewCell
cell.name.text = zhihang[indexPath.row]["name"]?.stringValue
cell.badgeCenterOffset = CGPoint(x: -15, y: 10)
cell.showBadge(with: .number, value: 2, animationType: .shake)
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath)
}
}
|
25675f2b897a208e006d5955cdf873cb
| 36.4 | 199 | 0.614236 | false | false | false | false |
huonw/swift
|
refs/heads/master
|
test/SILGen/objc_metatypes.swift
|
apache-2.0
|
3
|
// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership -enable-objc-interop | %FileCheck %s
import gizmo
@objc class ObjCClass {}
class A {
// CHECK-LABEL: sil hidden @$S14objc_metatypes1AC3foo{{[_0-9a-zA-Z]*}}F
// CHECK-LABEL: sil hidden [thunk] @$S14objc_metatypes1AC3fooyAA9ObjCClassCmAFmFTo
@objc dynamic func foo(_ m: ObjCClass.Type) -> ObjCClass.Type {
// CHECK: bb0([[M:%[0-9]+]] : @trivial $@objc_metatype ObjCClass.Type, [[SELF:%[0-9]+]] : @unowned $A):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $A
// CHECK: [[M_AS_THICK:%[0-9]+]] = objc_to_thick_metatype [[M]] : $@objc_metatype ObjCClass.Type to $@thick ObjCClass.Type
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[NATIVE_FOO:%[0-9]+]] = function_ref @$S14objc_metatypes1AC3foo{{[_0-9a-zA-Z]*}}F
// CHECK: [[NATIVE_RESULT:%[0-9]+]] = apply [[NATIVE_FOO]]([[M_AS_THICK]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@thick ObjCClass.Type, @guaranteed A) -> @thick ObjCClass.Type
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[OBJC_RESULT:%[0-9]+]] = thick_to_objc_metatype [[NATIVE_RESULT]] : $@thick ObjCClass.Type to $@objc_metatype ObjCClass.Type
// CHECK: return [[OBJC_RESULT]] : $@objc_metatype ObjCClass.Type
// CHECK: } // end sil function '$S14objc_metatypes1AC3fooyAA9ObjCClassCmAFmFTo'
return m
}
// CHECK-LABEL: sil hidden @$S14objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZ
// CHECK-LABEL: sil hidden [thunk] @$S14objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZTo
// CHECK: bb0([[SELF:%[0-9]+]] : @trivial $@objc_metatype A.Type):
// CHECK-NEXT: [[OBJC_SELF:%[0-9]+]] = objc_to_thick_metatype [[SELF]] : $@objc_metatype A.Type to $@thick A.Type
// CHECK: [[BAR:%[0-9]+]] = function_ref @$S14objc_metatypes1AC3bar{{[_0-9a-zA-Z]*}}FZ
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[BAR]]([[OBJC_SELF]]) : $@convention(method) (@thick A.Type) -> ()
// CHECK-NEXT: return [[RESULT]] : $()
@objc dynamic class func bar() { }
@objc dynamic func takeGizmo(_ g: Gizmo.Type) { }
// CHECK-LABEL: sil hidden @$S14objc_metatypes1AC7callFoo{{[_0-9a-zA-Z]*}}F
func callFoo() {
// Make sure we peephole Type/thick_to_objc_metatype.
// CHECK-NOT: thick_to_objc_metatype
// CHECK: metatype $@objc_metatype ObjCClass.Type
foo(ObjCClass.self)
// CHECK: return
}
}
|
849aea2791d89c6a6e728e88ef671674
| 54.391304 | 191 | 0.628336 | false | false | false | false |
alessandrostone/DDUtils
|
refs/heads/master
|
swift/ddutils-common/model/DDPermutation [IOS+OSX]/DDPermutation/main.swift
|
mit
|
1
|
//
// main.swift
// M42RandomIndexPermutation
//
// Created by Dominik Pich on 11/05/15.
// Copyright (c) 2015 Dominik Pich. All rights reserved.
//
import Foundation
println("Hello, World!")
let data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
println("seed 0")
var permutation0 = permutate(data, 0)
var idx = permutation0.allIndexes
var i = 0
for obj in permutation0 {
println("\(obj) at \(idx[i++])")
}
println("seed 1")
var permutation1 = permutate(permutation0, UInt32(NSDate().timeIntervalSince1970))
idx = permutation1.allIndexes
i = 0
for obj in permutation1 {
println("\(obj) at \(idx[i++])")
}
println("seed 0 (second try")
var permutation2 = permutate(data, 0)
idx = permutation2.allIndexes
i = 0
for obj in permutation1 {
println("\(obj) at \(idx[i++])")
}
println("seed 1 (second try")
var permutation3 = permutate(permutation2, UInt32(NSDate().timeIntervalSince1970))
idx = permutation3.allIndexes
i = 0
for obj in permutation3 {
println("\(obj) at \(idx[i++])")
}
println("permutation0 == permutation2? \(permutation0 == permutation2)")
println("permutation1 == permutation3? \(permutation1 == permutation3)")
println("permutation1 != permutation2? \(permutation1 != permutation2)")
|
e76306983b37e75852967dbb584d82a2
| 23.938776 | 82 | 0.696151 | false | false | false | false |
jianghongbing/APIReferenceDemo
|
refs/heads/master
|
UIKit/UIImagePickerController/UIImagePickerController/TableViewController.swift
|
mit
|
1
|
//
// TableViewController.swift
// UIImagePickerController
//
// Created by pantosoft on 2018/4/17.
// Copyright © 2018年 jianghongbing. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let sourceType = UIImagePickerControllerSourceType(rawValue: indexPath.row) {
switch sourceType {
case .photoLibrary:
requestAccessPhotoLibary { (accessLevel) in
if(accessLevel == .authorized) {
self.presentImagePickerController(with: .photoLibrary)
}else {
self.alert(with: "authorization status", message: accessLevel.rawValue)
}
}
case .camera:
requestAccessCamera { (accessLevel) in
if(accessLevel == .authorized) {
self.presentImagePickerController(with: .camera)
}else {
self.alert(with: "authorization status", message: accessLevel.rawValue)
}
}
case .savedPhotosAlbum:
self.presentImagePickerController(with: .savedPhotosAlbum)
}
}
}
private func requestAccessPhotoLibary(completionHandler: @escaping (AccessLevel) -> Void) {
PHPhotoLibrary.requestAuthorization { (authorizationStatus) in
DispatchQueue.main.async {
switch authorizationStatus {
case .notDetermined:
completionHandler(.notDetermined)
case .restricted:
completionHandler(.restricted)
case .denied:
completionHandler(.denied)
case .authorized:
completionHandler(.authorized)
}
}
}
}
private func requestAccessCamera(completionHandler: @escaping (AccessLevel) -> Void) {
AVCaptureDevice.requestAccess(for: .video) { (_) in
let authorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
DispatchQueue.main.async {
switch authorizationStatus {
case .notDetermined:
completionHandler(.notDetermined)
case .restricted:
completionHandler(.restricted)
case .denied:
completionHandler(.denied)
case .authorized:
completionHandler(.authorized)
}
}
}
}
private func presentImagePickerController(with sourceType: UIImagePickerControllerSourceType) {
//判断某个sourceType是否可用
//sourceType类型: photoLibrary,相册, camera:相机, savedPhotesAlbum,保存图片到相册
let isSourceTypeAvailable = UIImagePickerController.isSourceTypeAvailable(sourceType)
guard isSourceTypeAvailable else {
alert(with: "Warning", message: "Source type is not available for current device")
return
}
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = sourceType
imagePickerController.allowsEditing = true
if #available(iOS 11.0, *) {
imagePickerController.imageExportPreset = .current
imagePickerController.videoExportPreset = AVAssetExportPreset960x540
}
print("mediaTypes:\(imagePickerController.mediaTypes)")
//获取可用的medie types
if let availableMediaTypes = UIImagePickerController.availableMediaTypes(for: sourceType) {
print("avaliableMediaTypes:\(availableMediaTypes)")
//设置imagePickerController的mediaTypes,默认里面包含pulic.image,没有包含pulic.video
imagePickerController.mediaTypes = availableMediaTypes
}
if sourceType == .camera {
//判断前后摄像头是否可用
let cameraDeviceRearIsAvailable = UIImagePickerController.isCameraDeviceAvailable(.rear)
let cameraDeviceFrontIsAvailable = UIImagePickerController.isCameraDeviceAvailable(.front)
print("cameraDeviceRearIsAvailable:\(cameraDeviceRearIsAvailable), cameraDeviceFrontIsAvailable:\(cameraDeviceFrontIsAvailable)");
if cameraDeviceFrontIsAvailable {
//设置imagePickerController的摄像头
imagePickerController.cameraDevice = .front
//设置imagePickerController的闪光灯模式
imagePickerController.cameraFlashMode = .auto
//设置cameraView的transform
// imagePickerController.cameraViewTransform = CGAffineTransform(rotationAngle: CGFloat.pi / 4)
//设置录制视频的质量,默认值为medium
imagePickerController.videoQuality = .type640x480
//设置录制视频的最长时间,默认为10分钟
imagePickerController.videoMaximumDuration = 30
if let availableCaptureModes = UIImagePickerController.availableCaptureModes(for: .front) {
print("availableCaptureModes:\(availableCaptureModes)")
if availableCaptureModes.contains(UIImagePickerControllerCameraCaptureMode.video.rawValue as NSNumber) {
imagePickerController.mediaTypes = ["public.image", "public.movie"]
imagePickerController.cameraCaptureMode = .video
}
}
}
// imagePickerController.showsCameraControls = false
// imagePickerController.cameraOverlayView = nil
}
present(imagePickerController, animated: true, completion: nil)
}
}
extension TableViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("info:\(info)")
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("image picker controller cancel")
picker.dismiss(animated: true, completion: nil)
}
}
|
66966713c13cb715cac7548069ecac6f
| 39.276074 | 142 | 0.613709 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS
|
refs/heads/develop
|
Aztec/Classes/Extensions/UIPasteboard+Helpers.swift
|
gpl-2.0
|
2
|
import Foundation
import MobileCoreServices
import UIKit
// MARK: - Pasteboard Helpers
//
extension UIPasteboard {
/// Attempts to retrieve the Pasteboard's contents as an attributed string, if possible.
///
func attributedString() -> NSAttributedString? {
if let string = aztecAttributedString() {
return string
}
if let string = rtfdAttributedString() {
return string
}
if let string = rtfAttributedString() {
return string
}
if let string = richTextAttributedString() {
return string
}
return plainTextAttributedString()
}
func html() -> String? {
guard let htmlData = data(forPasteboardType: String(kUTTypeHTML)) else {
return nil
}
return String(data: htmlData, encoding: .utf8)
}
}
// MARK: - Attributed String Conversion
private extension UIPasteboard {
// MARK: -
/// Attempts to unarchive the Pasteboard's Aztec-Archived String
///
private func aztecAttributedString() -> NSAttributedString? {
guard let data = data(forPasteboardType: NSAttributedString.pastesboardUTI) else {
return nil
}
return NSAttributedString.unarchive(with: data)
}
/// Attempts to unarchive the Pasteboard's Plain Text contents into an Attributed String
///
private func plainTextAttributedString() -> NSAttributedString? {
return unarchiveAttributedString(fromPasteboardCFType: kUTTypePlainText, with: StringOptions.plainText)
}
/// Attempts to unarchive the Pasteboard's Text contents into an Attributed String
///
private func richTextAttributedString() -> NSAttributedString? {
return unarchiveAttributedString(fromPasteboardCFType: kUTTypeText, with: StringOptions.RTFText)
}
/// Attempts to unarchive the Pasteboard's RTF contents into an Attributed String
///
private func rtfAttributedString() -> NSAttributedString? {
return unarchiveAttributedString(fromPasteboardCFType: kUTTypeRTF, with: StringOptions.RTFText)
}
/// Attempts to unarchive the Pasteboard's RTFD contents into an Attributed String
///
private func rtfdAttributedString() -> NSAttributedString? {
return unarchiveAttributedString(fromPasteboardCFType: kUTTypeFlatRTFD, with: StringOptions.RTFDText)
}
// MARK: - Helpers
/// String Initialization Options
///
private struct StringOptions {
static let html: [DocumentReadingOptionKey: DocumentType] = [.documentType: .html]
static let plainText: [DocumentReadingOptionKey: DocumentType] = [.documentType: .plain]
static let RTFText: [DocumentReadingOptionKey: DocumentType] = [.documentType: .rtf]
static let RTFDText: [DocumentReadingOptionKey: DocumentType] = [.documentType: .rtfd]
}
/// Attempts to unarchive a Pasteboard's Entry into a NSAttributedString Instance.
///
/// - Parameters:
/// - type: Pasteboard's Attribute Key
/// - options: Properties to be utilized during the NSAttributedString Initialization.
///
/// - Returns: NSAttributed String with the contents of the specified Pasteboard entry, if any.
///
private func unarchiveAttributedString(fromPasteboardCFType type: CFString, with options: [DocumentReadingOptionKey: Any]) -> NSAttributedString? {
guard let data = data(forPasteboardType: String(type)) else {
return nil
}
return try? NSAttributedString(data: data, options: options, documentAttributes: nil)
}
}
|
61d0d17d1b1b6ccf95c84947d411f90c
| 33.439252 | 151 | 0.671099 | false | false | false | false |
irisapp/das-quadrat
|
refs/heads/master
|
Source/Shared/Task.swift
|
bsd-2-clause
|
1
|
//
// Task.swift
// Quadrat
//
// Created by Constantine Fry on 26/10/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
public enum FoursquareResponse {
case Result(Dictionary<String, String>)
case Error(NSError)
}
public class Task {
private var task: NSURLSessionTask?
private weak var session: Session?
private let completionHandler: ResponseClosure?
var request: Request
/** The identifier of network activity. */
var networkActivityId: Int?
init (session: Session, request: Request, completionHandler: ResponseClosure?) {
self.session = session
self.request = request
self.completionHandler = completionHandler
}
func constructURLSessionTask() {fatalError("Use subclasses!")}
/** Starts the task. */
public func start() {
if self.session == nil {
fatalError("No session for this task.")
}
if self.task == nil {
self.constructURLSessionTask()
}
if let task = self.task {
task.resume()
networkActivityId = session!.networkActivityController?.beginNetworkActivity()
}
}
/**
Cancels the task.
Returns error with NSURLErrorDomain and code NSURLErrorCancelled in `completionHandler`.
Hint: use `isCancelled()` on `Response` object.
*/
public func cancel() {
self.task?.cancel()
self.task = nil
}
}
class DataTask: Task {
override func constructURLSessionTask() {
let URLsession = self.session?.URLSession
self.task = URLsession?.dataTaskWithRequest(request.URLRequest()) {
(data, response, error) -> Void in
self.session?.networkActivityController?.endNetworkActivity(self.networkActivityId)
let result = Result.resultFromURLSessionResponse(response, data: data, error: error)
self.session?.processResult(result)
self.session?.completionQueue.addOperationWithBlock {
self.completionHandler?(result: result)
return Void()
}
}
}
}
class UploadTask: Task {
var fileURL: NSURL?
override func constructURLSessionTask() {
// swiftlint:disable force_cast
let mutableRequest = self.request.URLRequest().mutableCopy() as! NSMutableURLRequest
let boundary = NSUUID().UUIDString
let contentType = "multipart/form-data; boundary=" + boundary
mutableRequest.addValue(contentType, forHTTPHeaderField: "Content-Type")
let body = NSMutableData()
let appendStringBlock = {
(string: String) in
body.appendData(string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
}
var extention = self.fileURL!.pathExtension
if extention == nil {
extention = "png"
}
appendStringBlock("\r\n--\(boundary)\r\n")
appendStringBlock("Content-Disposition: form-data; name=\"photo\"; filename=\"photo.\(extention)\"\r\n")
appendStringBlock("Content-Type: image/\(extention)\r\n\r\n")
if let imageData = NSData(contentsOfURL: self.fileURL!) {
body.appendData(imageData)
} else {
fatalError("Can't read data at URL: \(self.fileURL!)")
}
appendStringBlock("\r\n--\(boundary)--\r\n")
self.task = self.session?.URLSession.uploadTaskWithRequest(mutableRequest, fromData: body) {
(data, response, error) -> Void in
self.session?.networkActivityController?.endNetworkActivity(self.networkActivityId)
let result = Result.resultFromURLSessionResponse(response, data: data, error: error)
self.session?.processResult(result)
self.session?.completionQueue.addOperationWithBlock {
self.completionHandler?(result: result)
return Void()
}
}
}
}
|
0cd15582e4e3203c36ba3c746fe9c452
| 33.538462 | 112 | 0.621133 | false | false | false | false |
cherrywoods/swift-meta-serialization
|
refs/heads/master
|
Examples/Example1/Container.swift
|
apache-2.0
|
1
|
//
// Container.swift
// MetaSerialization
//
// Copyright 2018 cherrywoods
//
// 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
@testable import MetaSerialization
enum Example1Container {
case `nil`
case string(String)
case bool(Bool)
case int(Int)
case double(Double)
case array([Example1Container])
case dictionary([String:Example1Container])
}
extension Example1Container: Hashable {
func hash(into hasher: inout Hasher) {
switch self {
case .nil:
hasher.combine(42)
case .bool(let val):
hasher.combine(val)
case .string(let val):
hasher.combine(val)
case .int(let val):
hasher.combine(val)
case .double(let val):
hasher.combine(val)
case .array(let val):
hasher.combine(val)
case .dictionary(let val):
hasher.combine(val)
}
}
static func ==(lhs: Example1Container, rhs: Example1Container) -> Bool {
switch (lhs, rhs) {
case (.nil, .nil):
return true
case (.bool(let lhv), .bool(let rhv)):
return lhv == rhv
case (.string(let lhv), .string(let rhv)):
return lhv == rhv
case (.int(let lhv), .int(let rhv)):
return lhv == rhv
case (.double(let lhv), .double(let rhv)):
return lhv == rhv
case (.array(let lhv), .array(let rhv)):
return lhv == rhv
case (.dictionary(let lhv), .dictionary(let rhv)):
return lhv == rhv
default:
return false
}
}
}
extension Example1Container: CustomStringConvertible {
var description: String {
switch self {
case .nil:
return "nil"
case .bool(let val):
return val.description
case .string(let val):
return val.description
case .int(let val):
return val.description
case .double(let val):
return val.description
case .array(let val):
return val.description
case .dictionary(let val):
return val.description
}
}
}
|
6b8a37e3bfb1456b8306800aa9a478d9
| 26.245098 | 76 | 0.574667 | false | false | false | false |
imodeveloperlab/ImoTableView
|
refs/heads/development
|
Carthage/Carthage/Checkouts/Fakery/Tests/Fakery/Generators/NameSpec.swift
|
mit
|
3
|
import Quick
import Nimble
@testable import Fakery
final class NameSpec: QuickSpec {
override func spec() {
describe("Name") {
var name: Faker.Name!
beforeEach {
let parser = Parser(locale: "en-TEST")
name = Faker.Name(parser: parser)
}
describe("#name") {
it("returns the correct text") {
let text = name.name()
expect(text).to(equal("Mr. Vadym Markov"))
}
}
describe("#firstName") {
it("returns the correct text") {
let firstName = name.firstName()
expect(firstName).to(equal("Vadym"))
}
}
describe("#lastName") {
it("returns the correct text") {
let lastName = name.lastName()
expect(lastName).to(equal("Markov"))
}
}
describe("#prefix") {
it("returns the correct text") {
let prefix = name.prefix()
expect(prefix).to(equal("Mr."))
}
}
describe("#suffix") {
it("returns the correct text") {
let suffix = name.suffix()
expect(suffix).to(equal("I"))
}
}
describe("#title") {
it("returns the correct text") {
let title = name.title()
expect(title).to(equal("Lead Mobility Engineer"))
}
}
}
}
}
|
1546e4250fec4265624364449d410727
| 22.034483 | 59 | 0.509731 | false | false | false | false |
kperryua/swift
|
refs/heads/master
|
test/attr/attributes.swift
|
apache-2.0
|
2
|
// RUN: %target-parse-verify-swift
@unknown func f0() {} // expected-error{{unknown attribute 'unknown'}}
@unknown(x,y) func f1() {} // expected-error{{unknown attribute 'unknown'}}
enum binary {
case Zero
case One
init() { self = .Zero }
}
func f5(x: inout binary) {}
//===---
//===--- IB attributes
//===---
@IBDesignable
class IBDesignableClassTy {
@IBDesignable func foo() {} // expected-error {{@IBDesignable cannot be applied to this declaration}} {{3-17=}}
}
@IBDesignable // expected-error {{@IBDesignable cannot be applied to this declaration}} {{1-15=}}
struct IBDesignableStructTy {}
@IBDesignable // expected-error {{@IBDesignable cannot be applied to this declaration}} {{1-15=}}
protocol IBDesignableProtTy {}
@IBDesignable // expected-error {{@IBDesignable can only be applied to classes and extensions of classes}} {{1-15=}}
extension IBDesignableStructTy {}
class IBDesignableClassExtensionTy {}
@IBDesignable // okay
extension IBDesignableClassExtensionTy {}
class Inspect {
@IBInspectable var value : Int = 0 // okay
@GKInspectable var value2: Int = 0 // okay
@IBInspectable func foo() {} // expected-error {{@IBInspectable may only be used on 'var' declarations}} {{3-18=}}
@GKInspectable func foo2() {} // expected-error {{@GKInspectable may only be used on 'var' declarations}} {{3-18=}}
@IBInspectable class var cval: Int { return 0 } // expected-error {{only instance properties can be declared @IBInspectable}} {{3-18=}}
@GKInspectable class var cval2: Int { return 0 } // expected-error {{only instance properties can be declared @GKInspectable}} {{3-18=}}
}
@IBInspectable var ibinspectable_global : Int // expected-error {{only instance properties can be declared @IBInspectable}} {{1-16=}}
@GKInspectable var gkinspectable_global : Int // expected-error {{only instance properties can be declared @GKInspectable}} {{1-16=}}
func foo(x: @convention(block) Int) {} // expected-error {{@convention attribute only applies to function types}}
func foo(x: @convention(block) (Int) -> Int) {}
@_transparent
func zim() {}
@_transparent
func zung<T>(_: T) {}
@_transparent // expected-error{{@_transparent cannot be applied to stored properties}} {{1-15=}}
var zippity : Int
func zoom(x: @_transparent () -> ()) { } // expected-error{{attribute can only be applied to declarations, not types}} {{1-1=@_transparent }} {{14-28=}}
protocol ProtoWithTransparent {
@_transparent// expected-error{{@_transparent is not supported on declarations within protocols}} {{3-16=}}
func transInProto()
}
class TestTranspClass : ProtoWithTransparent {
@_transparent // expected-error{{@_transparent is not supported on declarations within classes}} {{3-17=}}
init () {}
@_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{3-17=}}
deinit {}
@_transparent // expected-error{{@_transparent is not supported on declarations within classes}} {{3-17=}}
class func transStatic() {}
@_transparent// expected-error{{@_transparent is not supported on declarations within classes}} {{3-16=}}
func transInProto() {}
}
struct TestTranspStruct : ProtoWithTransparent{
@_transparent
init () {}
@_transparent
init <T> (x : T) { }
@_transparent
static func transStatic() {}
@_transparent
func transInProto() {}
}
@_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}}
struct CannotHaveTransparentStruct {
func m1() {}
}
@_transparent // expected-error{{@_transparent is only supported on struct and enum extensions}} {{1-15=}}
extension TestTranspClass {
func tr1() {}
}
@_transparent
extension TestTranspStruct {
func tr1() {}
}
@_transparent
extension binary {
func tr1() {}
}
class transparentOnCalssVar {
@_transparent var max: Int { return 0xFF }; // expected-error {{@_transparent is not supported on declarations within classes}} {{3-17=}}
func blah () {
var _: Int = max
}
};
class transparentOnCalssVar2 {
var max: Int {
@_transparent // expected-error {{@_transparent is not supported on declarations within classes}} {{5-19=}}
get {
return 0xFF
}
}
func blah () {
var _: Int = max
}
};
@thin // expected-error {{attribute can only be applied to types, not declarations}}
func testThinDecl() -> () {}
protocol Class : class {}
protocol NonClass {}
@objc
class Ty0 : Class, NonClass {
init() { }
}
// Attributes that should be reported by parser as unknown
// See rdar://19533915
@__accessibility struct S__accessibility {} // expected-error{{unknown attribute '__accessibility'}}
@__raw_doc_comment struct S__raw_doc_comment {} // expected-error{{unknown attribute '__raw_doc_comment'}}
@__objc_bridged struct S__objc_bridged {} // expected-error{{unknown attribute '__objc_bridged'}}
weak
var weak0 : Ty0?
weak
var weak0x : Ty0?
weak unowned var weak1 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
weak weak var weak2 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
unowned var weak3 : Ty0
unowned var weak3a : Ty0
unowned(safe) var weak3b : Ty0
unowned(unsafe) var weak3c : Ty0
unowned unowned var weak4 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
unowned weak var weak5 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
weak
var weak6 : Int // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
unowned
var weak7 : Int // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'Int'}}
weak
var weak8 : Class? = Ty0()
unowned var weak9 : Class = Ty0()
weak
var weak10 : NonClass = Ty0() // expected-error {{'weak' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak11 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak12 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak13 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
weak
var weak14 : Ty0 // expected-error {{'weak' variable should have optional type 'Ty0?'}}
weak
var weak15 : Class // expected-error {{'weak' variable should have optional type 'Class?'}}
weak var weak16 : Class!
@weak var weak17 : Class? // expected-error {{'weak' is a declaration modifier, not an attribute}} {{1-2=}}
@_exported var exportVar: Int // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
@_exported func exportFunc() {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
@_exported struct ExportStruct {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
// Function result type attributes.
var func_result_type_attr : () -> @xyz Int // expected-error {{unknown attribute 'xyz'}}
func func_result_attr() -> @xyz Int { // expected-error {{unknown attribute 'xyz'}}
return 4
}
func func_with_unknown_attr1(@unknown(*) x: Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr2(x: @unknown(_) Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr3(x: @unknown(Int) -> Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr4(x: @unknown(Int) throws -> Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr5(x: @unknown (x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr6(x: @unknown(x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected parameter type following ':'}}
func func_with_unknown_attr7(x: @unknown (Int) () -> Int) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected ',' separator}} {{47-47=,}} expected-error {{unnamed parameters must be written with the empty name '_'}} {{48-48=_: }}
func func_type_attribute_with_space(x: @convention (c) () -> Int) {} // OK. Known attributes can have space before its paren.
// @thin is not supported except in SIL.
var thinFunc : @thin () -> () // expected-error {{attribute is not supported}}
@inline(never) func nolineFunc() {}
@inline(never) var noinlineVar : Int // expected-error {{@inline(never) cannot be applied to this declaration}} {{1-16=}}
@inline(never) class FooClass { // expected-error {{@inline(never) cannot be applied to this declaration}} {{1-16=}}
}
@inline(__always) func AlwaysInlineFunc() {}
@inline(__always) var alwaysInlineVar : Int // expected-error {{@inline(__always) cannot be applied to this declaration}} {{1-19=}}
@inline(__always) class FooClass2 { // expected-error {{@inline(__always) cannot be applied to this declaration}} {{1-19=}}
}
class A {
@inline(never) init(a : Int) {}
var b : Int {
@inline(never) get {
return 42
}
@inline(never) set {
}
}
}
class B {
@inline(__always) init(a : Int) {}
var b : Int {
@inline(__always) get {
return 42
}
@inline(__always) set {
}
}
}
class SILStored {
@sil_stored var x : Int = 42 // expected-error {{'sil_stored' only allowed in SIL modules}}
}
@_show_in_interface protocol _underscored {}
@_show_in_interface class _notapplicable {} // expected-error {{may only be used on 'protocol' declarations}}
|
607bcc749269d5faf50bad28de9c67db
| 38.804082 | 256 | 0.693396 | false | false | false | false |
ephread/Instructions
|
refs/heads/main
|
Examples/Example/Unit Tests/Helpers/CoachMarkInnerLayoutHelperTests.swift
|
mit
|
1
|
// Copyright (c) 2016-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import XCTest
@testable import Instructions
// Since we are not going to test static constraints definitions
// this tests will only make sure that the constraints returned are
// not empty.
class CoachMarkInnerLayoutHelperTests: XCTestCase {
let layoutHelper = CoachMarkInnerLayoutHelper()
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testThatVerticalConstraintArrayIsNotEmpty() {
let parent = UIView()
let body = UIView()
parent.addSubview(body)
let constraints =
layoutHelper.verticalConstraints(for: (bodyView: UIView(), arrowView: UIView()),
in: UIView(),
withProperties: (orientation: .bottom,
verticalArrowOffset: 0))
XCTAssertFalse(constraints.isEmpty)
}
func testThatVerticalConstraintArraysAreDifferentDependingOnParameters() {
let parent = UIView()
let body = UIView()
parent.addSubview(body)
let constraints1 =
layoutHelper.verticalConstraints(for: (bodyView: UIView(), arrowView: UIView()),
in: UIView(),
withProperties: (orientation: .bottom,
verticalArrowOffset: 0))
let constraints2 =
layoutHelper.verticalConstraints(for: (bodyView: UIView(), arrowView: UIView()),
in: UIView(),
withProperties: (orientation: .top,
verticalArrowOffset: 0))
XCTAssertFalse(constraints1 == constraints2)
}
// func testThatHorizontalArrowConstraintsAreReturned() {
// let constraint =
// layoutHelper.horizontalArrowConstraints(for: (bodyView: UIView(), arrowView: UIView()),
// withPosition: .center,
// horizontalOffset: 0)
//
// XCTAssertTrue(constraint != nil)
// }
}
|
315d873263d3f87f8f57aac218809dce
| 36.875 | 101 | 0.52764 | false | true | false | false |
blokadaorg/blokada
|
refs/heads/main
|
ios/App/UI/Home/RateAppView.swift
|
mpl-2.0
|
1
|
//
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import SwiftUI
import StoreKit
struct RateAppView: View {
@ObservedObject var contentVM = ViewModels.content
@State var rating = 0
var body: some View {
NavigationView {
VStack {
BlokadaView(animate: true)
.frame(width: 100, height: 100)
Text(L10n.mainRateUsHeader)
.font(.largeTitle)
.bold()
.padding()
Text(L10n.mainRateUsDescription)
.padding()
HStack {
ForEach(1..<6) { number in
Button(action: {
self.rating = number
if number < 4 {
self.contentVM.dismissSheet()
}
}) {
Image(systemName: self.rating < number ? "star" : "star.fill")
.imageScale(.large)
.foregroundColor(self.rating < number ? .secondary : Color.cActivePlus)
.frame(width: 32, height: 32)
}
}
}
VStack {
Text(L10n.mainRateUsOnAppStore)
.multilineTextAlignment(.center)
.lineLimit(3)
.padding()
Button(action: {
self.contentVM.dismissSheet()
requestReview()
}) {
ZStack {
ButtonView(enabled: .constant(true), plus: .constant(true))
.frame(height: 44)
Text(L10n.mainRateUsActionSure)
.foregroundColor(.white)
.bold()
}
}
}
.padding(40)
.opacity(self.rating >= 4 ? 1 : 0)
.animation(.easeInOut)
}
.frame(maxWidth: 500)
.navigationBarItems(trailing:
Button(action: {
self.contentVM.dismissSheet()
}) {
Text(L10n.universalActionDone)
}
.contentShape(Rectangle())
)
}
.navigationViewStyle(StackNavigationViewStyle())
.accentColor(Color.cAccent)
}
}
private func requestReview() {
if let scene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
SKStoreReviewController.requestReview(in: scene)
}
}
struct RateAppView_Previews: PreviewProvider {
static var previews: some View {
Group {
RateAppView()
RateAppView(rating: 3)
.previewDevice(PreviewDevice(rawValue: "iPhone X"))
RateAppView(rating: 5)
.previewDevice(PreviewDevice(rawValue: "iPad Pro (12.9-inch) (3rd generation)"))
}
}
}
/**
In order to open app store:
guard let writeReviewURL = URL(string: "https://itunes.apple.com/app/idXXXXXXXXXX?action=write-review")
else { fatalError("Expected a valid URL") }
UIApplication.shared.open(writeReviewURL, options: [:], completionHandler: nil)
*/
|
aea243a1c04fb201f840d0314624f02e
| 31.747826 | 133 | 0.473181 | false | false | false | false |
IamAlchemist/Animations
|
refs/heads/master
|
Animations/DraggableView.swift
|
mit
|
2
|
//
// DraggableView.swift
// DemoAnimations
//
// Created by wizard on 5/4/16.
// Copyright © 2016 Alchemist. All rights reserved.
//
import UIKit
protocol DraggableViewDelegate : class {
func draggableView(view: DraggableView, draggingEndedWithVelocity velocity: CGPoint)
func draggableViewBeganDraggin(view: DraggableView)
}
class DraggableView : UIView {
weak var delegate : DraggableViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
let recognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan(_:)))
addGestureRecognizer(recognizer)
}
func didPan(recognizer : UIPanGestureRecognizer) {
let point = recognizer.translationInView(superview)
center = CGPoint(x: center.x, y: center.y + point.y)
recognizer.setTranslation(CGPointZero, inView: superview)
if case .Ended = recognizer.state {
var velocity = recognizer.velocityInView(superview)
velocity.x = 0
delegate?.draggableView(self, draggingEndedWithVelocity: velocity)
}
else if case .Began = recognizer.state {
delegate?.draggableViewBeganDraggin(self)
}
}
}
|
6180c7455313a6ed67da9b279cbd616a
| 27.9375 | 92 | 0.650576 | false | false | false | false |
AlbertXYZ/HDCP
|
refs/heads/dev
|
BarsAroundMe/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+Collection.swift
|
apache-2.0
|
47
|
//
// CombineLatest+Collection.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class CombineLatestCollectionTypeSink<C: Collection, O: ObserverType>
: Sink<O> where C.Iterator.Element : ObservableConvertibleType {
typealias R = O.E
typealias Parent = CombineLatestCollectionType<C, R>
typealias SourceElement = C.Iterator.Element.E
let _parent: Parent
let _lock = RecursiveLock()
// state
var _numberOfValues = 0
var _values: [SourceElement?]
var _isDone: [Bool]
var _numberOfDone = 0
var _subscriptions: [SingleAssignmentDisposable]
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_values = [SourceElement?](repeating: nil, count: parent._count)
_isDone = [Bool](repeating: false, count: parent._count)
_subscriptions = Array<SingleAssignmentDisposable>()
_subscriptions.reserveCapacity(parent._count)
for _ in 0 ..< parent._count {
_subscriptions.append(SingleAssignmentDisposable())
}
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceElement>, atIndex: Int) {
_lock.lock(); defer { _lock.unlock() } // {
switch event {
case .next(let element):
if _values[atIndex] == nil {
_numberOfValues += 1
}
_values[atIndex] = element
if _numberOfValues < _parent._count {
let numberOfOthersThatAreDone = self._numberOfDone - (_isDone[atIndex] ? 1 : 0)
if numberOfOthersThatAreDone == self._parent._count - 1 {
forwardOn(.completed)
dispose()
}
return
}
do {
let result = try _parent._resultSelector(_values.map { $0! })
forwardOn(.next(result))
}
catch let error {
forwardOn(.error(error))
dispose()
}
case .error(let error):
forwardOn(.error(error))
dispose()
case .completed:
if _isDone[atIndex] {
return
}
_isDone[atIndex] = true
_numberOfDone += 1
if _numberOfDone == self._parent._count {
forwardOn(.completed)
dispose()
}
else {
_subscriptions[atIndex].dispose()
}
}
// }
}
func run() -> Disposable {
var j = 0
for i in _parent._sources {
let index = j
let source = i.asObservable()
let disposable = source.subscribe(AnyObserver { event in
self.on(event, atIndex: index)
})
_subscriptions[j].setDisposable(disposable)
j += 1
}
return Disposables.create(_subscriptions)
}
}
final class CombineLatestCollectionType<C: Collection, R> : Producer<R> where C.Iterator.Element : ObservableConvertibleType {
typealias ResultSelector = ([C.Iterator.Element.E]) throws -> R
let _sources: C
let _resultSelector: ResultSelector
let _count: Int
init(sources: C, resultSelector: @escaping ResultSelector) {
_sources = sources
_resultSelector = resultSelector
_count = Int(self._sources.count.toIntMax())
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R {
let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
|
32afd34bde85d20dca86c3c63e812a25
| 31.992063 | 139 | 0.521049 | false | false | false | false |
BridgeTheGap/KRAnimationKit
|
refs/heads/master
|
KRAnimationKit/UIViewExtension/UIView+BGColorAnim.swift
|
mit
|
1
|
//
// UIView+BGColorAnim.swift
// KRAnimationKit
//
// Created by Joshua Park on 15/10/2019.
//
import UIKit
import KRTimingFunction
// MARK: - Background color
public extension UIView {
// MARK: - Animate
@discardableResult
func animate(
backgroundColor color: CGColor,
duration: Double,
function: FunctionType = .linear,
reverses: Bool = false,
repeatCount: Float = 0.0,
completion: (() -> Void)? = nil)
-> String
{
return animate(
backgroundColor: color.uiColor,
duration: duration,
function: function,
reverses: reverses,
repeatCount: repeatCount,
completion: completion)
}
@discardableResult
func animate(
backgroundColor color: UIColor,
duration: Double,
function: FunctionType = .linear,
reverses: Bool = false,
repeatCount: Float = 0.0,
completion: (() -> Void)? = nil)
-> String
{
let animDesc = AnimationDescriptor(
view: self,
delay: 0.0,
property: .backgroundColor,
endValue: color,
duration: duration,
function: function)
return KRAnimation.animate(
animDesc,
reverses: reverses,
repeatCount: repeatCount,
completion: completion)
}
// MARK: - Chain
func chain(
backgroundColor color: CGColor,
duration: Double,
function: FunctionType = .linear)
-> [AnimationDescriptor]
{
return chain(backgroundColor: color.uiColor, duration: duration, function: function)
}
func chain(
backgroundColor color: UIColor,
duration: Double,
function: FunctionType = .linear)
-> [AnimationDescriptor]
{
return [
AnimationDescriptor(
view: self,
delay: 0.0,
property: .backgroundColor,
endValue: color,
duration: duration,
function: function),
]
}
}
|
2e502aef16dcfd0533aa4a5027b9d353
| 23.438202 | 92 | 0.535632 | false | false | false | false |
AllisonWangJiaoJiao/KnowledgeAccumulation
|
refs/heads/master
|
11-WKWebProgressDemo/WKWebProgressDemo/BaseWebViewController.swift
|
mit
|
1
|
//
// BaseWebViewController.swift
// EnergyTaxi
//
// Created by Allison on 2017/5/23.
// Copyright © 2017年 Allison. All rights reserved.
//
import UIKit
import WebKit
class BaseWebViewController: UIViewController {
var webView: WKWebView?
var progressView: UIProgressView?
override func viewDidLoad() {
super.viewDidLoad()
//self.view.backgroundColor = UIColor.white
// self.automaticallyAdjustsScrollViewInsets = false
let configuration = WKWebViewConfiguration.init()
// 设置偏好设置
configuration.preferences = WKPreferences.init()
configuration.preferences.minimumFontSize = 16;
configuration.preferences.javaScriptEnabled = true
// 不能自动通过窗口打开
configuration.preferences.javaScriptCanOpenWindowsAutomatically = false
// web内容处理池
configuration.processPool = WKProcessPool.init()
// 通过JS与WebView交互
configuration.userContentController = WKUserContentController.init()
// 注意:self会被强引用(像被某个单例请引用,释放webView也不能释放self),得调用下面的代码才行
// self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "AppModel")
// 注册函数名,注入JS对象名称AppModel,JS调用改函数时WKScriptMessageHandler代理可接收到
configuration.userContentController.add(self as WKScriptMessageHandler, name: "AppModel")
self.webView = WKWebView.init(frame: self.view.bounds, configuration: configuration)
self.view.addSubview(self.webView!)
self.webView?.allowsBackForwardNavigationGestures = true
// 代理代理
self.webView?.navigationDelegate = self
// 与webview UI 交互代理
self.webView?.uiDelegate = self
// KVO
self.webView?.addObserver(self, forKeyPath: "title", options: .new, context: nil)
self.webView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
self.progressView = UIProgressView.init(frame: CGRect(x:0, y:(self.navigationController?.navigationBar.bounds.height)!, width:self.view.frame.size.width, height:5))
self.navigationController?.navigationBar.addSubview(self.progressView!)
self.progressView?.backgroundColor = UIColor.white
self.progressView?.progressTintColor = UIColor.blue
self.progressView?.trackTintColor = UIColor.lightGray
let goFarward = UIBarButtonItem.init(title: "前进", style: .plain, target: self, action: #selector(BaseWebViewController.goFarward))
let goBack = UIBarButtonItem.init(title: "后退", style: .plain, target: self, action: #selector(BaseWebViewController.goBack))
self.navigationItem.rightBarButtonItems = [goBack,goFarward]
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// let Url = Bundle.main.url(forResource: "test", withExtension: "html")
let Url = URL.init(string: "https://github.com")
let request = URLRequest.init(url: Url!)
_ = self.webView?.load(request)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Swift调用JS
self.webView?.evaluateJavaScript("callJsAlert()", completionHandler: { (response, error) in
if (error == nil) {
print(response ?? "")
}else {
print(error?.localizedDescription ?? "")
}
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// 一定要调用,不然self会一直被强引用,就算释放webView也不能将self释放
self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "AppModel")
self.progressView?.removeFromSuperview()
self.webView?.stopLoading()
}
deinit {
self.webView?.removeObserver(self, forKeyPath: "title")
self.webView?.removeObserver(self, forKeyPath: "estimatedProgress")
NSLog("\(self.classForCoder)%@已释放")
}
final func goFarward() {
if (self.webView?.canGoForward == true) {
_ = self.webView?.goForward()
}
}
final func goBack() {
if (self.webView?.canGoBack == true) {
_ = self.webView?.goBack()
}
}
// MARK - KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "title" {
self.navigationItem.title = self.webView?.title
}else if keyPath == "estimatedProgress" {
let estimatedProgress = Float((self.webView?.estimatedProgress)!)
self.progressView?.setProgress(estimatedProgress, animated: true)
//TLOG(estimatedProgress)
}else{
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension BaseWebViewController: WKNavigationDelegate{
// MARK: - WKNavigationDelegate
/// 发送请求前决定是否跳转的代理
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// let hostName = navigationAction.request.url?.host?.lowercased()
// if (navigationAction.navigationType == WKNavigationType.linkActivated && hostName?.contains(".baidu.com") == false) {
// UIApplication.shared.canOpenURL(navigationAction.request.url!)
// decisionHandler(WKNavigationActionPolicy.cancel)
// }else{
// self.progressView?.alpha = 1.0
decisionHandler(WKNavigationActionPolicy.allow)
// }
TLOG("")
}
/// 收到响应后,决定是否跳转的代理
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
decisionHandler(WKNavigationResponsePolicy.allow)
TLOG("")
}
/// 接收到服务器跳转请求的代理
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
TLOG("")
}
/// 准备加载页面
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.progressView?.isHidden = false
self.progressView?.alpha = 1.0
TLOG("")
}
/// 准备加载失败
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
weak var weakSelf = self
UIView.animate(withDuration: 0.25, delay: 0.15, options: .curveEaseOut, animations: {
guard let strongSelf = weakSelf else { return }
strongSelf.progressView?.alpha = 0
}) { (finished) in
guard let strongSelf = weakSelf else { return }
strongSelf.progressView?.progress = 0
strongSelf.progressView?.isHidden = true
}
TLOG("")
}
/// 内容开始加载
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
TLOG("")
}
/// 加载完成
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("showAlert('这是一个弹窗')") { (item, error) in
if (error != nil) {
TLOG(item)
}else {
TLOG(error?.localizedDescription)
}
}
weak var weakSelf = self
UIView.animate(withDuration: 0.25, delay: 0.15, options: .curveEaseOut, animations: {
guard let strongSelf = weakSelf else { return }
strongSelf.progressView?.alpha = 0
}) { (finished) in
guard let strongSelf = weakSelf else { return }
strongSelf.progressView?.progress = 0
strongSelf.progressView?.isHidden = true
}
TLOG("")
}
/// 加载失败
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
weak var weakSelf = self
UIView.animate(withDuration: 0.25, delay: 0.15, options: .curveEaseOut, animations: {
guard let strongSelf = weakSelf else { return }
strongSelf.progressView?.alpha = 0
}) { (finished) in
guard let strongSelf = weakSelf else { return }
strongSelf.progressView?.progress = 0
strongSelf.progressView?.isHidden = true
}
TLOG("")
}
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
TLOG("")
}
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
TLOG("")
}
}
extension BaseWebViewController: WKScriptMessageHandler{
// MARK - WKNavigationDelegate
// JS调用swift注册的函数时回调,message包括JS传的数据
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name.isEqual("AppModel") {
// NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull
print(message.body)
}
}
}
extension BaseWebViewController: WKUIDelegate{
// MARK - WKUIDelegate
// web已关闭
func webViewDidClose(_ webView: WKWebView) {
TLOG("")
}
// 在JS端调用alert函数时(警告弹窗),会触发此代理方法。message :JS端传的数据
// 通过completionHandler()回调JS
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let alertVC = UIAlertController.init(title: "提示", message: message, preferredStyle: .alert)
alertVC.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { (action) in
completionHandler()
}))
self.present(alertVC, animated: true, completion: nil)
TLOG("")
}
// JS端调用confirm函数时(确认、取消弹窗),会触发此方法
// completionHandler(true)返回结果,message :JS端传的数据
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertVC = UIAlertController.init(title: "提示", message: message, preferredStyle: .alert)
alertVC.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { (action) in
completionHandler(true)
}))
alertVC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: { (action) in
completionHandler(false)
}))
self.present(alertVC, animated: true, completion: nil)
TLOG(message)
}
// JS调用prompt函数(输入框)时回调,completionHandler回调结果
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let alertVC = UIAlertController.init(title: "TextInput", message: prompt, preferredStyle: .alert)
alertVC.addTextField { (textField) in
textField.textColor = UIColor.red
textField.placeholder = "TextInput"
}
alertVC.addAction(UIAlertAction.init(title: "确定", style: .cancel, handler: { (action) in
completionHandler(alertVC.textFields?.last?.text)
}))
self.present(alertVC, animated: true, completion: nil)
TLOG(prompt)
}
}
|
5672e7d2b6ef72ebfdae38c8ff97987e
| 34.66568 | 201 | 0.63061 | false | false | false | false |
grandiere/box
|
refs/heads/master
|
box/View/GridVisorDetail/Cells/VGridVisorDetailCellAge.swift
|
mit
|
1
|
import UIKit
class VGridVisorDetailCellAge:VGridVisorDetailCell
{
private weak var labelAge:UILabel!
private weak var layoutIconLeft:NSLayoutConstraint!
private let kIconWidth:CGFloat = 36
private let kIconRight:CGFloat = 10
private let kLabelWidth:CGFloat = 250
override init(frame:CGRect)
{
super.init(frame:frame)
isUserInteractionEnabled = false
let labelAge:UILabel = UILabel()
labelAge.translatesAutoresizingMaskIntoConstraints = false
labelAge.isUserInteractionEnabled = false
labelAge.backgroundColor = UIColor.clear
labelAge.font = UIFont.regular(size:14)
labelAge.textColor = UIColor.black
labelAge.textAlignment = NSTextAlignment.right
self.labelAge = labelAge
let icon:UIImageView = UIImageView()
icon.isUserInteractionEnabled = false
icon.translatesAutoresizingMaskIntoConstraints = false
icon.clipsToBounds = true
icon.contentMode = UIViewContentMode.center
icon.image = #imageLiteral(resourceName: "assetGenericAge")
addSubview(labelAge)
addSubview(icon)
NSLayoutConstraint.equalsVertical(
view:icon,
toView:self)
layoutIconLeft = NSLayoutConstraint.leftToLeft(
view:icon,
toView:self)
NSLayoutConstraint.width(
view:icon,
constant:kIconWidth)
NSLayoutConstraint.equalsVertical(
view:labelAge,
toView:self)
NSLayoutConstraint.rightToLeft(
view:labelAge,
toView:icon)
NSLayoutConstraint.width(
view:labelAge,
constant:kLabelWidth)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
let width:CGFloat = bounds.maxX
let remainLeft:CGFloat = width - kIconWidth
let marginLeft:CGFloat = remainLeft / 2.0
layoutIconLeft.constant = marginLeft + kIconRight
super.layoutSubviews()
}
override func config(controller:CGridVisorDetail, model:MGridVisorDetailProtocol)
{
super.config(controller:controller, model:model)
guard
let modelAge:MGridVisorDetailAge = model as? MGridVisorDetailAge
else
{
return
}
labelAge.text = modelAge.age
}
}
|
56bfa3f3d6c634163910798cb1130ad7
| 28.232558 | 85 | 0.618536 | false | false | false | false |
qiandashuai/YH-IOS
|
refs/heads/master
|
YH-IOS/Components/Mine/InstituteViewController.swift
|
gpl-3.0
|
1
|
//
// InstituteViewController.swift
// YH-IOS
//
// Created by 钱宝峰 on 2017/6/7.
// Copyright © 2017年 com.intfocus. All rights reserved.
//
import UIKit
class InstituteViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//view.backgroundColor = UIColor.blue
let imageAvater:UIImageView = UIImageView()
imageAvater.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
let imageUrl:URL = URL(string: "http://upload-images.jianshu.io/upload_images/1567375-1d1283291a093bbc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240")!
imageAvater.sd_setAnimationImages(with:[imageUrl])
imageAvater.backgroundColor = UIColor.red
view.addSubview(imageAvater)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
f97c4fbd8185c77bad618d519c60a6f8
| 31.926829 | 168 | 0.683704 | false | false | false | false |
RevenueCat/purchases-ios
|
refs/heads/main
|
Tests/UnitTests/Purchasing/Purchases/PurchasesConfiguringTests.swift
|
mit
|
1
|
//
// 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
//
// PurchasesConfiguringTests.swift
//
// Created by Nacho Soto on 5/25/22.
import Nimble
import XCTest
@testable import RevenueCat
class PurchasesConfiguringTests: BasePurchasesTests {
func testIsAbleToBeInitialized() {
self.setupPurchases()
expect(self.purchases).toNot(beNil())
}
func testUsingSharedInstanceWithoutInitializingThrowsAssertion() {
let expectedMessage = "Purchases has not been configured. Please call Purchases.configure()"
expectFatalError(expectedMessage: expectedMessage) { _ = Purchases.shared }
}
func testUsingSharedInstanceAfterInitializingDoesntThrowAssertion() {
self.setupPurchases()
expectNoFatalError { _ = Purchases.shared }
}
func testIsConfiguredReturnsCorrectvalue() {
expect(Purchases.isConfigured) == false
self.setupPurchases()
expect(Purchases.isConfigured) == true
}
func testConfigurationPassedThroughTimeouts() {
let networkTimeoutSeconds: TimeInterval = 9
let configurationBuilder = Configuration.Builder(withAPIKey: "")
.with(networkTimeout: networkTimeoutSeconds)
.with(storeKit1Timeout: networkTimeoutSeconds)
let purchases = Purchases.configure(with: configurationBuilder.build())
expect(purchases.networkTimeout) == networkTimeoutSeconds
expect(purchases.storeKitTimeout) == networkTimeoutSeconds
}
func testSharedInstanceIsSetWhenConfiguring() {
let purchases = Purchases.configure(withAPIKey: "")
expect(Purchases.shared) === purchases
}
func testSharedInstanceIsSetWhenConfiguringWithConfiguration() {
let configurationBuilder = Configuration.Builder(withAPIKey: "")
let purchases = Purchases.configure(with: configurationBuilder.build())
expect(Purchases.shared) === purchases
}
@available(*, deprecated) // Ignore deprecation warnings
func testSharedInstanceIsSetWhenConfiguringWithAppUserID() {
let purchases = Purchases.configure(withAPIKey: "", appUserID: "")
expect(Purchases.shared) === purchases
}
@available(*, deprecated) // Ignore deprecation warnings
func testSharedInstanceIsSetWhenConfiguringWithObserverMode() {
let purchases = Purchases.configure(withAPIKey: "", appUserID: "", observerMode: true)
expect(Purchases.shared) === purchases
expect(Purchases.shared.finishTransactions) == false
}
@available(*, deprecated) // Ignore deprecation warnings
func testSharedInstanceIsSetWhenConfiguringWithAppUserIDAndUserDefaults() {
let purchases = Purchases.configure(withAPIKey: "", appUserID: "", observerMode: false, userDefaults: nil)
expect(Purchases.shared) === purchases
expect(Purchases.shared.finishTransactions) == true
}
@available(*, deprecated) // Ignore deprecation warnings
func testSharedInstanceIsSetWhenConfiguringWithAppUserIDAndUserDefaultsAndUseSK2() {
let purchases = Purchases.configure(withAPIKey: "",
appUserID: "",
observerMode: false,
userDefaults: nil,
useStoreKit2IfAvailable: true)
expect(Purchases.shared) === purchases
expect(Purchases.shared.finishTransactions) == true
}
func testFirstInitializationCallDelegate() {
self.setupPurchases()
expect(self.purchasesDelegate.customerInfoReceivedCount).toEventually(equal(1))
}
func testFirstInitializationFromForegroundDelegateForAnonIfNothingCached() {
self.systemInfo.stubbedIsApplicationBackgrounded = false
self.setupPurchases()
expect(self.purchasesDelegate.customerInfoReceivedCount).toEventually(equal(1))
}
func testFirstInitializationFromBackgroundDoesntCallDelegateForAnonIfNothingCached() {
self.systemInfo.stubbedIsApplicationBackgrounded = true
self.setupPurchases()
expect(self.purchasesDelegate.customerInfoReceivedCount).toEventually(equal(0))
}
func testFirstInitializationFromBackgroundCallsDelegateForAnonIfInfoCached() throws {
self.systemInfo.stubbedIsApplicationBackgrounded = true
let info = try CustomerInfo(data: Self.emptyCustomerInfoData)
let object = try info.asData()
self.deviceCache.cachedCustomerInfo[identityManager.currentAppUserID] = object
self.setupPurchases()
expect(self.purchasesDelegate.customerInfoReceivedCount).toEventually(equal(1))
expect(self.purchasesDelegate.customerInfo) == info
}
func testSettingTheDelegateAfterInitializationSendsCachedCustomerInfo() throws {
let info = try CustomerInfo(data: Self.emptyCustomerInfoData)
let object = try info.asData()
self.deviceCache.cachedCustomerInfo[identityManager.currentAppUserID] = object
self.setupPurchases(withDelegate: false)
expect(self.purchasesDelegate.customerInfoReceivedCount) == 0
self.purchases.delegate = self.purchasesDelegate
expect(self.purchasesDelegate.customerInfoReceivedCount) == 1
expect(self.purchasesDelegate.customerInfo) == info
}
func testSettingTheDelegateLaterPastInitializationSendsCachedCustomerInfo() throws {
let info = try CustomerInfo(data: Self.emptyCustomerInfoData)
let object = try info.asData()
self.deviceCache.cachedCustomerInfo[identityManager.currentAppUserID] = object
self.setupPurchases(withDelegate: false)
expect(self.purchasesDelegate.customerInfoReceivedCount) == 0
let expectation = XCTestExpectation()
DispatchQueue.main.async {
self.purchases.delegate = self.purchasesDelegate
expect(self.purchasesDelegate.customerInfoReceivedCount) == 1
expect(self.purchasesDelegate.customerInfo) == info
expectation.fulfill()
}
self.wait(for: [expectation], timeout: 5)
}
func testFirstInitializationFromBackgroundDoesntUpdateCustomerInfoCache() {
self.systemInfo.stubbedIsApplicationBackgrounded = true
self.setupPurchases()
expect(self.backend.getSubscriberCallCount).toEventually(equal(0))
}
func testFirstInitializationFromForegroundUpdatesCustomerInfoCacheIfNotInUserDefaults() {
self.systemInfo.stubbedIsApplicationBackgrounded = false
self.setupPurchases()
expect(self.backend.getSubscriberCallCount).toEventually(equal(1))
}
func testFirstInitializationFromForegroundUpdatesCustomerInfoCacheIfUserDefaultsCacheStale() {
let staleCacheDateForForeground = Calendar.current.date(byAdding: .minute, value: -20, to: Date())!
self.deviceCache.setCustomerInfoCache(timestamp: staleCacheDateForForeground,
appUserID: identityManager.currentAppUserID)
self.systemInfo.stubbedIsApplicationBackgrounded = false
self.setupPurchases()
expect(self.backend.getSubscriberCallCount).toEventually(equal(1))
}
func testFirstInitializationFromForegroundUpdatesCustomerInfoEvenIfCacheValid() {
let staleCacheDateForForeground = Calendar.current.date(byAdding: .minute, value: -2, to: Date())!
self.deviceCache.setCustomerInfoCache(timestamp: staleCacheDateForForeground,
appUserID: identityManager.currentAppUserID)
self.systemInfo.stubbedIsApplicationBackgrounded = false
self.setupPurchases()
expect(self.backend.getSubscriberCallCount).toEventually(equal(1))
}
func testProxyURL() {
expect(SystemInfo.proxyURL).to(beNil())
let defaultHostURL = URL(string: "https://api.revenuecat.com")
expect(SystemInfo.serverHostURL) == defaultHostURL
let testURL = URL(string: "https://test_url")
Purchases.proxyURL = testURL
expect(SystemInfo.serverHostURL) == testURL
Purchases.proxyURL = nil
expect(SystemInfo.serverHostURL) == defaultHostURL
}
func testIsAnonymous() {
setupAnonPurchases()
expect(self.purchases.isAnonymous).to(beTrue())
}
func testIsNotAnonymous() {
setupPurchases()
expect(self.purchases.isAnonymous).to(beFalse())
}
func testSetsSelfAsStoreKit1WrapperDelegate() {
self.setupPurchases()
expect(self.storeKit1Wrapper.delegate) === self.purchasesOrchestrator
}
func testSetsSelfAsStoreKit1WrapperDelegateForSK1() {
let configurationBuilder = Configuration.Builder(withAPIKey: "")
.with(usesStoreKit2IfAvailable: false)
let purchases = Purchases.configure(with: configurationBuilder.build())
expect(purchases.isStoreKit1Configured) == true
}
func testDoesNotInitializeSK1IfSK2Enabled() throws {
try AvailabilityChecks.iOS15APIAvailableOrSkipTest()
let configurationBuilder = Configuration.Builder(withAPIKey: "")
.with(usesStoreKit2IfAvailable: true)
let purchases = Purchases.configure(with: configurationBuilder.build())
expect(purchases.isStoreKit1Configured) == false
}
func testSetsPaymentQueueWrapperDelegateToPurchasesOrchestratorIfSK1IsEnabled() {
self.systemInfo = MockSystemInfo(finishTransactions: false,
storeKit2Setting: .disabled)
self.setupPurchases()
expect(self.paymentQueueWrapper.delegate).to(beNil())
}
func testSetsPaymentQueueWrapperDelegateToPaymentQueueWrapperIfSK1IsNotEnabled() throws {
try AvailabilityChecks.iOS15APIAvailableOrSkipTest()
self.systemInfo = MockSystemInfo(finishTransactions: false,
storeKit2Setting: .enabledForCompatibleDevices)
self.setupPurchases()
expect(self.paymentQueueWrapper.delegate) === self.purchasesOrchestrator
}
// MARK: - UserDefaults
func testCustomUserDefaultsIsUsed() {
expect(Self.create(userDefaults: Self.customUserDefaults).configuredUserDefaults) === Self.customUserDefaults
}
func testDefaultUserDefaultsIsUsedByDefault() {
expect(Self.create(userDefaults: nil).configuredUserDefaults) === UserDefaults.computeDefault()
}
private static func create(userDefaults: UserDefaults?) -> Purchases {
var configurationBuilder: Configuration.Builder = .init(withAPIKey: "")
if let userDefaults = userDefaults {
configurationBuilder = configurationBuilder.with(userDefaults: userDefaults)
}
return Purchases.configure(with: configurationBuilder.build())
}
private static let customUserDefaults: UserDefaults = .init(suiteName: "com.revenuecat.testing_user_defaults")!
}
|
c97d41fe1047aeecdd8ce0bca79fd5c6
| 37.8125 | 117 | 0.704419 | false | true | false | false |
DayLogger/ADVOperation
|
refs/heads/master
|
Source/GroupOperation.swift
|
unlicense
|
1
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows how operations can be composed together to form new operations.
*/
import Foundation
/**
A subclass of `Operation` that executes zero or more operations as part of its
own execution. This class of operation is very useful for abstracting several
smaller operations into a larger operation. As an example, the `GetEarthquakesOperation`
is composed of both a `DownloadEarthquakesOperation` and a `ParseEarthquakesOperation`.
Additionally, `GroupOperation`s are useful if you establish a chain of dependencies,
but part of the chain may "loop". For example, if you have an operation that
requires the user to be authenticated, you may consider putting the "login"
operation inside a group operation. That way, the "login" operation may produce
subsequent operations (still within the outer `GroupOperation`) that will all
be executed before the rest of the operations in the initial chain of operations.
*/
public class GroupOperation: Operation {
private let internalQueue = OperationQueue()
private let finishingOperation = NSBlockOperation(block: {})
private var aggregatedErrors = [NSError]()
convenience public init(operations: NSOperation...) {
self.init(operations: operations)
}
public init(operations: [NSOperation]) {
super.init()
internalQueue.suspended = true
internalQueue.delegate = self
for operation in operations {
internalQueue.addOperation(operation)
}
}
override public func cancel() {
internalQueue.cancelAllOperations()
super.cancel()
}
override public func execute() {
internalQueue.suspended = false
internalQueue.addOperation(finishingOperation)
}
public func addOperation(operation: NSOperation) {
internalQueue.addOperation(operation)
}
/**
Note that some part of execution has produced an error.
Errors aggregated through this method will be included in the final array
of errors reported to observers and to the `finished(_:)` method.
*/
public final func aggregateError(error: NSError) {
aggregatedErrors.append(error)
}
public func operationDidFinish(operation: NSOperation, withErrors errors: [NSError]) {
// For use by subclassers.
}
}
extension GroupOperation: OperationQueueDelegate {
final func operationQueue(operationQueue: OperationQueue, willAddOperation operation: NSOperation) {
assert(!finishingOperation.finished && !finishingOperation.executing, "cannot add new operations to a group after the group has completed")
/*
Some operation in this group has produced a new operation to execute.
We want to allow that operation to execute before the group completes,
so we'll make the finishing operation dependent on this newly-produced operation.
*/
if operation !== finishingOperation {
finishingOperation.addDependency(operation)
}
}
final func operationQueue(operationQueue: OperationQueue, operationDidFinish operation: NSOperation, withErrors errors: [NSError]) {
aggregatedErrors.appendContentsOf(errors)
if operation === finishingOperation {
internalQueue.suspended = true
finish(aggregatedErrors)
}
else {
operationDidFinish(operation, withErrors: errors)
}
}
}
|
45c5c1de12c58937eae98b28aef87883
| 36.030303 | 147 | 0.690671 | false | false | false | false |
littlelightwang/firefox-ios
|
refs/heads/master
|
Client/Frontend/Tabs/TabsViewController.swift
|
mpl-2.0
|
2
|
/* 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 Alamofire
import Storage
class TabsViewController: UITableViewController
{
private var TABS_HEADER_IDENTIFIER = "TABS_HEADER"
private var TABS_CELL_IDENTIFIER = "TABS_CELL"
var profile: Profile!
var tabsResponse: TabsResponse?
override func viewDidLoad()
{
super.viewDidLoad()
tableView.sectionFooterHeight = 0
//tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: TABS_CELL_IDENTIFIER);
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
let nib = UINib(nibName: "TabsViewControllerHeader", bundle: nil);
tableView.registerNib(nib, forHeaderFooterViewReuseIdentifier: TABS_HEADER_IDENTIFIER)
}
func reloadData() {
Alamofire.request(.GET, "https://syncapi-dev.sateh.com/1.0/tabs")
.authenticate(user: "[email protected]", password: "q1w2e3r4") // TODO: Get rid of test account and use AccountManager and TabProvider to obtain tabs.
.responseJSON { (request, response, data, error) in
self.tabsResponse = parseTabsResponse(data)
dispatch_async(dispatch_get_main_queue()) {
self.refreshControl?.endRefreshing()
self.tableView.reloadData()
}
}
}
func refresh() {
reloadData()
}
override func viewDidAppear(animated: Bool) {
reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if let r = tabsResponse {
return r.clients.count
} else {
return 0
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let r = tabsResponse {
return r.clients[section].tabs.count
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(TABS_CELL_IDENTIFIER, forIndexPath: indexPath) as UITableViewCell
if let tab = tabsResponse?.clients[indexPath.section].tabs[indexPath.row] {
// TODO: We need better async image loading here
let opts = QueryOptions()
opts.filter = tab.url
cell.textLabel?.text = tab.title
}
cell.textLabel?.font = UIFont(name: "FiraSans-SemiBold", size: 13)
cell.textLabel?.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor.darkGrayColor()
cell.indentationWidth = 20
return cell
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 42
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(TABS_HEADER_IDENTIFIER) as? UIView
if let label = view?.viewWithTag(1) as? UILabel {
if let response = tabsResponse {
let client = response.clients[section]
label.text = client.name
}
}
return view
}
// func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
// let objects = UINib(nibName: "TabsViewControllerHeader", bundle: nil).instantiateWithOwner(nil, options: nil)
// if let view = objects[0] as? UIView {
// if let label = view.viewWithTag(1) as? UILabel {
// // TODO: More button
// }
// }
// return view
// }
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let tab = tabsResponse?.clients[indexPath.section].tabs[indexPath.row] {
UIApplication.sharedApplication().openURL(NSURL(string: tab.url)!)
}
}
}
|
2663a18cfa7ddb610c9322dc3f912415
| 37.231405 | 172 | 0.641591 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/FeatureDashboard/Sources/FeatureDashboardUI/Components/SimpleBalanceCell/SimpleBalanceTableViewCell.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import PlatformUIKit
import RxCocoa
import RxSwift
final class SimpleBalanceTableViewCell: UITableViewCell {
/// Presenter should be injected
var presenter: HistoricalBalanceCellPresenter? {
willSet { disposeBag = DisposeBag() }
didSet {
guard let presenter = presenter else {
assetBalanceView.presenter = nil
badgeImageView.viewModel = nil
assetTitleLabel.content = .empty
return
}
assetBalanceView.presenter = presenter.balancePresenter
presenter.thumbnail
.drive(badgeImageView.rx.viewModel)
.disposed(by: disposeBag)
presenter.name
.drive(assetTitleLabel.rx.content)
.disposed(by: disposeBag)
presenter.assetNetworkContent
.compactMap { $0 }
.drive(assetNetworkLabel.rx.content)
.disposed(by: disposeBag)
presenter.assetNetworkContent
.map { $0 == nil }
.drive(tagView.rx.isHidden)
.disposed(by: disposeBag)
presenter.displayCode
.drive(assetCodeLabel.rx.content)
.disposed(by: disposeBag)
}
}
private var disposeBag = DisposeBag()
// MARK: Private IBOutlets
private var assetTitleLabel: UILabel = .init()
private var assetCodeLabel: UILabel = .init()
private var tagView = UIView()
private var assetNetworkLabel: UILabel = .init()
private var badgeImageView: BadgeImageView = .init()
private var assetBalanceView: AssetBalanceView = .init()
private var bottomSeparatorView: UIView = .init()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
// MARK: - Lifecycle
@available(*, unavailable)
required init?(coder: NSCoder) { nil }
override func prepareForReuse() {
super.prepareForReuse()
presenter = nil
}
// MARK: - Private
private func setup() {
contentView.addSubview(badgeImageView)
contentView.addSubview(assetBalanceView)
contentView.addSubview(bottomSeparatorView)
assetTitleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
assetTitleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
assetTitleLabel.numberOfLines = 1
tagView.addSubview(assetNetworkLabel)
tagView.isHidden = true
tagView.layer.cornerRadius = 4
tagView.layer.borderColor = UIColor.gray2.cgColor
tagView.layer.borderWidth = 1
assetNetworkLabel.layoutToSuperview(.centerX, .centerY)
assetNetworkLabel.layoutToSuperview(.top, offset: 3)
assetNetworkLabel.layoutToSuperview(.left, offset: Spacing.standard)
assetNetworkLabel.layoutToSuperview(.right, offset: -Spacing.standard)
assetNetworkLabel.layoutToSuperview(.bottom, offset: -3)
let assetCodeAndBadgeContainer = UIStackView(
arrangedSubviews: [assetCodeLabel, tagView]
)
assetCodeAndBadgeContainer.axis = .horizontal
assetCodeAndBadgeContainer.alignment = .center
assetCodeAndBadgeContainer.spacing = Spacing.standard
let assetStackView = UIStackView(
arrangedSubviews: [assetTitleLabel, assetCodeAndBadgeContainer]
)
assetStackView.spacing = Spacing.interItem
assetStackView.axis = .vertical
assetStackView.alignment = .top
contentView.addSubview(assetStackView)
assetStackView.layoutToSuperview(.centerY)
assetStackView.layoutToSuperview(.top, relation: .greaterThanOrEqual, offset: Spacing.inner)
assetStackView.layout(edge: .leading, to: .trailing, of: badgeImageView, offset: Spacing.inner)
assetStackView.layoutToSuperview(.bottom, relation: .lessThanOrEqual, offset: Spacing.inner)
assetStackView.layout(edge: .trailing, to: .leading, of: assetBalanceView, offset: -Spacing.inner)
badgeImageView.layout(dimension: .height, to: 32)
badgeImageView.layout(dimension: .width, to: 32)
badgeImageView.layoutToSuperview(.centerY)
badgeImageView.layoutToSuperview(.leading, offset: Spacing.inner)
assetBalanceView.layout(to: .top, of: assetStackView)
assetBalanceView.layoutToSuperview(.centerY)
assetBalanceView.layoutToSuperview(.trailing, offset: -Spacing.inner)
assetBalanceView.layoutToSuperview(.bottom, relation: .lessThanOrEqual, offset: Spacing.inner)
bottomSeparatorView.layout(dimension: .height, to: 1)
bottomSeparatorView.layoutToSuperview(.trailing, priority: .defaultHigh)
bottomSeparatorView.layoutToSuperview(.bottom, priority: .defaultHigh)
bottomSeparatorView.layoutToSuperview(.width, relation: .equal, ratio: 0.82)
bottomSeparatorView.backgroundColor = .lightBorder
assetBalanceView.shimmer(
estimatedFiatLabelSize: CGSize(width: 90, height: 16),
estimatedCryptoLabelSize: CGSize(width: 100, height: 14)
)
}
}
|
19daee7e8a5a23e99a5fc9b5a6fcb410
| 38.125 | 106 | 0.674121 | false | false | false | false |
onmyway133/Github.swift
|
refs/heads/master
|
Carthage/Checkouts/Sugar/Source/Shared/Extensions/NSDate+Compare.swift
|
mit
|
1
|
import Foundation
extension NSDate : Comparable {}
public func < (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}
public func <= (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 <= rhs.timeIntervalSince1970
}
public func >= (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 >= rhs.timeIntervalSince1970
}
public func > (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 > rhs.timeIntervalSince1970
}
// MARK: - Components
public extension NSDate {
public func components(unit: NSCalendarUnit, retrieval: NSDateComponents -> Int) -> Int {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(unit, fromDate: self)
return retrieval(components)
}
public var second: Int {
return components(.Second) {
return $0.second
}
}
public var minute: Int {
return components(.Minute) {
return $0.minute
}
}
public var hour: Int {
return components(.Hour) {
return $0.hour
}
}
public var day: Int {
return components(.Day) {
return $0.day
}
}
public var month: Int {
return components(.Month) {
return $0.month
}
}
public var year: Int {
return components(.Year) {
return $0.year
}
}
public var weekday: Int {
return components(.Weekday) {
return $0.weekday
}
}
}
|
04cf5ec83dad1b9cf92b0075376d435d
| 19.150685 | 91 | 0.64378 | false | false | false | false |
zvonler/PasswordElephant
|
refs/heads/master
|
external/github.com/apple/swift-protobuf/Tests/SwiftProtobufTests/Test_JSON.swift
|
gpl-3.0
|
1
|
// Tests/SwiftProtobufTests/Test_JSON.swift - Exercise JSON coding
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// JSON is a major new feature for Proto3. This test suite exercises
/// the JSON coding for all primitive types, including boundary and error
/// cases.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
import SwiftProtobuf
class Test_JSON: XCTestCase, PBTestHelpers {
typealias MessageTestType = Proto3Unittest_TestAllTypes
private func configureLargeObject(_ o: inout MessageTestType) {
o.optionalInt32 = 1
o.optionalInt64 = 2
o.optionalUint32 = 3
o.optionalUint64 = 4
o.optionalSint32 = 5
o.optionalSint64 = 6
o.optionalFixed32 = 7
o.optionalFixed64 = 8
o.optionalSfixed32 = 9
o.optionalSfixed64 = 10
o.optionalFloat = 11
o.optionalDouble = 12
o.optionalBool = true
o.optionalString = "abc"
o.optionalBytes = Data(bytes: [65, 66])
var nested = MessageTestType.NestedMessage()
nested.bb = 7
o.optionalNestedMessage = nested
var foreign = Proto3Unittest_ForeignMessage()
foreign.c = 88
o.optionalForeignMessage = foreign
var importMessage = ProtobufUnittestImport_ImportMessage()
importMessage.d = -9
o.optionalImportMessage = importMessage
o.optionalNestedEnum = .baz
o.optionalForeignEnum = .foreignBaz
var publicImportMessage = ProtobufUnittestImport_PublicImportMessage()
publicImportMessage.e = -999999
o.optionalPublicImportMessage = publicImportMessage
o.repeatedInt32 = [1, 2]
o.repeatedInt64 = [3, 4]
o.repeatedUint32 = [5, 6]
o.repeatedUint64 = [7, 8]
o.repeatedSint32 = [9, 10]
o.repeatedSint64 = [11, 12]
o.repeatedFixed32 = [13, 14]
o.repeatedFixed64 = [15, 16]
o.repeatedSfixed32 = [17, 18]
o.repeatedSfixed64 = [19, 20]
o.repeatedFloat = [21, 22]
o.repeatedDouble = [23, 24]
o.repeatedBool = [true, false]
o.repeatedString = ["abc", "def"]
o.repeatedBytes = [Data(), Data(bytes: [65, 66])]
var nested2 = nested
nested2.bb = -7
o.repeatedNestedMessage = [nested, nested2]
var foreign2 = foreign
foreign2.c = -88
o.repeatedForeignMessage = [foreign, foreign2]
var importMessage2 = importMessage
importMessage2.d = 999999
o.repeatedImportMessage = [importMessage, importMessage2]
o.repeatedNestedEnum = [.bar, .baz]
o.repeatedForeignEnum = [.foreignBar, .foreignBaz]
var publicImportMessage2 = publicImportMessage
publicImportMessage2.e = 999999
o.oneofUint32 = 99
}
func testMultipleFields() {
let expected: String = ("{"
+ "\"optionalInt32\":1,"
+ "\"optionalInt64\":\"2\","
+ "\"optionalUint32\":3,"
+ "\"optionalUint64\":\"4\","
+ "\"optionalSint32\":5,"
+ "\"optionalSint64\":\"6\","
+ "\"optionalFixed32\":7,"
+ "\"optionalFixed64\":\"8\","
+ "\"optionalSfixed32\":9,"
+ "\"optionalSfixed64\":\"10\","
+ "\"optionalFloat\":11,"
+ "\"optionalDouble\":12,"
+ "\"optionalBool\":true,"
+ "\"optionalString\":\"abc\","
+ "\"optionalBytes\":\"QUI=\","
+ "\"optionalNestedMessage\":{\"bb\":7},"
+ "\"optionalForeignMessage\":{\"c\":88},"
+ "\"optionalImportMessage\":{\"d\":-9},"
+ "\"optionalNestedEnum\":\"BAZ\","
+ "\"optionalForeignEnum\":\"FOREIGN_BAZ\","
+ "\"optionalPublicImportMessage\":{\"e\":-999999},"
+ "\"repeatedInt32\":[1,2],"
+ "\"repeatedInt64\":[\"3\",\"4\"],"
+ "\"repeatedUint32\":[5,6],"
+ "\"repeatedUint64\":[\"7\",\"8\"],"
+ "\"repeatedSint32\":[9,10],"
+ "\"repeatedSint64\":[\"11\",\"12\"],"
+ "\"repeatedFixed32\":[13,14],"
+ "\"repeatedFixed64\":[\"15\",\"16\"],"
+ "\"repeatedSfixed32\":[17,18],"
+ "\"repeatedSfixed64\":[\"19\",\"20\"],"
+ "\"repeatedFloat\":[21,22],"
+ "\"repeatedDouble\":[23,24],"
+ "\"repeatedBool\":[true,false],"
+ "\"repeatedString\":[\"abc\",\"def\"],"
+ "\"repeatedBytes\":[\"\",\"QUI=\"],"
+ "\"repeatedNestedMessage\":[{\"bb\":7},{\"bb\":-7}],"
+ "\"repeatedForeignMessage\":[{\"c\":88},{\"c\":-88}],"
+ "\"repeatedImportMessage\":[{\"d\":-9},{\"d\":999999}],"
+ "\"repeatedNestedEnum\":[\"BAR\",\"BAZ\"],"
+ "\"repeatedForeignEnum\":[\"FOREIGN_BAR\",\"FOREIGN_BAZ\"],"
+ "\"oneofUint32\":99"
+ "}")
assertJSONEncode(expected, configure: configureLargeObject)
}
// See if we can crash the JSON parser by trying every possible
// truncation of the large message above.
func testTruncation() throws {
var m = MessageTestType()
configureLargeObject(&m)
let s = try m.jsonString()
#if swift(>=3.2)
let chars = s
#else
let chars = s.characters
#endif
var truncated = ""
for c in chars {
truncated.append(c)
do {
_ = try MessageTestType(jsonString: truncated)
} catch _ {
continue
}
}
}
func testOptionalInt32() {
assertJSONEncode("{\"optionalInt32\":1}") {(o: inout MessageTestType) in
o.optionalInt32 = 1
}
assertJSONEncode("{\"optionalInt32\":2147483647}") {(o: inout MessageTestType) in
o.optionalInt32 = Int32.max
}
assertJSONEncode("{\"optionalInt32\":-2147483648}") {(o: inout MessageTestType) in
o.optionalInt32 = Int32.min
}
// 32-bit overflow
assertJSONDecodeFails("{\"optionalInt32\":2147483648}")
// Explicit 'null' is permitted, proto3 decodes it to default value
assertJSONDecodeSucceeds("{\"optionalInt32\":null}") {(o:MessageTestType) in
o.optionalInt32 == 0}
// Quoted or unquoted numbers, positive, negative, or zero
assertJSONDecodeSucceeds("{\"optionalInt32\":1}") {(o:MessageTestType) in
o.optionalInt32 == 1}
assertJSONDecodeSucceeds("{\"optionalInt32\":\"1\"}") {(o:MessageTestType) in
o.optionalInt32 == 1}
assertJSONDecodeSucceeds("{\"optionalInt32\":\"\\u0030\"}") {(o:MessageTestType) in
o.optionalInt32 == 0}
assertJSONDecodeSucceeds("{\"optionalInt32\":\"\\u0031\"}") {(o:MessageTestType) in
o.optionalInt32 == 1}
assertJSONDecodeSucceeds("{\"optionalInt32\":\"\\u00310\"}") {(o:MessageTestType) in
o.optionalInt32 == 10}
assertJSONDecodeSucceeds("{\"optionalInt32\":0}") {(o:MessageTestType) in
o.optionalInt32 == 0}
assertJSONDecodeSucceeds("{\"optionalInt32\":\"0\"}") {(o:MessageTestType) in
o.optionalInt32 == 0}
assertJSONDecodeSucceeds("{\"optionalInt32\":-0}") {(o:MessageTestType) in
o.optionalInt32 == 0}
assertJSONDecodeSucceeds("{\"optionalInt32\":\"-0\"}") {(o:MessageTestType) in
o.optionalInt32 == 0}
assertJSONDecodeSucceeds("{\"optionalInt32\":-1}") {(o:MessageTestType) in
o.optionalInt32 == -1}
assertJSONDecodeSucceeds("{\"optionalInt32\":\"-1\"}") {(o:MessageTestType) in
o.optionalInt32 == -1}
// JSON RFC does not accept leading zeros
assertJSONDecodeFails("{\"optionalInt32\":00000000000000000000001}")
assertJSONDecodeFails("{\"optionalInt32\":\"01\"}")
assertJSONDecodeFails("{\"optionalInt32\":-01}")
assertJSONDecodeFails("{\"optionalInt32\":\"-00000000000000000000001\"}")
// Exponents are okay, as long as result is integer
assertJSONDecodeSucceeds("{\"optionalInt32\":2.147483647e9}") {(o:MessageTestType) in
o.optionalInt32 == Int32.max}
assertJSONDecodeSucceeds("{\"optionalInt32\":-2.147483648e9}") {(o:MessageTestType) in
o.optionalInt32 == Int32.min}
assertJSONDecodeSucceeds("{\"optionalInt32\":1e3}") {(o:MessageTestType) in
o.optionalInt32 == 1000}
assertJSONDecodeSucceeds("{\"optionalInt32\":100e-2}") {(o:MessageTestType) in
o.optionalInt32 == 1}
assertJSONDecodeFails("{\"optionalInt32\":1e-1}")
// Reject malformed input
assertJSONDecodeFails("{\"optionalInt32\":\\u0031}")
assertJSONDecodeFails("{\"optionalInt32\":\"\\u0030\\u0030\"}")
assertJSONDecodeFails("{\"optionalInt32\":\" 1\"}")
assertJSONDecodeFails("{\"optionalInt32\":\"1 \"}")
assertJSONDecodeFails("{\"optionalInt32\":\"01\"}")
assertJSONDecodeFails("{\"optionalInt32\":true}")
assertJSONDecodeFails("{\"optionalInt32\":0x102}")
assertJSONDecodeFails("{\"optionalInt32\":{}}")
assertJSONDecodeFails("{\"optionalInt32\":[]}")
// Try to get the library to access past the end of the string...
assertJSONDecodeFails("{\"optionalInt32\":0")
assertJSONDecodeFails("{\"optionalInt32\":-0")
assertJSONDecodeFails("{\"optionalInt32\":0.1")
assertJSONDecodeFails("{\"optionalInt32\":0.")
assertJSONDecodeFails("{\"optionalInt32\":1")
assertJSONDecodeFails("{\"optionalInt32\":\"")
assertJSONDecodeFails("{\"optionalInt32\":\"1")
assertJSONDecodeFails("{\"optionalInt32\":\"1\"")
assertJSONDecodeFails("{\"optionalInt32\":1.")
assertJSONDecodeFails("{\"optionalInt32\":1e")
assertJSONDecodeFails("{\"optionalInt32\":1e1")
assertJSONDecodeFails("{\"optionalInt32\":-1")
assertJSONDecodeFails("{\"optionalInt32\":123e")
assertJSONDecodeFails("{\"optionalInt32\":123.")
assertJSONDecodeFails("{\"optionalInt32\":123")
}
func testOptionalUInt32() {
assertJSONEncode("{\"optionalUint32\":1}") {(o: inout MessageTestType) in
o.optionalUint32 = 1
}
assertJSONEncode("{\"optionalUint32\":4294967295}") {(o: inout MessageTestType) in
o.optionalUint32 = UInt32.max
}
assertJSONDecodeFails("{\"optionalUint32\":4294967296}")
// Explicit 'null' is permitted, decodes to default
assertJSONDecodeSucceeds("{\"optionalUint32\":null}") {$0.optionalUint32 == 0}
// Quoted or unquoted numbers, positive, negative, or zero
assertJSONDecodeSucceeds("{\"optionalUint32\":1}") {$0.optionalUint32 == 1}
assertJSONDecodeSucceeds("{\"optionalUint32\":\"1\"}") {$0.optionalUint32 == 1}
assertJSONDecodeSucceeds("{\"optionalUint32\":0}") {$0.optionalUint32 == 0}
assertJSONDecodeSucceeds("{\"optionalUint32\":\"0\"}") {$0.optionalUint32 == 0}
// Protobuf JSON does not accept leading zeros
assertJSONDecodeFails("{\"optionalUint32\":01}")
assertJSONDecodeFails("{\"optionalUint32\":\"01\"}")
// But it does accept exponential (as long as result is integral)
assertJSONDecodeSucceeds("{\"optionalUint32\":4.294967295e9}") {$0.optionalUint32 == UInt32.max}
assertJSONDecodeSucceeds("{\"optionalUint32\":1e3}") {$0.optionalUint32 == 1000}
assertJSONDecodeSucceeds("{\"optionalUint32\":1.2e3}") {$0.optionalUint32 == 1200}
assertJSONDecodeSucceeds("{\"optionalUint32\":1000e-2}") {$0.optionalUint32 == 10}
assertJSONDecodeSucceeds("{\"optionalUint32\":1.0}") {$0.optionalUint32 == 1}
assertJSONDecodeSucceeds("{\"optionalUint32\":1.000000e2}") {$0.optionalUint32 == 100}
assertJSONDecodeFails("{\"optionalUint32\":1e-3}")
assertJSONDecodeFails("{\"optionalUint32\":1")
assertJSONDecodeFails("{\"optionalUint32\":\"")
assertJSONDecodeFails("{\"optionalUint32\":\"1")
assertJSONDecodeFails("{\"optionalUint32\":\"1\"")
assertJSONDecodeFails("{\"optionalUint32\":1.11e1}")
// Reject malformed input
assertJSONDecodeFails("{\"optionalUint32\":true}")
assertJSONDecodeFails("{\"optionalUint32\":-1}")
assertJSONDecodeFails("{\"optionalUint32\":\"-1\"}")
assertJSONDecodeFails("{\"optionalUint32\":0x102}")
assertJSONDecodeFails("{\"optionalUint32\":{}}")
assertJSONDecodeFails("{\"optionalUint32\":[]}")
}
func testOptionalInt64() throws {
// Protoc JSON always quotes Int64 values
assertJSONEncode("{\"optionalInt64\":\"9007199254740992\"}") {(o: inout MessageTestType) in
o.optionalInt64 = 0x20000000000000
}
assertJSONEncode("{\"optionalInt64\":\"9007199254740991\"}") {(o: inout MessageTestType) in
o.optionalInt64 = 0x1fffffffffffff
}
assertJSONEncode("{\"optionalInt64\":\"-9007199254740992\"}") {(o: inout MessageTestType) in
o.optionalInt64 = -0x20000000000000
}
assertJSONEncode("{\"optionalInt64\":\"-9007199254740991\"}") {(o: inout MessageTestType) in
o.optionalInt64 = -0x1fffffffffffff
}
assertJSONEncode("{\"optionalInt64\":\"9223372036854775807\"}") {(o: inout MessageTestType) in
o.optionalInt64 = Int64.max
}
assertJSONEncode("{\"optionalInt64\":\"-9223372036854775808\"}") {(o: inout MessageTestType) in
o.optionalInt64 = Int64.min
}
assertJSONEncode("{\"optionalInt64\":\"1\"}") {(o: inout MessageTestType) in
o.optionalInt64 = 1
}
assertJSONEncode("{\"optionalInt64\":\"-1\"}") {(o: inout MessageTestType) in
o.optionalInt64 = -1
}
// 0 is default, so proto3 omits it
var a = MessageTestType()
a.optionalInt64 = 0
XCTAssertEqual(try a.jsonString(), "{}")
// Decode should work even with unquoted large numbers
assertJSONDecodeSucceeds("{\"optionalInt64\":9223372036854775807}") {$0.optionalInt64 == Int64.max}
assertJSONDecodeFails("{\"optionalInt64\":9223372036854775808}")
assertJSONDecodeSucceeds("{\"optionalInt64\":-9223372036854775808}") {$0.optionalInt64 == Int64.min}
assertJSONDecodeFails("{\"optionalInt64\":-9223372036854775809}")
// Protobuf JSON does not accept leading zeros
assertJSONDecodeFails("{\"optionalInt64\": \"01\" }")
assertJSONDecodeSucceeds("{\"optionalInt64\": \"1\" }") {$0.optionalInt64 == 1}
assertJSONDecodeFails("{\"optionalInt64\": \"-01\" }")
assertJSONDecodeSucceeds("{\"optionalInt64\": \"-1\" }") {$0.optionalInt64 == -1}
assertJSONDecodeSucceeds("{\"optionalInt64\": \"0\" }") {$0.optionalInt64 == 0}
// Protobuf JSON does accept exponential format for integer fields
assertJSONDecodeSucceeds("{\"optionalInt64\":1e3}") {$0.optionalInt64 == 1000}
assertJSONDecodeSucceeds("{\"optionalInt64\":\"9223372036854775807\"}") {$0.optionalInt64 == Int64.max}
assertJSONDecodeSucceeds("{\"optionalInt64\":-9.223372036854775808e18}") {$0.optionalInt64 == Int64.min}
assertJSONDecodeFails("{\"optionalInt64\":9.223372036854775808e18}") // Out of range
// Explicit 'null' is permitted, decodes to default (in proto3)
assertJSONDecodeSucceeds("{\"optionalInt64\":null}") {$0.optionalInt64 == 0}
assertJSONDecodeSucceeds("{\"optionalInt64\":2147483648}") {$0.optionalInt64 == 2147483648}
assertJSONDecodeSucceeds("{\"optionalInt64\":2147483648}") {$0.optionalInt64 == 2147483648}
assertJSONDecodeFails("{\"optionalInt64\":1")
assertJSONDecodeFails("{\"optionalInt64\":\"")
assertJSONDecodeFails("{\"optionalInt64\":\"1")
assertJSONDecodeFails("{\"optionalInt64\":\"1\"")
}
func testOptionalUInt64() {
assertJSONEncode("{\"optionalUint64\":\"1\"}") {(o: inout MessageTestType) in
o.optionalUint64 = 1
}
assertJSONEncode("{\"optionalUint64\":\"4294967295\"}") {(o: inout MessageTestType) in
o.optionalUint64 = UInt64(UInt32.max)
}
assertJSONEncode("{\"optionalUint64\":\"18446744073709551615\"}") {(o: inout MessageTestType) in
o.optionalUint64 = UInt64.max
}
// Parse unquoted 64-bit integers
assertJSONDecodeSucceeds("{\"optionalUint64\":18446744073709551615}") {$0.optionalUint64 == UInt64.max}
// Accept quoted 64-bit integers with backslash escapes in them
assertJSONDecodeSucceeds("{\"optionalUint64\":\"184467\\u00344073709551615\"}") {$0.optionalUint64 == UInt64.max}
// Reject unquoted 64-bit integers with backslash escapes
assertJSONDecodeFails("{\"optionalUint64\":184467\\u00344073709551615}")
// Reject out-of-range integers, whether or not quoted
assertJSONDecodeFails("{\"optionalUint64\":\"18446744073709551616\"}")
assertJSONDecodeFails("{\"optionalUint64\":18446744073709551616}")
assertJSONDecodeFails("{\"optionalUint64\":\"184467440737095516109\"}")
assertJSONDecodeFails("{\"optionalUint64\":184467440737095516109}")
// Explicit 'null' is permitted, decodes to default
assertJSONDecodeSucceeds("{\"optionalUint64\":null}") {$0.optionalUint64 == 0}
// Quoted or unquoted numbers, positive or zero
assertJSONDecodeSucceeds("{\"optionalUint64\":1}") {$0.optionalUint64 == 1}
assertJSONDecodeSucceeds("{\"optionalUint64\":\"1\"}") {$0.optionalUint64 == 1}
assertJSONDecodeSucceeds("{\"optionalUint64\":0}") {$0.optionalUint64 == 0}
assertJSONDecodeSucceeds("{\"optionalUint64\":\"0\"}") {$0.optionalUint64 == 0}
// Protobuf JSON does not accept leading zeros
assertJSONDecodeFails("{\"optionalUint64\":01}")
assertJSONDecodeFails("{\"optionalUint64\":\"01\"}")
// But it does accept exponential (as long as result is integral)
assertJSONDecodeSucceeds("{\"optionalUint64\":4.294967295e9}") {$0.optionalUint64 == UInt64(UInt32.max)}
assertJSONDecodeSucceeds("{\"optionalUint64\":1e3}") {$0.optionalUint64 == 1000}
assertJSONDecodeSucceeds("{\"optionalUint64\":1.2e3}") {$0.optionalUint64 == 1200}
assertJSONDecodeSucceeds("{\"optionalUint64\":1000e-2}") {$0.optionalUint64 == 10}
assertJSONDecodeSucceeds("{\"optionalUint64\":1.0}") {$0.optionalUint64 == 1}
assertJSONDecodeSucceeds("{\"optionalUint64\":1.000000e2}") {$0.optionalUint64 == 100}
assertJSONDecodeFails("{\"optionalUint64\":1e-3}")
assertJSONDecodeFails("{\"optionalUint64\":1.11e1}")
// Reject truncated JSON (ending at the beginning, end, or middle of the number
assertJSONDecodeFails("{\"optionalUint64\":")
assertJSONDecodeFails("{\"optionalUint64\":1")
assertJSONDecodeFails("{\"optionalUint64\":\"")
assertJSONDecodeFails("{\"optionalUint64\":\"1")
assertJSONDecodeFails("{\"optionalUint64\":\"1\"")
// Reject malformed input
assertJSONDecodeFails("{\"optionalUint64\":true}")
assertJSONDecodeFails("{\"optionalUint64\":-1}")
assertJSONDecodeFails("{\"optionalUint64\":\"-1\"}")
assertJSONDecodeFails("{\"optionalUint64\":0x102}")
assertJSONDecodeFails("{\"optionalUint64\":{}}")
assertJSONDecodeFails("{\"optionalUint64\":[]}")
}
private func assertRoundTripJSON(file: XCTestFileArgType = #file, line: UInt = #line, configure: (inout MessageTestType) -> Void) {
var original = MessageTestType()
configure(&original)
do {
let json = try original.jsonString()
do {
let decoded = try MessageTestType(jsonString: json)
XCTAssertEqual(original, decoded, file: file, line: line)
} catch let e {
XCTFail("Failed to decode \(e): \(json)", file: file, line: line)
}
} catch let e {
XCTFail("Failed to encode \(e)", file: file, line: line)
}
}
func testOptionalDouble() throws {
assertJSONEncode("{\"optionalDouble\":1}") {(o: inout MessageTestType) in
o.optionalDouble = 1.0
}
assertJSONEncode("{\"optionalDouble\":\"Infinity\"}") {(o: inout MessageTestType) in
o.optionalDouble = Double.infinity
}
assertJSONEncode("{\"optionalDouble\":\"-Infinity\"}") {(o: inout MessageTestType) in
o.optionalDouble = -Double.infinity
}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"Inf\"}") {$0.optionalDouble == Double.infinity}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"-Inf\"}") {$0.optionalDouble == -Double.infinity}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1\"}") {$0.optionalDouble == 1}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.0\"}") {$0.optionalDouble == 1.0}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5\"}") {$0.optionalDouble == 1.5}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5e1\"}") {$0.optionalDouble == 15}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5E1\"}") {$0.optionalDouble == 15}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1\\u002e5e1\"}") {$0.optionalDouble == 15}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.\\u0035e1\"}") {$0.optionalDouble == 15}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5\\u00651\"}") {$0.optionalDouble == 15}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5e\\u002b1\"}") {$0.optionalDouble == 15}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5e+\\u0031\"}") {$0.optionalDouble == 15}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.5e+1\"}") {$0.optionalDouble == 15}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"15e-1\"}") {$0.optionalDouble == 1.5}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"1.0e0\"}") {$0.optionalDouble == 1.0}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"-0\"}") {$0.optionalDouble == 0.0}
assertJSONDecodeSucceeds("{\"optionalDouble\":\"0\"}") {$0.optionalDouble == 0.0}
assertJSONDecodeSucceeds("{\"optionalDouble\":-0}") {$0.optionalDouble == 0.0}
assertJSONDecodeSucceeds("{\"optionalDouble\":0}") {$0.optionalDouble == 0.0}
// Malformed numbers should fail
assertJSONDecodeFails("{\"optionalDouble\":Infinity}")
assertJSONDecodeFails("{\"optionalDouble\":-Infinity}") // Must be quoted
assertJSONDecodeFails("{\"optionalDouble\":\"inf\"}")
assertJSONDecodeFails("{\"optionalDouble\":\"-inf\"}")
assertJSONDecodeFails("{\"optionalDouble\":NaN}")
assertJSONDecodeFails("{\"optionalDouble\":\"nan\"}")
assertJSONDecodeFails("{\"optionalDouble\":\"1.0.0\"}")
assertJSONDecodeFails("{\"optionalDouble\":00.1}")
assertJSONDecodeFails("{\"optionalDouble\":\"00.1\"}")
assertJSONDecodeFails("{\"optionalDouble\":.1}")
assertJSONDecodeFails("{\"optionalDouble\":\".1\"}")
assertJSONDecodeFails("{\"optionalDouble\":1.}")
assertJSONDecodeFails("{\"optionalDouble\":\"1.\"}")
assertJSONDecodeFails("{\"optionalDouble\":1e}")
assertJSONDecodeFails("{\"optionalDouble\":\"1e\"}")
assertJSONDecodeFails("{\"optionalDouble\":1e+}")
assertJSONDecodeFails("{\"optionalDouble\":\"1e+\"}")
assertJSONDecodeFails("{\"optionalDouble\":1e3.2}")
assertJSONDecodeFails("{\"optionalDouble\":\"1e3.2\"}")
assertJSONDecodeFails("{\"optionalDouble\":1.0.0}")
// A wide range of numbers should exactly round-trip
assertRoundTripJSON {$0.optionalDouble = 0.1}
assertRoundTripJSON {$0.optionalDouble = 0.01}
assertRoundTripJSON {$0.optionalDouble = 0.001}
assertRoundTripJSON {$0.optionalDouble = 0.0001}
assertRoundTripJSON {$0.optionalDouble = 0.00001}
assertRoundTripJSON {$0.optionalDouble = 0.000001}
assertRoundTripJSON {$0.optionalDouble = 1e-10}
assertRoundTripJSON {$0.optionalDouble = 1e-20}
assertRoundTripJSON {$0.optionalDouble = 1e-30}
assertRoundTripJSON {$0.optionalDouble = 1e-40}
assertRoundTripJSON {$0.optionalDouble = 1e-50}
assertRoundTripJSON {$0.optionalDouble = 1e-60}
assertRoundTripJSON {$0.optionalDouble = 1e-100}
assertRoundTripJSON {$0.optionalDouble = 1e-200}
assertRoundTripJSON {$0.optionalDouble = Double.pi}
assertRoundTripJSON {$0.optionalDouble = 123456.789123456789123}
assertRoundTripJSON {$0.optionalDouble = 1.7976931348623157e+308}
assertRoundTripJSON {$0.optionalDouble = 2.22507385850720138309e-308}
}
func testOptionalFloat() {
assertJSONEncode("{\"optionalFloat\":1}") {(o: inout MessageTestType) in
o.optionalFloat = 1.0
}
assertJSONEncode("{\"optionalFloat\":\"Infinity\"}") {(o: inout MessageTestType) in
o.optionalFloat = Float.infinity
}
assertJSONEncode("{\"optionalFloat\":\"-Infinity\"}") {(o: inout MessageTestType) in
o.optionalFloat = -Float.infinity
}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"Inf\"}") {$0.optionalFloat == Float.infinity}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"-Inf\"}") {$0.optionalFloat == -Float.infinity}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1\"}") {$0.optionalFloat == 1}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.0\"}") {$0.optionalFloat == 1.0}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5\"}") {$0.optionalFloat == 1.5}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5e1\"}") {$0.optionalFloat == 15}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1\\u002e5e1\"}") {$0.optionalFloat == 15}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.\\u0035e1\"}") {$0.optionalFloat == 15}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5\\u00651\"}") {$0.optionalFloat == 15}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5e\\u002b1\"}") {$0.optionalFloat == 15}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5e+\\u0031\"}") {$0.optionalFloat == 15}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.5e+1\"}") {$0.optionalFloat == 15}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"15e-1\"}") {$0.optionalFloat == 1.5}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"1.0e0\"}") {$0.optionalFloat == 1.0}
assertJSONDecodeSucceeds("{\"optionalFloat\":1.0e0}") {$0.optionalFloat == 1.0}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"0\"}") {$0.optionalFloat == 0.0}
assertJSONDecodeSucceeds("{\"optionalFloat\":0}") {$0.optionalFloat == 0.0}
assertJSONDecodeSucceeds("{\"optionalFloat\":\"-0\"}") {$0.optionalFloat == -0.0 && $0.optionalFloat.sign == .minus}
assertJSONDecodeSucceeds("{\"optionalFloat\":-0}") {$0.optionalFloat == 0 && $0.optionalFloat.sign == .minus}
// Malformed numbers should fail
assertJSONDecodeFails("{\"optionalFloat\":Infinity}")
assertJSONDecodeFails("{\"optionalFloat\":-Infinity}") // Must be quoted
assertJSONDecodeFails("{\"optionalFloat\":NaN}")
assertJSONDecodeFails("{\"optionalFloat\":\"nan\"}")
assertJSONDecodeFails("{\"optionalFloat\":\"1.0.0\"}")
assertJSONDecodeFails("{\"optionalFloat\":1.0.0}")
assertJSONDecodeFails("{\"optionalFloat\":00.1}")
assertJSONDecodeFails("{\"optionalFloat\":\"00.1\"}")
assertJSONDecodeFails("{\"optionalFloat\":.1}")
assertJSONDecodeFails("{\"optionalFloat\":\".1\"}")
assertJSONDecodeFails("{\"optionalFloat\":\"1")
assertJSONDecodeFails("{\"optionalFloat\":\"")
assertJSONDecodeFails("{\"optionalFloat\":1")
assertJSONDecodeFails("{\"optionalFloat\":1.")
assertJSONDecodeFails("{\"optionalFloat\":1.}")
assertJSONDecodeFails("{\"optionalFloat\":\"1.\"}")
assertJSONDecodeFails("{\"optionalFloat\":1e}")
assertJSONDecodeFails("{\"optionalFloat\":\"1e\"}")
assertJSONDecodeFails("{\"optionalFloat\":1e+}")
assertJSONDecodeFails("{\"optionalFloat\":\"1e+\"}")
assertJSONDecodeFails("{\"optionalFloat\":1e3.2}")
assertJSONDecodeFails("{\"optionalFloat\":\"1e3.2\"}")
// Out-of-range numbers should fail
assertJSONDecodeFails("{\"optionalFloat\":1e39}")
// A wide range of numbers should exactly round-trip
assertRoundTripJSON {$0.optionalFloat = 0.1}
assertRoundTripJSON {$0.optionalFloat = 0.01}
assertRoundTripJSON {$0.optionalFloat = 0.001}
assertRoundTripJSON {$0.optionalFloat = 0.0001}
assertRoundTripJSON {$0.optionalFloat = 0.00001}
assertRoundTripJSON {$0.optionalFloat = 0.000001}
assertRoundTripJSON {$0.optionalFloat = 1.00000075e-36}
assertRoundTripJSON {$0.optionalFloat = 1e-10}
assertRoundTripJSON {$0.optionalFloat = 1e-20}
assertRoundTripJSON {$0.optionalFloat = 1e-30}
assertRoundTripJSON {$0.optionalFloat = 1e-40}
assertRoundTripJSON {$0.optionalFloat = 1e-50}
assertRoundTripJSON {$0.optionalFloat = 1e-60}
assertRoundTripJSON {$0.optionalFloat = 1e-100}
assertRoundTripJSON {$0.optionalFloat = 1e-200}
assertRoundTripJSON {$0.optionalFloat = Float.pi}
assertRoundTripJSON {$0.optionalFloat = 123456.789123456789123}
assertRoundTripJSON {$0.optionalFloat = 1999.9999999999}
assertRoundTripJSON {$0.optionalFloat = 1999.9}
assertRoundTripJSON {$0.optionalFloat = 1999.99}
assertRoundTripJSON {$0.optionalFloat = 1999.99}
assertRoundTripJSON {$0.optionalFloat = 3.402823567e+38}
assertRoundTripJSON {$0.optionalFloat = 1.1754944e-38}
}
func testOptionalDouble_NaN() throws {
// The helper functions don't work with NaN because NaN != NaN
var o = Proto3Unittest_TestAllTypes()
o.optionalDouble = Double.nan
let encoded = try o.jsonString()
XCTAssertEqual(encoded, "{\"optionalDouble\":\"NaN\"}")
let o2 = try Proto3Unittest_TestAllTypes(jsonString: encoded)
XCTAssert(o2.optionalDouble.isNaN == .some(true))
}
func testOptionalFloat_NaN() throws {
// The helper functions don't work with NaN because NaN != NaN
var o = Proto3Unittest_TestAllTypes()
o.optionalFloat = Float.nan
let encoded = try o.jsonString()
XCTAssertEqual(encoded, "{\"optionalFloat\":\"NaN\"}")
do {
let o2 = try Proto3Unittest_TestAllTypes(jsonString: encoded)
XCTAssert(o2.optionalFloat.isNaN == .some(true))
} catch let e {
XCTFail("Couldn't decode: \(e) -- \(encoded)")
}
}
func testOptionalDouble_roundtrip() throws {
for _ in 0..<10000 {
let d = drand48()
assertRoundTripJSON {$0.optionalDouble = d}
}
}
func testOptionalFloat_roundtrip() throws {
for _ in 0..<10000 {
let f = Float(drand48())
assertRoundTripJSON {$0.optionalFloat = f}
}
}
func testOptionalBool() throws {
assertJSONEncode("{\"optionalBool\":true}") {(o: inout MessageTestType) in
o.optionalBool = true
}
// False is default, so should not serialize in proto3
var o = MessageTestType()
o.optionalBool = false
XCTAssertEqual(try o.jsonString(), "{}")
}
func testOptionalString() {
assertJSONEncode("{\"optionalString\":\"hello\"}") {(o: inout MessageTestType) in
o.optionalString = "hello"
}
// Start of the C1 range
assertJSONEncode("{\"optionalString\":\"~\\u007F\\u0080\\u0081\"}") {(o: inout MessageTestType) in
o.optionalString = "\u{7e}\u{7f}\u{80}\u{81}"
}
// End of the C1 range
assertJSONEncode("{\"optionalString\":\"\\u009E\\u009F ¡¢£\"}") {(o: inout MessageTestType) in
o.optionalString = "\u{9e}\u{9f}\u{a0}\u{a1}\u{a2}\u{a3}"
}
// Empty string is default, so proto3 omits it
var a = MessageTestType()
a.optionalString = ""
XCTAssertEqual(try a.jsonString(), "{}")
// Example from RFC 7159: G clef coded as escaped surrogate pair
assertJSONDecodeSucceeds("{\"optionalString\":\"\\uD834\\uDD1E\"}") {$0.optionalString == "𝄞"}
// Ditto, with lowercase hex
assertJSONDecodeSucceeds("{\"optionalString\":\"\\ud834\\udd1e\"}") {$0.optionalString == "𝄞"}
// Same character represented directly
assertJSONDecodeSucceeds("{\"optionalString\":\"𝄞\"}") {$0.optionalString == "𝄞"}
// Various broken surrogate forms
assertJSONDecodeFails("{\"optionalString\":\"\\uDD1E\\uD834\"}")
assertJSONDecodeFails("{\"optionalString\":\"\\uDD1E\"}")
assertJSONDecodeFails("{\"optionalString\":\"\\uD834\"}")
assertJSONDecodeFails("{\"optionalString\":\"\\uDD1E\\u1234\"}")
}
func testOptionalString_controlCharacters() {
// This is known to fail on Swift Linux 4.1 and earlier,
// so skip it there.
// See https://bugs.swift.org/browse/SR-4218 for details.
#if !os(Linux) || swift(>=4.2)
// Verify that all C0 controls are correctly escaped
assertJSONEncode("{\"optionalString\":\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\"}") {(o: inout MessageTestType) in
o.optionalString = "\u{00}\u{01}\u{02}\u{03}\u{04}\u{05}\u{06}\u{07}"
}
assertJSONEncode("{\"optionalString\":\"\\b\\t\\n\\u000B\\f\\r\\u000E\\u000F\"}") {(o: inout MessageTestType) in
o.optionalString = "\u{08}\u{09}\u{0a}\u{0b}\u{0c}\u{0d}\u{0e}\u{0f}"
}
assertJSONEncode("{\"optionalString\":\"\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\"}") {(o: inout MessageTestType) in
o.optionalString = "\u{10}\u{11}\u{12}\u{13}\u{14}\u{15}\u{16}\u{17}"
}
assertJSONEncode("{\"optionalString\":\"\\u0018\\u0019\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F\"}") {(o: inout MessageTestType) in
o.optionalString = "\u{18}\u{19}\u{1a}\u{1b}\u{1c}\u{1d}\u{1e}\u{1f}"
}
#endif
}
func testOptionalBytes() throws {
// Empty bytes is default, so proto3 omits it
var a = MessageTestType()
a.optionalBytes = Data()
XCTAssertEqual(try a.jsonString(), "{}")
assertJSONEncode("{\"optionalBytes\":\"AA==\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [0])
}
assertJSONEncode("{\"optionalBytes\":\"AAA=\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [0, 0])
}
assertJSONEncode("{\"optionalBytes\":\"AAAA\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [0, 0, 0])
}
assertJSONEncode("{\"optionalBytes\":\"/w==\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [255])
}
assertJSONEncode("{\"optionalBytes\":\"//8=\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [255, 255])
}
assertJSONEncode("{\"optionalBytes\":\"////\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [255, 255, 255])
}
assertJSONEncode("{\"optionalBytes\":\"QQ==\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [65])
}
assertJSONDecodeFails("{\"optionalBytes\":\"QQ=\"}")
assertJSONDecodeSucceeds("{\"optionalBytes\":\"QQ\"}") {
$0.optionalBytes == Data(bytes: [65])
}
assertJSONEncode("{\"optionalBytes\":\"QUI=\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [65, 66])
}
assertJSONDecodeSucceeds("{\"optionalBytes\":\"QUI\"}") {
$0.optionalBytes == Data(bytes: [65, 66])
}
assertJSONEncode("{\"optionalBytes\":\"QUJD\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [65, 66, 67])
}
assertJSONEncode("{\"optionalBytes\":\"QUJDRA==\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [65, 66, 67, 68])
}
assertJSONDecodeFails("{\"optionalBytes\":\"QUJDRA===\"}")
assertJSONDecodeFails("{\"optionalBytes\":\"QUJDRA=\"}")
assertJSONDecodeSucceeds("{\"optionalBytes\":\"QUJDRA\"}") {
$0.optionalBytes == Data(bytes: [65, 66, 67, 68])
}
assertJSONEncode("{\"optionalBytes\":\"QUJDREU=\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [65, 66, 67, 68, 69])
}
assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREU==\"}")
assertJSONDecodeSucceeds("{\"optionalBytes\":\"QUJDREU\"}") {
$0.optionalBytes == Data(bytes: [65, 66, 67, 68, 69])
}
assertJSONEncode("{\"optionalBytes\":\"QUJDREVG\"}") {(o: inout MessageTestType) in
o.optionalBytes = Data(bytes: [65, 66, 67, 68, 69, 70])
}
assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREVG=\"}")
assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREVG==\"}")
assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREVG===\"}")
assertJSONDecodeFails("{\"optionalBytes\":\"QUJDREVG====\"}")
// Accept both RFC4648 Section 4 and Section 5 base64 variants, but reject mixed coding:
assertJSONDecodeSucceeds("{\"optionalBytes\":\"-_-_\"}") {
$0.optionalBytes == Data(bytes: [251, 255, 191])
}
assertJSONDecodeSucceeds("{\"optionalBytes\":\"+/+/\"}") {
$0.optionalBytes == Data(bytes: [251, 255, 191])
}
assertJSONDecodeFails("{\"optionalBytes\":\"-_+/\"}")
}
func testOptionalBytes2() {
assertJSONDecodeSucceeds("{\"optionalBytes\":\"QUJD\"}") {
$0.optionalBytes == Data(bytes: [65, 66, 67])
}
}
func testOptionalBytes_roundtrip() throws {
for i in UInt8(0)...UInt8(255) {
let d = Data(bytes: [i])
let message = Proto3Unittest_TestAllTypes.with { $0.optionalBytes = d }
let text = try message.jsonString()
let decoded = try Proto3Unittest_TestAllTypes(jsonString: text)
XCTAssertEqual(decoded, message)
XCTAssertEqual(message.optionalBytes[0], i)
}
}
func testOptionalNestedMessage() {
assertJSONEncode("{\"optionalNestedMessage\":{\"bb\":1}}") {(o: inout MessageTestType) in
var sub = Proto3Unittest_TestAllTypes.NestedMessage()
sub.bb = 1
o.optionalNestedMessage = sub
}
}
func testOptionalNestedEnum() {
assertJSONEncode("{\"optionalNestedEnum\":\"FOO\"}") {(o: inout MessageTestType) in
o.optionalNestedEnum = Proto3Unittest_TestAllTypes.NestedEnum.foo
}
assertJSONDecodeSucceeds("{\"optionalNestedEnum\":1}") {$0.optionalNestedEnum == .foo}
// Out-of-range values should be serialized to an int
assertJSONEncode("{\"optionalNestedEnum\":123}") {(o: inout MessageTestType) in
o.optionalNestedEnum = .UNRECOGNIZED(123)
}
// TODO: Check whether Google's spec agrees that unknown Enum tags
// should fail to parse
assertJSONDecodeFails("{\"optionalNestedEnum\":\"UNKNOWN\"}")
}
func testRepeatedInt32() {
assertJSONEncode("{\"repeatedInt32\":[1]}") {(o: inout MessageTestType) in
o.repeatedInt32 = [1]
}
assertJSONEncode("{\"repeatedInt32\":[1,2]}") {(o: inout MessageTestType) in
o.repeatedInt32 = [1, 2]
}
assertEncode([250, 1, 2, 1, 2]) {(o: inout MessageTestType) in
// Proto3 seems to default to packed for repeated int fields
o.repeatedInt32 = [1, 2]
}
assertJSONDecodeSucceeds("{\"repeatedInt32\":null}") {$0.repeatedInt32 == []}
assertJSONDecodeSucceeds("{\"repeatedInt32\":[]}") {$0.repeatedInt32 == []}
assertJSONDecodeSucceeds("{\"repeatedInt32\":[1]}") {$0.repeatedInt32 == [1]}
assertJSONDecodeSucceeds("{\"repeatedInt32\":[1,2]}") {$0.repeatedInt32 == [1, 2]}
}
func testRepeatedString() {
assertJSONEncode("{\"repeatedString\":[\"\"]}") {(o: inout MessageTestType) in
o.repeatedString = [""]
}
assertJSONEncode("{\"repeatedString\":[\"abc\",\"\"]}") {(o: inout MessageTestType) in
o.repeatedString = ["abc", ""]
}
assertJSONDecodeSucceeds("{\"repeatedString\":null}") {$0.repeatedString == []}
assertJSONDecodeSucceeds("{\"repeatedString\":[]}") {$0.repeatedString == []}
assertJSONDecodeSucceeds(" { \"repeatedString\" : [ \"1\" , \"2\" ] } ") {
$0.repeatedString == ["1", "2"]
}
}
func testRepeatedNestedMessage() {
assertJSONEncode("{\"repeatedNestedMessage\":[{\"bb\":1}]}") {(o: inout MessageTestType) in
var sub = Proto3Unittest_TestAllTypes.NestedMessage()
sub.bb = 1
o.repeatedNestedMessage = [sub]
}
assertJSONEncode("{\"repeatedNestedMessage\":[{\"bb\":1},{\"bb\":2}]}") {(o: inout MessageTestType) in
var sub1 = Proto3Unittest_TestAllTypes.NestedMessage()
sub1.bb = 1
var sub2 = Proto3Unittest_TestAllTypes.NestedMessage()
sub2.bb = 2
o.repeatedNestedMessage = [sub1, sub2]
}
assertJSONDecodeSucceeds("{\"repeatedNestedMessage\": []}") {
$0.repeatedNestedMessage == []
}
}
// TODO: Test other repeated field types
func testOneof() {
assertJSONEncode("{\"oneofUint32\":1}") {(o: inout MessageTestType) in
o.oneofUint32 = 1
}
assertJSONEncode("{\"oneofString\":\"abc\"}") {(o: inout MessageTestType) in
o.oneofString = "abc"
}
assertJSONEncode("{\"oneofNestedMessage\":{\"bb\":1}}") {(o: inout MessageTestType) in
var sub = Proto3Unittest_TestAllTypes.NestedMessage()
sub.bb = 1
o.oneofNestedMessage = sub
}
assertJSONDecodeFails("{\"oneofString\": 1}")
assertJSONDecodeFails("{\"oneofUint32\":1,\"oneofString\":\"abc\"}")
assertJSONDecodeFails("{\"oneofString\":\"abc\",\"oneofUint32\":1}")
}
}
class Test_JSONPacked: XCTestCase, PBTestHelpers {
typealias MessageTestType = Proto3Unittest_TestPackedTypes
func testPackedFloat() {
assertJSONEncode("{\"packedFloat\":[1]}") {(o: inout MessageTestType) in
o.packedFloat = [1]
}
assertJSONEncode("{\"packedFloat\":[1,0.25,0.125]}") {(o: inout MessageTestType) in
o.packedFloat = [1, 0.25, 0.125]
}
assertJSONDecodeSucceeds("{\"packedFloat\":[1,0.25,125e-3]}") {
$0.packedFloat == [1, 0.25, 0.125]
}
assertJSONDecodeSucceeds("{\"packedFloat\":null}") {$0.packedFloat == []}
assertJSONDecodeSucceeds("{\"packedFloat\":[]}") {$0.packedFloat == []}
assertJSONDecodeSucceeds("{\"packedFloat\":[\"1\"]}") {$0.packedFloat == [1]}
assertJSONDecodeSucceeds("{\"packedFloat\":[\"1\",2]}") {$0.packedFloat == [1, 2]}
}
func testPackedDouble() {
assertJSONEncode("{\"packedDouble\":[1]}") {(o: inout MessageTestType) in
o.packedDouble = [1]
}
assertJSONEncode("{\"packedDouble\":[1,0.25,0.125]}") {(o: inout MessageTestType) in
o.packedDouble = [1, 0.25, 0.125]
}
assertJSONDecodeSucceeds("{\"packedDouble\":[1,0.25,125e-3]}") {
$0.packedDouble == [1, 0.25, 0.125]
}
assertJSONDecodeSucceeds("{\"packedDouble\":null}") {$0.packedDouble == []}
assertJSONDecodeSucceeds("{\"packedDouble\":[]}") {$0.packedDouble == []}
assertJSONDecodeSucceeds("{\"packedDouble\":[\"1\"]}") {$0.packedDouble == [1]}
assertJSONDecodeSucceeds("{\"packedDouble\":[\"1\",2]}") {$0.packedDouble == [1, 2]}
}
func testPackedInt32() {
assertJSONEncode("{\"packedInt32\":[1]}") {(o: inout MessageTestType) in
o.packedInt32 = [1]
}
assertJSONEncode("{\"packedInt32\":[1,2]}") {(o: inout MessageTestType) in
o.packedInt32 = [1, 2]
}
assertJSONEncode("{\"packedInt32\":[-2147483648,2147483647]}") {(o: inout MessageTestType) in
o.packedInt32 = [Int32.min, Int32.max]
}
assertJSONDecodeSucceeds("{\"packedInt32\":null}") {$0.packedInt32 == []}
assertJSONDecodeSucceeds("{\"packedInt32\":[]}") {$0.packedInt32 == []}
assertJSONDecodeSucceeds("{\"packedInt32\":[\"1\"]}") {$0.packedInt32 == [1]}
assertJSONDecodeSucceeds("{\"packedInt32\":[\"1\",\"2\"]}") {$0.packedInt32 == [1, 2]}
assertJSONDecodeSucceeds(" { \"packedInt32\" : [ \"1\" , \"2\" ] } ") {$0.packedInt32 == [1, 2]}
}
func testPackedInt64() {
assertJSONEncode("{\"packedInt64\":[\"1\"]}") {(o: inout MessageTestType) in
o.packedInt64 = [1]
}
assertJSONEncode("{\"packedInt64\":[\"9223372036854775807\",\"-9223372036854775808\"]}") {
(o: inout MessageTestType) in
o.packedInt64 = [Int64.max, Int64.min]
}
assertJSONDecodeSucceeds("{\"packedInt64\":null}") {$0.packedInt64 == []}
assertJSONDecodeSucceeds("{\"packedInt64\":[]}") {$0.packedInt64 == []}
assertJSONDecodeSucceeds("{\"packedInt64\":[1]}") {$0.packedInt64 == [1]}
assertJSONDecodeSucceeds("{\"packedInt64\":[1,2]}") {$0.packedInt64 == [1, 2]}
assertJSONDecodeFails("{\"packedInt64\":[null]}")
}
func testPackedUInt32() {
assertJSONEncode("{\"packedUint32\":[1]}") {(o: inout MessageTestType) in
o.packedUint32 = [1]
}
assertJSONEncode("{\"packedUint32\":[0,4294967295]}") {(o: inout MessageTestType) in
o.packedUint32 = [UInt32.min, UInt32.max]
}
assertJSONDecodeSucceeds("{\"packedUint32\":null}") {$0.packedUint32 == []}
assertJSONDecodeSucceeds("{\"packedUint32\":[]}") {$0.packedUint32 == []}
assertJSONDecodeSucceeds("{\"packedUint32\":[1]}") {$0.packedUint32 == [1]}
assertJSONDecodeSucceeds("{\"packedUint32\":[1,2]}") {$0.packedUint32 == [1, 2]}
assertJSONDecodeFails("{\"packedUint32\":[null]}")
assertJSONDecodeFails("{\"packedUint32\":[-1]}")
assertJSONDecodeFails("{\"packedUint32\":[1.2]}")
}
func testPackedUInt64() {
assertJSONEncode("{\"packedUint64\":[\"1\"]}") {(o: inout MessageTestType) in
o.packedUint64 = [1]
}
assertJSONEncode("{\"packedUint64\":[\"0\",\"18446744073709551615\"]}") {
(o: inout MessageTestType) in
o.packedUint64 = [UInt64.min, UInt64.max]
}
assertJSONDecodeSucceeds("{\"packedUint64\":null}") {$0.packedUint64 == []}
assertJSONDecodeSucceeds("{\"packedUint64\":[]}") {$0.packedUint64 == []}
assertJSONDecodeSucceeds("{\"packedUint64\":[1]}") {$0.packedUint64 == [1]}
assertJSONDecodeSucceeds("{\"packedUint64\":[1,2]}") {$0.packedUint64 == [1, 2]}
assertJSONDecodeFails("{\"packedUint64\":[null]}")
assertJSONDecodeFails("{\"packedUint64\":[-1]}")
assertJSONDecodeFails("{\"packedUint64\":[1.2]}")
}
func testPackedSInt32() {
assertJSONEncode("{\"packedSint32\":[1]}") {(o: inout MessageTestType) in
o.packedSint32 = [1]
}
assertJSONEncode("{\"packedSint32\":[-2147483648,2147483647]}") {(o: inout MessageTestType) in
o.packedSint32 = [Int32.min, Int32.max]
}
assertJSONDecodeSucceeds("{\"packedSint32\":null}") {$0.packedSint32 == []}
assertJSONDecodeSucceeds("{\"packedSint32\":[]}") {$0.packedSint32 == []}
assertJSONDecodeSucceeds("{\"packedSint32\":[1]}") {$0.packedSint32 == [1]}
assertJSONDecodeSucceeds("{\"packedSint32\":[1,2]}") {$0.packedSint32 == [1, 2]}
assertJSONDecodeFails("{\"packedSint32\":[null]}")
assertJSONDecodeFails("{\"packedSint32\":[1.2]}")
}
func testPackedSInt64() {
assertJSONEncode("{\"packedSint64\":[\"1\"]}") {(o: inout MessageTestType) in
o.packedSint64 = [1]
}
assertJSONEncode("{\"packedSint64\":[\"-9223372036854775808\",\"9223372036854775807\"]}") {
(o: inout MessageTestType) in
o.packedSint64 = [Int64.min, Int64.max]
}
assertJSONDecodeSucceeds("{\"packedSint64\":null}") {$0.packedSint64 == []}
assertJSONDecodeSucceeds("{\"packedSint64\":[]}") {$0.packedSint64 == []}
assertJSONDecodeSucceeds("{\"packedSint64\":[1]}") {$0.packedSint64 == [1]}
assertJSONDecodeSucceeds("{\"packedSint64\":[1,2]}") {$0.packedSint64 == [1, 2]}
assertJSONDecodeFails("{\"packedSint64\":[null]}")
assertJSONDecodeFails("{\"packedSint64\":[1.2]}")
}
func testPackedFixed32() {
assertJSONEncode("{\"packedFixed32\":[1]}") {(o: inout MessageTestType) in
o.packedFixed32 = [1]
}
assertJSONEncode("{\"packedFixed32\":[0,4294967295]}") {(o: inout MessageTestType) in
o.packedFixed32 = [UInt32.min, UInt32.max]
}
assertJSONDecodeSucceeds("{\"packedFixed32\":null}") {$0.packedFixed32 == []}
assertJSONDecodeSucceeds("{\"packedFixed32\":[]}") {$0.packedFixed32 == []}
assertJSONDecodeSucceeds("{\"packedFixed32\":[1]}") {$0.packedFixed32 == [1]}
assertJSONDecodeSucceeds("{\"packedFixed32\":[1,2]}") {$0.packedFixed32 == [1, 2]}
assertJSONDecodeFails("{\"packedFixed32\":[null]}")
assertJSONDecodeFails("{\"packedFixed32\":[-1]}")
assertJSONDecodeFails("{\"packedFixed32\":[1.2]}")
}
func testPackedFixed64() {
assertJSONEncode("{\"packedFixed64\":[\"1\"]}") {(o: inout MessageTestType) in
o.packedFixed64 = [1]
}
assertJSONEncode("{\"packedFixed64\":[\"0\",\"18446744073709551615\"]}") {
(o: inout MessageTestType) in
o.packedFixed64 = [UInt64.min, UInt64.max]
}
assertJSONDecodeSucceeds("{\"packedFixed64\":null}") {$0.packedFixed64 == []}
assertJSONDecodeSucceeds("{\"packedFixed64\":[]}") {$0.packedFixed64 == []}
assertJSONDecodeSucceeds("{\"packedFixed64\":[1]}") {$0.packedFixed64 == [1]}
assertJSONDecodeSucceeds("{\"packedFixed64\":[1,2]}") {$0.packedFixed64 == [1, 2]}
assertJSONDecodeFails("{\"packedFixed64\":[null]}")
assertJSONDecodeFails("{\"packedFixed64\":[-1]}")
assertJSONDecodeFails("{\"packedFixed64\":[1.2]}")
}
func testPackedSFixed32() {
assertJSONEncode("{\"packedSfixed32\":[1]}") {(o: inout MessageTestType) in
o.packedSfixed32 = [1]
}
assertJSONEncode("{\"packedSfixed32\":[-2147483648,2147483647]}") {(o: inout MessageTestType) in
o.packedSfixed32 = [Int32.min, Int32.max]
}
assertJSONDecodeSucceeds("{\"packedSfixed32\":null}") {$0.packedSfixed32 == []}
assertJSONDecodeSucceeds("{\"packedSfixed32\":[]}") {$0.packedSfixed32 == []}
assertJSONDecodeSucceeds("{\"packedSfixed32\":[1]}") {$0.packedSfixed32 == [1]}
assertJSONDecodeSucceeds("{\"packedSfixed32\":[1,2]}") {$0.packedSfixed32 == [1, 2]}
assertJSONDecodeFails("{\"packedSfixed32\":[null]}")
assertJSONDecodeFails("{\"packedSfixed32\":[1.2]}")
}
func testPackedSFixed64() {
assertJSONEncode("{\"packedSfixed64\":[\"1\"]}") {(o: inout MessageTestType) in
o.packedSfixed64 = [1]
}
assertJSONEncode("{\"packedSfixed64\":[\"-9223372036854775808\",\"9223372036854775807\"]}") {
(o: inout MessageTestType) in
o.packedSfixed64 = [Int64.min, Int64.max]
}
assertJSONDecodeSucceeds("{\"packedSfixed64\":null}") {$0.packedSfixed64 == []}
assertJSONDecodeSucceeds("{\"packedSfixed64\":[]}") {$0.packedSfixed64 == []}
assertJSONDecodeSucceeds("{\"packedSfixed64\":[1]}") {$0.packedSfixed64 == [1]}
assertJSONDecodeSucceeds("{\"packedSfixed64\":[1,2]}") {$0.packedSfixed64 == [1, 2]}
assertJSONDecodeFails("{\"packedSfixed64\":[null]}")
assertJSONDecodeFails("{\"packedSfixed64\":[1.2]}")
}
func testPackedBool() {
assertJSONEncode("{\"packedBool\":[true]}") {(o: inout MessageTestType) in
o.packedBool = [true]
}
assertJSONEncode("{\"packedBool\":[true,false]}") {
(o: inout MessageTestType) in
o.packedBool = [true,false]
}
assertJSONDecodeSucceeds("{\"packedBool\":null}") {$0.packedBool == []}
assertJSONDecodeSucceeds("{\"packedBool\":[]}") {$0.packedBool == []}
assertJSONDecodeFails("{\"packedBool\":[null]}")
assertJSONDecodeFails("{\"packedBool\":[1,0]}")
assertJSONDecodeFails("{\"packedBool\":[\"true\"]}")
assertJSONDecodeFails("{\"packedBool\":[\"false\"]}")
}
}
class Test_JSONrepeated: XCTestCase, PBTestHelpers {
typealias MessageTestType = Proto3Unittest_TestUnpackedTypes
func testPackedInt32() {
assertJSONEncode("{\"repeatedInt32\":[1]}") {(o: inout MessageTestType) in
o.repeatedInt32 = [1]
}
assertJSONEncode("{\"repeatedInt32\":[1,2]}") {(o: inout MessageTestType) in
o.repeatedInt32 = [1, 2]
}
assertEncode([8, 1, 8, 2]) {(o: inout MessageTestType) in
o.repeatedInt32 = [1, 2]
}
assertJSONDecodeSucceeds("{\"repeatedInt32\":null}") {$0.repeatedInt32 == []}
assertJSONDecodeSucceeds("{\"repeatedInt32\":[]}") {$0.repeatedInt32 == []}
assertJSONDecodeSucceeds("{\"repeatedInt32\":[1]}") {$0.repeatedInt32 == [1]}
assertJSONDecodeSucceeds("{\"repeatedInt32\":[1,2]}") {$0.repeatedInt32 == [1, 2]}
}
}
|
02550a476a793e3b297013a999134a73
| 49.814126 | 140 | 0.598764 | false | true | false | false |
zhiquan911/chance_btc_wallet
|
refs/heads/master
|
chance_btc_wallet/chance_btc_wallet/viewcontrollers/setting/SettingViewController.swift
|
mit
|
1
|
//
// SettingViewController.swift
// Chance_wallet
//
// Created by Chance on 16/1/26.
// Copyright © 2016年 Chance. All rights reserved.
//
import UIKit
class SettingViewController: BaseTableViewController {
/// 列表title
var rowsTitle: [[String]] = [
[
"Export Public Key".localized(),
"Export Private Key".localized(),
"Export RedeemScript".localized(),
],
[
"Export Wallet Passphrases".localized(),
"Restore Wallet By Passphrases".localized(),
],
[
"Security Setting".localized(),
],
[
"Blockchain Nodes".localized(),
],
[
"iCloud Auto Backup".localized(),
],
[
"Reset Wallet".localized(),
]
]
var currentAccount: CHBTCAcount? {
let i = CHBTCWallet.sharedInstance.selectedAccountIndex
if i != -1 {
return CHBTCWallet.sharedInstance.getAccount(byIndex: i)
} else {
return nil
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//CloudUtils.shared.query()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return self.rowsTitle.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
if let account = self.currentAccount {
if account.accountType == .multiSig {
return self.rowsTitle[section].count
} else {
return self.rowsTitle[section].count - 1
}
} else {
return 0
}
default:
return self.rowsTitle[section].count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SettingCell.cellIdentifier) as! SettingCell
cell.switchEnable.isHidden = true
cell.accessoryType = .disclosureIndicator
cell.labelTitle.text = self.rowsTitle[indexPath.section][indexPath.row]
switch indexPath.section {
case 4: //icloud同步开关
cell.accessoryType = .none
cell.switchEnable.isHidden = false
cell.switchEnable.isOn = CHWalletWrapper.enableICloud
//设置是否登录icloud账号
if CloudUtils.shared.iCloud {
cell.switchEnable.isEnabled = true
} else {
cell.switchEnable.isEnabled = false
}
//开关调用
cell.enableChange = {
(pressCell, sender) -> Void in
self.handleICloudBackupChange(sender: sender)
}
default:
cell.switchEnable.isHidden = true
cell.accessoryType = .disclosureIndicator
}
return cell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 18
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == self.numberOfSections(in: self.tableView) - 1 {
return 60
} else {
return 0.01
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let doBlock = {
() -> Void in
var title = ""
if indexPath.section == 0 {
var keyType = ExportKeyType.PublicKey
if indexPath.row == 0 {
keyType = ExportKeyType.PublicKey
title = "Public Key".localized()
} else if indexPath.row == 1 {
keyType = ExportKeyType.PrivateKey
title = "Private Key".localized()
} else if indexPath.row == 2 {
keyType = ExportKeyType.RedeemScript
title = "RedeemScript".localized()
}
guard let vc = StoryBoard.setting.initView(type: ExportKeyViewController.self) else {
return
}
vc.currentAccount = self.currentAccount!
vc.keyType = keyType
vc.navigationItem.title = title
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
} else if indexPath.section == 1 {
var restoreOperateType = RestoreOperateType.lookupPassphrase
var title = ""
if indexPath.row == 0 {
restoreOperateType = .lookupPassphrase
title = "Passphrase".localized()
} else {
restoreOperateType = .initiativeRestore
title = "Restore wallet".localized()
}
guard let vc = StoryBoard.setting.initView(type: RestoreWalletViewController.self) else {
return
}
vc.restoreOperateType = restoreOperateType
vc.navigationItem.title = title
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
} else if indexPath.section == 2 {
if indexPath.row == 0 {
guard let vc = StoryBoard.setting.initView(type: PasswordSettingViewController.self) else {
return
}
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
} else if indexPath.section == 3 {
//进入设置云节点
if indexPath.row == 0 {
guard let vc = StoryBoard.setting.initView(type: BlockchainNodeSettingViewController.self) else {
return
}
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
} else if indexPath.section == 4 {
} else if indexPath.section == 5 {
self.showResetWalletAlert()
}
}
switch indexPath.section {
case 0, 1, 2, 5: //需要密码
//需要提供指纹密码
CHWalletWrapper.unlock(vc: self, complete: {
(flag, error) in
if flag {
doBlock()
} else {
if error != "" {
SVProgressHUD.showError(withStatus: error)
}
}
})
default: //默认不需要密码
doBlock()
}
}
}
// MARK: - 控制器方法
extension SettingViewController {
/**
配置UI
*/
func setupUI() {
self.navigationItem.title = "Setting".localized()
}
/// 切换是否使用icloud备份
///
/// - Parameter sender:
@IBAction func handleICloudBackupChange(sender: UISwitch) {
CHWalletWrapper.enableICloud = sender.isOn
if sender.isOn {
//开启后,马上进行同步
let db = RealmDBHelper.shared.acountDB
RealmDBHelper.shared.iCloudSynchronize(db: db)
}
}
/// 弹出重置钱包的警告
func showResetWalletAlert() {
let actionSheet = UIAlertController(title: "Warning".localized(), message: "Please backup your passphrase before you do that.It's dangerous.".localized(), preferredStyle: UIAlertControllerStyle.actionSheet)
actionSheet.addAction(UIAlertAction(title: "Reset".localized(), style: UIAlertActionStyle.default, handler: {
(action) -> Void in
//删除钱包所有资料
CHWalletWrapper.deleteAllWallets()
//弹出欢迎界面,创新创建钱包
AppDelegate.sharedInstance().restoreWelcomeController()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertActionStyle.cancel, handler: {
(action) -> Void in
}))
self.present(actionSheet, animated: true, completion: nil)
}
}
|
819437cfabe82aea88f644219d8d581f
| 31.314685 | 214 | 0.516988 | false | false | false | false |
LeeMinglu/LSWeiboSwift
|
refs/heads/master
|
LSWeiboSwift/LSWeiboSwift/Classes/View/Main/VisitorView/LSVisitorView.swift
|
apache-2.0
|
1
|
//
// LSVisitorView.swift
// LSWeiboSwift
//
// Created by 李明禄 on 2017/8/19.
// Copyright © 2017年 SocererGroup. All rights reserved.
//
import UIKit
class LSVisitorView: UIView {
//添加注册按钮
lazy var regigterBtn:UIButton = UIButton.cz_textButton(
"注册",
fontSize: 16,
normalColor: .orange,
highlightedColor: .black,
backgroundImageName: "common_button_white_disable")
//添加登陆按钮
lazy var loginBtn:UIButton = UIButton.cz_textButton(
"登录",
fontSize: 16,
normalColor: .orange,
highlightedColor: .black,
backgroundImageName: "common_button_white_disable")
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: -设置visitorInfo
var visitorInfo: [String: String]? {
didSet {
guard let imageName = visitorInfo?["imageName"],
let message = visitorInfo?["message"]
else {
return
}
tipLabel.text = message
if imageName == "" {
startAnimate()
return
}
iconView.image = UIImage(named: imageName)
houseView.isHidden = true
maskIconView.isHidden = true
}
}
//MARK: - 旋转动画
fileprivate func startAnimate() {
let animate = CABasicAnimation(keyPath: "transform.rotation")
animate.toValue = Double.pi
animate.duration = 20
animate.repeatCount = MAXFLOAT
//必须添加在动作之前,否则是不生效的
animate.isRemovedOnCompletion = false
iconView.layer.add(animate, forKey: nil)
}
//MARK:- 懒加载视图
//添加image
fileprivate lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
//添加MaskIconImage
fileprivate lazy var maskIconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
//添加小房子
fileprivate lazy var houseView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
//添加label
fileprivate lazy var tipLabel: UILabel = UILabel.cz_label(withText: "关注一些人看看有什么惊喜吧", fontSize: 14, color: .darkGray)
}
extension LSVisitorView {
func setupUI() {
self.backgroundColor = UIColor.cz_color(withRed: 237, green: 237, blue: 237)
//1. 添加视图
addSubview(iconView)
addSubview(maskIconView)
addSubview(houseView)
addSubview(tipLabel)
addSubview(regigterBtn)
addSubview(loginBtn)
tipLabel.textAlignment = .center
//sb使用autolayout 代码使用autoresize
//2. 取消autoresize
for v in subviews {
v.translatesAutoresizingMaskIntoConstraints = false
}
//3.使用苹果原生设置布局
//设置iconView
addConstraint(NSLayoutConstraint(
item: iconView,
attribute: .centerX,
relatedBy: .equal,
toItem: self,
attribute: .centerX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: iconView,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1.0,
constant: -60))
//设置houseView
addConstraint(NSLayoutConstraint(
item: houseView,
attribute: .centerX,
relatedBy: .equal,
toItem: iconView,
attribute: .centerX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: houseView,
attribute: .centerY,
relatedBy: .equal,
toItem: iconView,
attribute: .centerY,
multiplier: 1.0,
constant: 20))
//设置tipLabel
addConstraint(NSLayoutConstraint(
item: tipLabel,
attribute: .centerX,
relatedBy: .equal,
toItem: iconView,
attribute: .centerX,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: tipLabel,
attribute: .top,
relatedBy: .equal,
toItem: iconView,
attribute: .bottom,
multiplier: 1.0,
constant: 20))
//在Label中显示内容换行
addConstraint(NSLayoutConstraint(
item: tipLabel,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 236))
//设置注册按钮
addConstraint(NSLayoutConstraint(
item: regigterBtn,
attribute: .left,
relatedBy: .equal,
toItem: tipLabel,
attribute: .left,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: regigterBtn,
attribute: .top,
relatedBy: .equal,
toItem: tipLabel,
attribute: .bottom,
multiplier: 1.0,
constant: 10))
addConstraint(NSLayoutConstraint(
item: regigterBtn,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 100))
//设置登陆按钮
addConstraint(NSLayoutConstraint(
item: loginBtn,
attribute: .right,
relatedBy: .equal,
toItem: tipLabel,
attribute: .right,
multiplier: 1.0,
constant: 0))
addConstraint(NSLayoutConstraint(
item: loginBtn,
attribute: .top,
relatedBy: .equal,
toItem: tipLabel,
attribute: .bottom,
multiplier: 1.0,
constant: 10))
addConstraint(NSLayoutConstraint(
item: loginBtn,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 100))
//使用VFL布局maskIcon
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[maskIconView]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["maskIconView": maskIconView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[maskIconView]-(0)-[regigterBtn]", options: .directionLeadingToTrailing, metrics: nil, views: ["maskIconView": maskIconView, "regigterBtn": regigterBtn]))
}
}
|
69f7d95f7c56133e23483f87ee5a6143
| 27.821138 | 233 | 0.535402 | false | false | false | false |
marcopolee/glimglam
|
refs/heads/master
|
Glimglam WatchKit Extension/NamespacesInterfaceController.swift
|
mit
|
1
|
//
// NamespacesInterfaceController.swift
// Glimglam WatchKit Extension
//
// Created by Tyrone Trevorrow on 15/10/17.
// Copyright © 2017 Marco Polee. All rights reserved.
//
import WatchKit
import Foundation
class NamespacesInterfaceController: WKInterfaceController {
var context: InterfaceContext!
@IBOutlet var table: WKInterfaceTable!
struct State {
let namespaces: [GitLab.Namespace]
}
var state = State(namespaces: []) {
didSet {
render()
}
}
override func awake(withContext context: Any?) {
self.context = context as! InterfaceContext
refreshData()
}
func refreshData() {
GitLab.API().getNamespaces(accessToken: context.context.gitLabLogin!) { res in
switch res {
case .Result(let namespaces):
self.state = State(namespaces: namespaces)
case .Error(let errStr):
print(errStr) // very sad
}
}
}
func render() {
table.setNumberOfRows(state.namespaces.count, withRowType: "Namespace")
for i in 0..<table.numberOfRows {
let row = table.rowController(at: i) as! NamespaceRowController
row.namespace = state.namespaces[i]
row.render()
}
}
override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? {
let namespace = state.namespaces[rowIndex]
return ProjectsInterfaceController.Context(context: context.context, namespace: namespace)
}
}
class NamespaceRowController: NSObject {
var namespace: GitLab.Namespace!
@IBOutlet var name: WKInterfaceLabel!
func render() {
name.setText(namespace.name)
}
}
|
3a1ffe3382ed93646fc02589a5d4f008
| 27.296875 | 126 | 0.626726 | false | false | false | false |
prey/prey-ios-client
|
refs/heads/master
|
Prey/Swifter/HttpServerIO.swift
|
gpl-3.0
|
1
|
//
// HttpServer.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
import Dispatch
public protocol HttpServerIODelegate: class {
func socketConnectionReceived(_ socket: Socket)
}
public class HttpServerIO {
public weak var delegate: HttpServerIODelegate?
private var socket = Socket(socketFileDescriptor: -1)
private var sockets = Set<Socket>()
public enum HttpServerIOState: Int32 {
case starting
case running
case stopping
case stopped
}
private var stateValue: Int32 = HttpServerIOState.stopped.rawValue
public private(set) var state: HttpServerIOState {
get {
return HttpServerIOState(rawValue: stateValue)!
}
set(state) {
#if !os(Linux)
OSAtomicCompareAndSwapInt(self.state.rawValue, state.rawValue, &stateValue)
#else
self.stateValue = state.rawValue
#endif
}
}
public var operating: Bool { return self.state == .running }
/// String representation of the IPv4 address to receive requests from.
/// It's only used when the server is started with `forceIPv4` option set to true.
/// Otherwise, `listenAddressIPv6` will be used.
public var listenAddressIPv4: String?
/// String representation of the IPv6 address to receive requests from.
/// It's only used when the server is started with `forceIPv4` option set to false.
/// Otherwise, `listenAddressIPv4` will be used.
public var listenAddressIPv6: String?
private let queue = DispatchQueue(label: "swifter.httpserverio.clientsockets")
public func port() throws -> Int {
return Int(try socket.port())
}
public func isIPv4() throws -> Bool {
return try socket.isIPv4()
}
deinit {
stop()
}
@available(macOS 10.10, *)
public func start(_ port: in_port_t = 8080, forceIPv4: Bool = false, priority: DispatchQoS.QoSClass = DispatchQoS.QoSClass.background) throws {
guard !self.operating else { return }
stop()
self.state = .starting
let address = forceIPv4 ? listenAddressIPv4 : listenAddressIPv6
self.socket = try Socket.tcpSocketForListen(port, forceIPv4, SOMAXCONN, address)
self.state = .running
DispatchQueue.global(qos: priority).async { [weak self] in
guard let strongSelf = self else { return }
guard strongSelf.operating else { return }
while let socket = try? strongSelf.socket.acceptClientSocket() {
DispatchQueue.global(qos: priority).async { [weak self] in
guard let strongSelf = self else { return }
guard strongSelf.operating else { return }
strongSelf.queue.async {
strongSelf.sockets.insert(socket)
}
strongSelf.handleConnection(socket)
strongSelf.queue.async {
strongSelf.sockets.remove(socket)
}
}
}
strongSelf.stop()
}
}
public func stop() {
guard self.operating else { return }
self.state = .stopping
// Shutdown connected peers because they can live in 'keep-alive' or 'websocket' loops.
for socket in self.sockets {
socket.close()
}
self.queue.sync {
self.sockets.removeAll(keepingCapacity: true)
}
socket.close()
self.state = .stopped
}
public func dispatch(_ request: HttpRequest) -> ([String: String], (HttpRequest) -> HttpResponse) {
return ([:], { _ in HttpResponse.notFound })
}
private func handleConnection(_ socket: Socket) {
let parser = HttpParser()
while self.operating, let request = try? parser.readHttpRequest(socket) {
let request = request
request.address = try? socket.peername()
let (params, handler) = self.dispatch(request)
request.params = params
let response = handler(request)
var keepConnection = parser.supportsKeepAlive(request.headers)
do {
if self.operating {
keepConnection = try self.respond(socket, response: response, keepAlive: keepConnection)
}
} catch {
print("Failed to send response: \(error)")
break
}
if let session = response.socketSession() {
delegate?.socketConnectionReceived(socket)
session(socket)
break
}
if !keepConnection { break }
}
socket.close()
}
private struct InnerWriteContext: HttpResponseBodyWriter {
let socket: Socket
func write(_ file: String.File) throws {
try socket.writeFile(file)
}
func write(_ data: [UInt8]) throws {
try write(ArraySlice(data))
}
func write(_ data: ArraySlice<UInt8>) throws {
try socket.writeUInt8(data)
}
func write(_ data: NSData) throws {
try socket.writeData(data)
}
func write(_ data: Data) throws {
try socket.writeData(data)
}
}
private func respond(_ socket: Socket, response: HttpResponse, keepAlive: Bool) throws -> Bool {
guard self.operating else { return false }
// Some web-socket clients (like Jetfire) expects to have header section in a single packet.
// We can't promise that but make sure we invoke "write" only once for response header section.
var responseHeader = String()
responseHeader.append("HTTP/1.1 \(response.statusCode()) \(response.reasonPhrase())\r\n")
let content = response.content()
if content.length >= 0 {
responseHeader.append("Content-Length: \(content.length)\r\n")
}
if keepAlive && content.length != -1 {
responseHeader.append("Connection: keep-alive\r\n")
}
for (name, value) in response.headers() {
responseHeader.append("\(name): \(value)\r\n")
}
responseHeader.append("\r\n")
try socket.writeUTF8(responseHeader)
if let writeClosure = content.write {
let context = InnerWriteContext(socket: socket)
try writeClosure(context)
}
return keepAlive && content.length != -1
}
}
|
2877d4a06878fbbdd0ca6703eec9f27d
| 31.497537 | 147 | 0.589965 | false | false | false | false |
CoderKman/AircraftWar
|
refs/heads/master
|
AircraftWar/AircraftWar/KMTopBarView.swift
|
apache-2.0
|
1
|
//
// KMTopBarView.swift
// Flivver
//
// Created by Kman on 15/7/14.
// Copyright (c) 2015年 Kman. All rights reserved.
//
import UIKit
protocol KMTopBarViewDelegate : NSObjectProtocol {
//代理方法
func operationClick()
}
class KMTopBarView: UIView {
@IBOutlet var content: KMTopBarView!
// 积分容器
@IBOutlet weak var scoreLabel: UILabel!
// 血量状态
@IBOutlet weak var HPProgressView: UIProgressView!
// 当前关卡
@IBOutlet weak var levelLabel: UILabel!
@IBOutlet weak var pauseBtn: UIButton!
//声明代理属性
var delegate : KMTopBarViewDelegate?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
let nib = UINib(nibName: "KMTopBarView", bundle: nil)
nib.instantiateWithOwner(self, options: nil)
content.frame = bounds
self.addSubview(content)
}
// 点击暂停
@IBAction func pauseClick(sender: UIButton) {
var title = self.pauseBtn.titleLabel?.text == "暂停" ? "继续" : "暂停"
self.pauseBtn.setTitle(title, forState: UIControlState.Normal)
self.delegate?.operationClick();
}
}
|
4531e56df415d692f0476236ea74c448
| 20.466667 | 72 | 0.610248 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS
|
refs/heads/master
|
SmartReceiptsTests/Utils/MatchableExtensions.swift
|
agpl-3.0
|
2
|
//
// MatchableExtensions.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 02/07/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
@testable import SmartReceipts
import Cuckoo
extension WBReceipt: Matchable {
public var matcher: ParameterMatcher<WBReceipt> {
get {
return ParameterMatcher(matchesFunction: { receipt -> Bool in
return self.isEqual(receipt)
})
}
}
}
extension UIImage: Matchable {
public var matcher: ParameterMatcher<UIImage> {
get {
return ParameterMatcher(matchesFunction: { image -> Bool in
return true
})
}
}
}
extension WBTrip: Matchable {
public var matcher: ParameterMatcher<WBTrip> {
get {
return ParameterMatcher(matchesFunction: { trip -> Bool in
return self.isEqual(trip)
})
}
}
}
extension Distance: Matchable {
public var matcher: ParameterMatcher<Distance> {
get {
return ParameterMatcher(matchesFunction: { distance -> Bool in
return self.objectId == distance.objectId
})
}
}
}
extension PaymentMethod: Matchable {
public var matcher: ParameterMatcher<PaymentMethod> {
get {
return ParameterMatcher(matchesFunction: { method -> Bool in
return self == method
})
}
}
}
extension WBCategory: Matchable {
public var matcher: ParameterMatcher<WBCategory> {
get {
return ParameterMatcher(matchesFunction: { category -> Bool in
return self == category
})
}
}
}
// MARK: Array<Column> : Matchable
extension Array: Matchable {
public var matcher: ParameterMatcher<Array<Column>> {
get {
return ParameterMatcher(matchesFunction: { columns -> Bool in
var matched = false
if self.count == columns.count && Element.self == Column.self {
for i in 0..<self.count {
if (self[i] as! Column).matcher.matches(columns[i]) {
continue
}
return false
}
matched = true
}
return matched
})
}
}
}
extension Column: Matchable {
public var matcher: ParameterMatcher<Column> {
get {
return ParameterMatcher(matchesFunction: { column -> Bool in
return self.name == column.name
})
}
}
}
extension Credentials: Matchable {
public var matcher: ParameterMatcher<Credentials> {
get {
return ParameterMatcher(matchesFunction: { credentials -> Bool in
return credentials.email == self.email && credentials.password == self.password
})
}
}
}
extension URL: Matchable {
public var matcher: ParameterMatcher<URL> {
get {
return ParameterMatcher(matchesFunction: { url -> Bool in
return self == url
})
}
}
}
|
18c763fe16ace2a4935432623a311381
| 25.31405 | 95 | 0.54554 | false | false | false | false |
dathtcheapgo/Jira-Demo
|
refs/heads/master
|
Driver/MVC/Register/Controller/RegisterViewController.swift
|
mit
|
1
|
//
// IntroduceRegisterViewController.swift
// Rider
//
// Created by Tien Dat on 10/27/16.
// Copyright © 2016 Đinh Anh Huy. All rights reserved.
//
import UIKit
class RegisterViewController: BaseViewController {
@IBOutlet weak var txtFirstName: UITextField!
@IBOutlet weak var txtLastName: UITextField!
@IBOutlet weak var txtEmail: TintTextField!
@IBOutlet weak var txtInviteCode: UITextField!
@IBOutlet weak var imgAvatar: UIImageView!
@IBOutlet weak var btGo: UIButton!
@IBOutlet weak var lbEmailInvalid: UILabel!
@IBOutlet weak var lbInvitationCodeInvalid: UILabel!
@IBOutlet weak var topSpacing: NSLayoutConstraint!
var originTopSpace:CGFloat?
let imagePicker = UIImagePickerController()
var crossButton:CrossButton!
@IBOutlet weak var btnGo: UIButton!
@IBAction func btGoDidClick(_ sender: UIButton) {
if txtEmail.hasText && !isValidEmail(testStr: txtEmail.text!) {
alert(title: "Invalid email", message: "", handler: { (action) in
self.lbEmailInvalid.isHidden = false
let color = UIColor(red: 222, green: 0, blue: 0)
self.txtEmail.tintColor = color
self.txtEmail.textColor = color
self.txtEmail.addBottomBorder(color: color)
self.txtEmail.becomeFirstResponder()
})
} else {
performSegue(withIdentifier: "Booking", sender: self)
}
}
override func viewWillAppear(_ animated: Bool) {
//originTopSpace = topSpacing.constant
btGo.layer.cornerRadius = btGo.frame.size.height / 2
self.view.layoutIfNeeded()
//hard-code here
// crossButton = CrossButton(frame:
// CGRect(x: imgAvatar.frame.origin.x + imgAvatar.frame.width * 0.75,
// y: imgAvatar.frame.origin.y,
// width: 20, height: 20))
//
// crossButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
// self.view.addSubview(crossButton)
NotificationCenter.default.addObserver(self,
selector: #selector(self.keyboardWillShown(notification:)),
name:NSNotification.Name.UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(self.keyboardWillHide(notification:)),
name:NSNotification.Name.UIKeyboardWillHide,
object: nil)
}
func keyboardWillShown(notification: NSNotification) {
let userInfo:NSDictionary = notification.userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
topSpacing.constant = originTopSpace! - keyboardHeight + 60
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
}
func keyboardWillHide(notification: NSNotification) {
topSpacing.constant = originTopSpace!
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
}
override func viewDidLayoutSubviews() {
txtFirstName.addBottomBorder(color: UIColor(netHex: 0xe6e6e6))
txtLastName.addBottomBorder(color: UIColor(netHex: 0xe6e6e6))
txtEmail.addBottomBorder(color: UIColor(netHex: 0xe6e6e6))
txtInviteCode.addBottomBorder(color: UIColor(netHex: 0xe6e6e6))
}
func buttonAction(sender: UIButton!) {
imgAvatar.image = nil
crossButton.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
//set textfield delegate to use custom action
setupTextField()
lbEmailInvalid.isHidden = true
lbInvitationCodeInvalid.isHidden = true
//set image picker delegate
imagePicker.delegate = self
self.view.layoutIfNeeded()
imgAvatar.layer.cornerRadius = imgAvatar.frame.size.height / 2
imgAvatar.layer.masksToBounds = true
updateStyleForButtonGo()
}
/// Tap Gesture Action
/// Present imagepicker view after tapped on avatarImageView
/// - parameter sender: Tao Gesture Regconizer
@IBAction func avatarPicture(_ sender: AnyObject) {
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
present(imagePicker, animated: true, completion: nil)
}
var isInputFieldValid: Bool {
if txtEmail.hasText && txtLastName.hasText && txtFirstName.hasText { return true }
return false
}
func isValidEmail(testStr:String) -> Bool {
print("validate emilId: \(testStr)")
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluate(with: testStr)
return result
}
}
extension RegisterViewController{
func setupTextField() {
txtEmail.addTarget(self,
action: #selector(self.textFieldDidChange(sender:)),
for: UIControlEvents.editingChanged)
txtLastName.addTarget(self,
action: #selector(self.textFieldDidChange(sender:)),
for: UIControlEvents.editingChanged)
txtFirstName.addTarget(self,
action: #selector(self.textFieldDidChange(sender:)),
for: UIControlEvents.editingChanged)
}
func textFieldDidChange(sender: UITextField) {
updateStyleForButtonGo()
}
func updateStyleForButtonGo() {
if !txtEmail.hasText && !txtFirstName.hasText &&
!txtLastName.hasText && imgAvatar.image == nil {
btnGo.setState(isSkip: true)
} else { btnGo.setState(isSkip: false) }
}
}
extension RegisterViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.imgAvatar.contentMode = .scaleAspectFill
self.imgAvatar.image = pickedImage
crossButton.isHidden = false
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
fileprivate extension UIButton {
func setState(isSkip: Bool) {
let color = UIColor.RGB(red: 4, green: 42, blue: 103)
if isSkip {
setTitle("Skip", for: .normal)
setTitleColor(color, for: .normal)
backgroundColor = UIColor.white
layer.borderWidth = 0.5
layer.borderColor = UIColor(red: 151, green: 151, blue: 151).cgColor
}
else {
setTitle("Go", for: .normal)
setTitleColor(UIColor.white, for: .normal)
backgroundColor = color
}
}
}
|
aeff696692c9ea020325bcf162502646
| 34.45 | 119 | 0.599436 | false | false | false | false |
MegaBits/SelfieBits
|
refs/heads/master
|
SelfieBits/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// SelfieBits
//
// Created by Patrick Perini on 12/21/14.
// Copyright (c) 2014 megabits. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: Properties
@IBOutlet var photoView: UIImageView?
@IBOutlet var stickerCollectionView: UICollectionView?
@IBOutlet var trashField: UIButton?
var stickerViews: [StickerView] = []
func resetPhoto() {
self.stickerViews.map {
$0.removeFromSuperview()
}
self.stickerViews = []
self.photoView?.image = nil
}
override func viewDidLoad() {
super.viewDidLoad()
self.stickerCollectionView?.reloadData()
StickerView.ControlProperties.deletionRect = CGRectInset(self.photoView!.convertRect(self.trashField!.frame, fromView: self.view), -50, -50)
NSNotificationCenter.defaultCenter().addObserverForName("StickerViewAdded", object: nil, queue: nil) { (note: NSNotification?) in
if let sticker: StickerView = note?.object as? StickerView {
self.stickerViews.append(sticker)
}
}
NSNotificationCenter.defaultCenter().addObserverForName("StickerViewDeleted", object: nil, queue: nil) { (note: NSNotification?) in
if let sticker: StickerView = note?.object as? StickerView {
UIView.animateWithDuration(0.25, animations: {
sticker.transform = CGAffineTransformScale(sticker.transform, 0.0001, 0.0001)
}, completion: {(finished: Bool) in
sticker.removeFromSuperview()
self.stickerViews = self.stickerViews.filter {
return $0 != sticker
}
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cameraButtonWasPressed(sender: UIButton) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(imagePicker,
animated: true,
completion: nil)
}
@IBAction func megabitsButtonWasPressed(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: "https://itunes.apple.com/us/app/megabits/id933449722?ls=1&mt=8")!)
}
@IBAction func shareButtonWasPressed(sender: UIButton) {
// Flash screen
let flashView: UIView = UIView(frame: UIScreen.mainScreen().bounds)
flashView.backgroundColor = UIColor.whiteColor()
flashView.layer.zPosition = CGFloat.max
flashView.alpha = 0.0
UIApplication.sharedApplication().keyWindow?.addSubview(flashView)
UIView.animateWithDuration(0.06) {
flashView.alpha = 1.0
}
// Pull image
var snapshot: UIImage
UIGraphicsBeginImageContext(self.photoView!.frame.size)
self.photoView!.drawViewHierarchyInRect(self.photoView!.bounds, afterScreenUpdates: false)
snapshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIView.animateWithDuration(0.94, animations: {
flashView.alpha = 0.0
}, completion: { (completed: Bool) in
flashView.removeFromSuperview()
})
var popTime = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(0.01 * Float(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
// Share
var caption = "#selfiebits"
let activityPicker = UIActivityViewController(activityItems: [snapshot, caption], applicationActivities: nil)
if activityPicker.respondsToSelector("popoverPresentationController") {
let presentationController: UIPopoverPresentationController? = activityPicker.popoverPresentationController!
presentationController?.sourceView = sender
}
activityPicker.completionHandler = { (activityType: String!, completed: Bool) in
if completed {
self.resetPhoto()
}
}
self.presentViewController(activityPicker, animated: true, completion: {
})
}
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 40
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell: StickerCellView? = collectionView.dequeueReusableCellWithReuseIdentifier("StickerCell", forIndexPath: indexPath) as? StickerCellView
cell?.photoView = self.photoView
switch indexPath.row {
case 39:
cell?.imageView?.image = UIImage(named: "XXX.png")
default:
cell?.imageView?.image = UIImage(named: String(format: "%03d.png", indexPath.row))
}
cell?.imageView?.layer.magnificationFilter = kCAFilterNearest
return cell!
}
}
extension ViewController: UINavigationControllerDelegate {
}
extension ViewController: UIImagePickerControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
self.presentedViewController?.dismissViewControllerAnimated(true, completion: nil)
if let image: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.resetPhoto()
self.photoView?.image = image
}
}
}
|
f2af7a52aa9a769ca1a6b1b3b57ae1f0
| 37.558442 | 150 | 0.641233 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
WordPress/Classes/ViewRelated/Stats/Extensions/Double+Stats.swift
|
gpl-2.0
|
1
|
import Foundation
fileprivate struct Unit {
let abbreviationFormat: String
let accessibilityLabelFormat: String
}
extension Double {
private var numberFormatter: NumberFormatter {
get {
struct Cache {
static let formatter: NumberFormatter = {
let formatter = NumberFormatter()
// Add commas to value
formatter.numberStyle = .decimal
return formatter
}()
}
return Cache.formatter
}
}
private var decimalFormatter: NumberFormatter {
get {
struct Cache {
static let formatter: NumberFormatter = {
let formatter = NumberFormatter()
// Show at least one digit after the decimal
formatter.minimumFractionDigits = 1
return formatter
}()
}
return Cache.formatter
}
}
private var units: [Unit] {
get {
struct Cache {
static let units: [Unit] = {
var units: [Unit] = []
// Note: using `AppLocalizedString` here (instead of `NSLocalizedString`) to ensure that strings
// will be looked up from the app's _own_ `Localizable.strings` file, even when this file is used
// as part of an _App Extension_ (especially our various stats Widgets which also use this file)
units.append(Unit(
abbreviationFormat: AppLocalizedString("%@K", comment: "Label displaying value in thousands. Ex: 66.6K."),
accessibilityLabelFormat: AppLocalizedString("%@ thousand", comment: "Accessibility label for value in thousands. Ex: 66.6 thousand.")
))
units.append(Unit(
abbreviationFormat: AppLocalizedString("%@M", comment: "Label displaying value in millions. Ex: 66.6M."),
accessibilityLabelFormat: AppLocalizedString("%@ million", comment: "Accessibility label for value in millions. Ex: 66.6 million.")
))
units.append(Unit(
abbreviationFormat: AppLocalizedString("%@B", comment: "Label displaying value in billions. Ex: 66.6B."),
accessibilityLabelFormat: AppLocalizedString("%@ billion", comment: "Accessibility label for value in billions. Ex: 66.6 billion.")
))
units.append(Unit(
abbreviationFormat: AppLocalizedString("%@T", comment: "Label displaying value in trillions. Ex: 66.6T."),
accessibilityLabelFormat: AppLocalizedString("%@ trillion", comment: "Accessibility label for value in trillions. Ex: 66.6 trillion.")
))
units.append(Unit(
abbreviationFormat: AppLocalizedString("%@P", comment: "Label displaying value in quadrillions. Ex: 66.6P."),
accessibilityLabelFormat: AppLocalizedString("%@ quadrillion", comment: "Accessibility label for value in quadrillion. Ex: 66.6 quadrillion.")
))
units.append(Unit(
abbreviationFormat: AppLocalizedString("%@E", comment: "Label displaying value in quintillions. Ex: 66.6E."),
accessibilityLabelFormat: AppLocalizedString("%@ quintillion", comment: "Accessibility label for value in quintillions. Ex: 66.6 quintillion.")
))
return units
}()
}
return Cache.units
}
}
/// Provides a short, friendly representation of the current Double value. If the value is
/// below 10,000, the decimal is stripped and the string returned will look like an Int. If the value
/// is above 10,000, the value is rounded to the nearest tenth and the appropriate abbreviation
/// will be appended (k, m, b, t, p, e).
///
/// Examples:
/// - 0 becomes "0"
/// - 9999 becomes "9999"
/// - 10000 becomes "10.0k"
/// - 987654 becomes "987.7k"
/// - 999999 becomes "1m"
/// - 1000000 becomes "1m"
/// - 1234324 becomes "1.2m"
/// - 5800199 becomes "5.8m"
/// - 5897459 becomes "5.9m"
/// - 1000000000 becomes "1b"
/// - 1000000000000 becomes "1t"
func abbreviatedString(forHeroNumber: Bool = false) -> String {
let absValue = fabs(self)
let abbreviationLimit = forHeroNumber ? 100000.0 : 10000.0
if absValue < abbreviationLimit {
return self.formatWithCommas()
}
let exp: Int = Int(log10(absValue) / 3.0)
let unsignedRoundedNum: Double = Foundation.round(10 * absValue / pow(1000.0, Double(exp))) / 10
var roundedNum: Double
var unit: Unit
if unsignedRoundedNum == 1000.0 {
guard exp >= units.startIndex else {
return self.formatWithCommas()
}
roundedNum = 1
unit = units[exp]
} else {
let unitIndex = exp - 1
guard unitIndex >= units.startIndex else {
return self.formatWithCommas()
}
roundedNum = unsignedRoundedNum
unit = units[unitIndex]
}
roundedNum = self < 0 ? -roundedNum : roundedNum
let formattedValue = roundedNum.formatWithFractions()
let formattedString = String.localizedStringWithFormat(unit.abbreviationFormat, formattedValue)
formattedString.accessibilityLabel = String.localizedStringWithFormat(unit.accessibilityLabelFormat, formattedValue)
return formattedString
}
private func formatWithCommas() -> String {
return numberFormatter.string(for: self) ?? ""
}
private func formatWithFractions() -> String {
return decimalFormatter.string(for: self) ?? String(self)
}
}
extension NSNumber {
func abbreviatedString(forHeroNumber: Bool = false) -> String {
return self.doubleValue.abbreviatedString(forHeroNumber: forHeroNumber)
}
}
extension Float {
func abbreviatedString(forHeroNumber: Bool = false) -> String {
return Double(self).abbreviatedString(forHeroNumber: forHeroNumber)
}
}
extension Int {
func abbreviatedString(forHeroNumber: Bool = false) -> String {
return Double(self).abbreviatedString(forHeroNumber: forHeroNumber)
}
}
|
09601038270f2cbc8f430b20b53cdb9b
| 37.412791 | 167 | 0.579688 | false | false | false | false |
dduan/swift
|
refs/heads/master
|
stdlib/public/core/ArrayType.swift
|
apache-2.0
|
2
|
//===--- ArrayType.swift - Protocol for Array-like types ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public // @testable
protocol _ArrayProtocol
: RangeReplaceableCollection,
ArrayLiteralConvertible
{
//===--- public interface -----------------------------------------------===//
/// The number of elements the Array stores.
var count: Int { get }
/// The number of elements the Array can store without reallocation.
var capacity: Int { get }
/// `true` if and only if the Array is empty.
var isEmpty: Bool { get }
/// An object that guarantees the lifetime of this array's elements.
var _owner: AnyObject? { get }
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
var _baseAddressIfContiguous: UnsafeMutablePointer<Element> { get }
subscript(index: Int) -> Iterator.Element { get set }
//===--- basic mutations ------------------------------------------------===//
/// Reserve enough space to store minimumCapacity elements.
///
/// - Postcondition: `capacity >= minimumCapacity` and the array has
/// mutable contiguous storage.
///
/// - Complexity: O(`self.count`).
mutating func reserveCapacity(minimumCapacity: Int)
/// Operator form of `append(contentsOf:)`.
func += <
S : Sequence where S.Iterator.Element == Iterator.Element
>(lhs: inout Self, rhs: S)
/// Insert `newElement` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
///
/// - Precondition: `i <= count`.
mutating func insert(newElement: Iterator.Element, at i: Int)
/// Remove and return the element at the given index.
///
/// - returns: The removed element.
///
/// - Complexity: Worst case O(N).
///
/// - Precondition: `count > index`.
mutating func remove(at index: Int) -> Iterator.Element
//===--- implementation detail -----------------------------------------===//
associatedtype _Buffer : _ArrayBufferProtocol
init(_ buffer: _Buffer)
// For testing.
var _buffer: _Buffer { get }
}
|
35c2733ec1756a330e0200db761a7ac2
| 31.480519 | 80 | 0.60096 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/WordPressTest/MediaPicker/Tenor/TenorReponseData.swift
|
gpl-2.0
|
2
|
import Foundation
class TenorReponseData {
static let validSearchResponse: Data = {
dataFromJsonResource("tenor-search-response")
}()
static let invalidSearchResponse: Data = {
dataFromJsonResource("tenor-invalid-search-reponse")
}()
static let emptyMediaSearchResponse =
"""
{
"weburl": "https://tenor.com/search/cat-gifs",
"results": [
],
}
"""
.data(using: .utf8)!
fileprivate static func dataFromJsonResource(_ resource: String) -> Data {
let json = Bundle(for: TenorReponseData.self).url(forResource: resource, withExtension: "json")!
let data = try! Data(contentsOf: json)
return data
}
}
|
042298aa2294be118e983717ce0731cb
| 25.357143 | 104 | 0.601626 | false | false | false | false |
jpush/aurora-imui
|
refs/heads/master
|
iOS/sample/sample/MyMessageModel.swift
|
mit
|
1
|
//
// MyMessageModel.swift
// IMUIChat
//
// Created by oshumini on 2017/3/5.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
class MyMessageModel: IMUIMessageModel {
open var myTextMessage: String = ""
var mediaPath = ""
var imageUrl = ""
override func mediaFilePath() -> String {
return mediaPath
}
override func webImageUrl() -> String {
return self.imageUrl
}
override var resizableBubbleImage: UIImage {
// return defoult message bubble
return super.resizableBubbleImage
}
init(msgId: String, messageStatus: IMUIMessageStatus, fromUser: MyUser, isOutGoing: Bool, date: Date, type: String, text: String, mediaPath: String, layout: IMUIMessageCellLayoutProtocol, duration: CGFloat?) {
self.myTextMessage = text
self.mediaPath = mediaPath
let chatTime = MyMessageModel.formatChatDate(date: date)
super.init(msgId: msgId, messageStatus: messageStatus, fromUser: fromUser, isOutGoing: isOutGoing, time: chatTime, type: type, cellLayout: layout, duration: duration)
}
convenience init(text: String, isOutGoing: Bool) {
let myLayout = MyMessageCellLayout(isOutGoingMessage: isOutGoing,
isNeedShowTime: true,
bubbleContentSize: MyMessageModel.calculateTextContentSize(text: text),
bubbleContentInsets: UIEdgeInsets.zero,
timeLabelContentSize: CGSize(width: 200, height: 20),
type: "text")
let msgId = "\(NSDate().timeIntervalSince1970 * 1000)"
self.init(msgId: msgId, messageStatus: .failed, fromUser: MyUser(), isOutGoing: isOutGoing, date: Date(), type: "text", text: text, mediaPath: "", layout: myLayout, duration: nil)
}
convenience init(voicePath: String, duration: CGFloat, isOutGoing: Bool) {
let myLayout = MyMessageCellLayout(isOutGoingMessage: isOutGoing,
isNeedShowTime: true,
bubbleContentSize: CGSize(width: 80, height: 37),
bubbleContentInsets: UIEdgeInsets.zero,
timeLabelContentSize: CGSize(width: 200, height: 20),
type: "voice")
let msgId = "\(NSDate().timeIntervalSince1970 * 1000)"
self.init(msgId: msgId, messageStatus: .sending, fromUser: MyUser(), isOutGoing: isOutGoing, date: Date(), type: "voice", text: "", mediaPath: voicePath, layout: myLayout, duration: duration)
}
convenience init(imagePath: String, isOutGoing: Bool) {
let msgId = "\(NSDate().timeIntervalSince1970 * 1000)"
var imgSize = CGSize(width: 120, height: 160)
if let img = UIImage(contentsOfFile: imagePath) {
imgSize = MyMessageModel.converImageSize(with: CGSize(width: (img.cgImage?.width)!, height: (img.cgImage?.height)!))
}
let myLayout = MyMessageCellLayout(isOutGoingMessage: isOutGoing,
isNeedShowTime: true,
bubbleContentSize: imgSize,
bubbleContentInsets: UIEdgeInsets.zero,
timeLabelContentSize: CGSize(width: 200, height: 20),
type: "image")
self.init(msgId: msgId, messageStatus: .sending, fromUser: MyUser(), isOutGoing: isOutGoing, date: Date(), type: "image", text: "", mediaPath: imagePath, layout: myLayout, duration: nil)
}
convenience init(imageUrl: String, isOutGoing: Bool) {
let msgId = "\(NSDate().timeIntervalSince1970 * 1000)"
let myLayout = MyMessageCellLayout(isOutGoingMessage: isOutGoing,
isNeedShowTime: true,
bubbleContentSize: CGSize(width: 120, height: 160),
bubbleContentInsets: UIEdgeInsets.zero,
timeLabelContentSize: CGSize(width: 200, height: 20),
type: "image")
self.init(msgId: msgId, messageStatus: .sending, fromUser: MyUser(), isOutGoing: isOutGoing, date: Date(), type: "image", text: "", mediaPath: "", layout: myLayout, duration: nil)
self.imageUrl = imageUrl
}
convenience init(videoPath: String, isOutGoing: Bool) {
let myLayout = MyMessageCellLayout(isOutGoingMessage: isOutGoing,
isNeedShowTime: true,
bubbleContentSize: CGSize(width: 120, height: 160),
bubbleContentInsets: UIEdgeInsets.zero,
timeLabelContentSize: CGSize(width: 200, height: 20),
type: "video")
let msgId = "\(NSDate().timeIntervalSince1970 * 1000)"
self.init(msgId: msgId, messageStatus: .sending, fromUser: MyUser(), isOutGoing: isOutGoing, date: Date(), type: "video", text: "", mediaPath: videoPath, layout: myLayout, duration: nil)
}
override func text() -> String {
return self.myTextMessage
}
static func calculateTextContentSize(text: String) -> CGSize {
let textSize = text.sizeWithConstrainedWidth(with: IMUIMessageCellLayout.bubbleMaxWidth, font: UIFont.systemFont(ofSize: 18))
return textSize
}
static func calculateNameContentSize(text: String) -> CGSize {
return text.sizeWithConstrainedWidth(with: 200,
font: IMUIMessageCellLayout.timeStringFont)
}
static func converImageSize(with size: CGSize) -> CGSize {
let maxSide = 160.0
var scale = size.width / size.height
if size.width > size.height {
scale = scale > 2 ? 2 : scale
return CGSize(width: CGFloat(maxSide), height: CGFloat(maxSide) / CGFloat(scale))
} else {
scale = scale < 0.5 ? 0.5 : scale
return CGSize(width: CGFloat(maxSide) * CGFloat(scale), height: CGFloat(maxSide))
}
}
/// Format chat date.
static func formatChatDate(date: Date) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.string(from: date)
}
}
//MARK - IMUIMessageCellLayoutProtocol
class MyMessageCellLayout: IMUIMessageCellLayout {
var type: String
init(isOutGoingMessage: Bool, isNeedShowTime: Bool, bubbleContentSize: CGSize, bubbleContentInsets: UIEdgeInsets, timeLabelContentSize: CGSize,type: String) {
self.type = type
super.init(isOutGoingMessage: isOutGoingMessage,
isNeedShowTime: isNeedShowTime,
bubbleContentSize: bubbleContentSize,
bubbleContentInsets: UIEdgeInsets.zero,
timeLabelContentSize: timeLabelContentSize)
}
override var bubbleContentInset: UIEdgeInsets {
if type != "text" { return UIEdgeInsets.zero }
if isOutGoingMessage {
return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 15)
} else {
return UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 10)
}
}
override var bubbleContentView: IMUIMessageContentViewProtocol {
switch type {
case "text":
return IMUITextMessageContentView()
case "image":
return IMUIImageMessageContentView()
case "voice":
return IMUIVoiceMessageContentView()
case "video":
return IMUIVideoMessageContentView()
default:
return IMUIDefaultContentView()
}
}
override var bubbleContentType: String {
return type
}
}
|
1659d36baae5a988f16bb422af35037b
| 39.962766 | 211 | 0.611609 | false | false | false | false |
RxSwiftCommunity/RxHttpClient
|
refs/heads/master
|
RxHttpClientTests/URLRequestTests.swift
|
mit
|
1
|
//
// URLRequestTests.swift
// RxHttpClient
//
// Created by Anton Efimenko on 31.10.16.
// Copyright © 2016 RxSwift Community. All rights reserved.
//
import XCTest
@testable import RxHttpClient
class URLRequestTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testInitRequest() {
let url = URL(string: "https://test.com")!
let request = URLRequest(url: url)
XCTAssertEqual(url, request.url)
XCTAssertNil(request.allHTTPHeaderFields)
}
func testInitRequestWithHeaders() {
let url = URL(string: "https://test.com")!
let headers = ["header1": "value1", "header2": "value2"]
let request = URLRequest(url: url, headers: headers)
XCTAssertEqual(url, request.url)
XCTAssertEqual(headers, request.allHTTPHeaderFields!)
}
func testInitWithCustomMethodAndBody() {
let url = URL(string: "https://test.com")!
let headers = ["header1": "value1", "header2": "value2"]
let bodyData = "test body data".data(using: .utf8)!
let request = URLRequest(url: url, method: .put, body: bodyData, headers: headers)
XCTAssertEqual(url, request.url)
XCTAssertEqual(HttpMethod.put.rawValue, request.httpMethod)
XCTAssertTrue(request.httpBody?.elementsEqual(bodyData) ?? false)
XCTAssertEqual(headers, request.allHTTPHeaderFields!)
}
func testInitWithJsonBody() {
let url = URL(string: "https://test.com")!
let headers = ["header1": "value1", "header2": "value2"]
let bodyJson: [String: Any] = ["key1": "val1", "key2": "val2", "key3": "val3"]
let request = URLRequest(url: url, method: .patch, jsonBody: bodyJson, options: [JSONSerialization.WritingOptions.prettyPrinted], headers: headers)!
XCTAssertEqual(url, request.url)
XCTAssertEqual(HttpMethod.patch.rawValue, request.httpMethod)
XCTAssertEqual(headers, request.allHTTPHeaderFields!)
let bodyData = try! JSONSerialization.data(withJSONObject: bodyJson, options: [JSONSerialization.WritingOptions.prettyPrinted])
XCTAssertTrue(request.httpBody?.elementsEqual(bodyData) ?? false)
let deserialized = try! JSONSerialization.jsonObject(with: request.httpBody!, options: []) as! [String: String]
XCTAssertEqual(bodyJson as! [String: String], deserialized)
}
func testNotInitWithInvalidJsonBody() {
let url = URL(string: "https://test.com")!
let headers = ["header1": "value1", "header2": "value2"]
let bodyJson: Any = "shit"
let request = URLRequest(url: url, method: .patch, jsonBody: bodyJson, options: [JSONSerialization.WritingOptions.prettyPrinted], headers: headers)
XCTAssertNil(request, "Should return nil because invalid json body object passed")
}
}
|
6a63b8dc86838c68af842f53fab00402
| 38.232877 | 150 | 0.72905 | false | true | false | false |
kaideyi/KDYSample
|
refs/heads/master
|
KYWebo/KYWebo/Bizs/Home/Controller/KYHomeController.swift
|
mit
|
1
|
//
// KYHomeController.swift
// KYWebo
//
// Created by KYCoder on 2017/8/10.
// Copyright © 2017年 mac. All rights reserved.
//
/**
* 实现思路可直接参考:https://github.com/ibireme/YYKit
*/
import UIKit
import SnapKit
/// Webo首页
class KYHomeController: UIViewController {
// MARK: - Properites
let timelineIdentifier = "timelineCell"
lazy var tableView: UITableView = {
let tb = UITableView()
tb.backgroundColor = UIColor(hexString: "#f2f2f2")
tb.tableFooterView = UIView()
tb.separatorStyle = .none
tb.dataSource = self
tb.delegate = self
return tb
}()
lazy var viewModel: HomeViewModel = {
let viewmodel = HomeViewModel()
return viewmodel
}()
var dataSource: NSMutableArray = []
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Webo"
self.view.backgroundColor = .white
setupViews()
setupRefresh()
}
func setupViews() {
view.addSubview(tableView)
tableView.register(HomeTimelineCell.classForCoder(), forCellReuseIdentifier: timelineIdentifier)
tableView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
}
func setupRefresh() {
tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
self.tableViewHeaderDidRefresh()
})
tableView.mj_header.beginRefreshing()
}
// MARK: -
func tableViewHeaderDidRefresh() {
// 请求并同时回调结果
viewModel.requestTimeline()
viewModel.timelineSuccess = { array in
DispatchQueue.main.async {
self.tableView.mj_header.endRefreshing()
self.dataSource = array as! NSMutableArray
self.tableView.reloadData()
}
}
viewModel.timelineFailed = { error in
print("error = \(error)")
}
}
}
// MARK: -
extension KYHomeController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: timelineIdentifier, for: indexPath) as! HomeTimelineCell
if let viewModel = dataSource[indexPath.row] as? HomeItemViewModel {
cell.setupCell(withViewmodel: viewModel)
}
return cell
}
}
// MARK: -
extension KYHomeController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let itemViewmodel = dataSource[indexPath.row] as? HomeItemViewModel {
return itemViewmodel.totalHeight
}
return 0
}
// Webo的需求不适合用此方法 (正文区与转发区都有点击事件)
// func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// tableView.deselectRow(at: indexPath, animated: true)
// }
}
|
a48eaf8e309998725f79d297dc0c181e
| 25.188525 | 121 | 0.606886 | false | false | false | false |
mahuiying0126/MDemo
|
refs/heads/master
|
BangDemo/BangDemo/Define/Comment/MVideoOrAudioSet.swift
|
mit
|
1
|
//
// MVideoOrAudioSet.swift
// BangDemo
//
// Created by yizhilu on 2017/8/15.
// Copyright © 2017年 Magic. All rights reserved.
//
import Foundation
public let PlayerMedia96KType = "96K"
public let PlayerMediaCCType = "CC"
public let PlayerMediaPolyType = "POLYV"
public let MediaUnknownType = "UNKNOWN"
public let MediaVideoType = "VIDEO"
public let MediaAudioType = "AUDIO"
|
c7449e69f92b893367c3ae364965e5f6
| 22.9375 | 49 | 0.744125 | false | false | false | false |
EventsNetwork/Source
|
refs/heads/master
|
LetsTravel/Utils.swift
|
apache-2.0
|
1
|
//
// Utils.swift
// LetsTravel
//
// Created by phuong le on 4/26/16.
// Copyright © 2016 TriNgo. All rights reserved.
//
import UIKit
class Utils: NSObject {
static func fromPriceToString(price: Double) -> String {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .DecimalStyle
numberFormatter.maximumFractionDigits = 0
return numberFormatter.stringFromNumber(price) ?? "0"
}
static func dateTotring(date: NSDate, format: String) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = format
return dateFormatter.stringFromDate(date)
}
}
|
3b01d4b818aeb0616bc82b5cf289f434
| 26.074074 | 69 | 0.673051 | false | false | false | false |
luckymore0520/leetcode
|
refs/heads/master
|
Search Insert Position.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
//Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
//
//You may assume no duplicates in the array.
//
//Here are few examples.
//[1,3,5,6], 5 → 2
//[1,3,5,6], 2 → 1
//[1,3,5,6], 7 → 4
//[1,3,5,6], 0 → 0
//同样也是二分查找,但是需要保存最后一个查找的位置
class Solution {
var lastVisitIndex = -1
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
let index = binarySearch(nums, target, start: 0, end: nums.count - 1)
if (index == -1) {
let placeShouldInsert = lastVisitIndex;
lastVisitIndex = -1
return placeShouldInsert
}
return index
}
func binarySearch(_ nums:[Int], _ target:Int, start:Int, end:Int) -> Int {
if (start > end) {
lastVisitIndex = start
return -1
}
let middle = (start + end) / 2
if (nums[middle] > target) {
return binarySearch(nums, target, start: start, end: middle-1)
} else if (nums[middle] < target) {
return binarySearch(nums, target, start: middle + 1, end: end)
} else {
return middle
}
}
}
let solution = Solution()
solution.searchInsert([1,3,5,6], 0)
|
86c59953eff527f6e7840369998517fa
| 26.653061 | 156 | 0.569004 | false | false | false | false |
davidbutz/ChristmasFamDuels
|
refs/heads/master
|
iOS/Boat Aware/LineView.swift
|
mit
|
1
|
//
// LineView.swift
// Boat Aware
//
// Created by Adam Douglass on 6/28/16.
// Copyright © 2016 Thrive Engineering. All rights reserved.
//
import UIKit
class LineView : UIView {
var width : CGFloat = 2.0;
var startPosition : CGPoint?
var endPosition : CGPoint?
init(frame: CGRect, lineWidth: CGFloat, leftMargin: CGFloat, rightMargin: CGFloat) {
super.init(frame: frame);
self.opaque = false;
let yPos = width / 2.0;
self.width = lineWidth;
self.startPosition = CGPoint(x: leftMargin, y: yPos);
self.endPosition = CGPoint(x: frame.width - rightMargin, y: yPos);
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
override func drawRect(rect: CGRect) {
super.drawRect(rect);
if (startPosition != nil && endPosition != nil) {
let context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, UIColor.darkGrayColor().CGColor);
CGContextSetLineWidth(context, self.width);
CGContextMoveToPoint(context, (startPosition?.x)!, (startPosition?.y)!);
CGContextAddLineToPoint(context, (endPosition?.x)!, (endPosition?.y)!);
CGContextStrokePath(context);
}
}
}
|
8962b1d1f0658202d72f44c0c1435887
| 31.170732 | 88 | 0.619409 | false | false | false | false |
scottrhoyt/Optimize
|
refs/heads/master
|
Optimize/Solver.swift
|
mit
|
1
|
import Foundation
public typealias SolverVar = Double
public typealias SolverFunc = (SolverVar) -> SolverVar
public func finiteDifference(f: SolverFunc, increment: Double) -> SolverFunc {
let approx = {
(x: SolverVar) -> SolverVar in
return (f(x+increment) - f(x))/increment
}
return approx
}
public protocol Solver {
var increment: Double { get set }
var maxIter: Int { get set }
var tolerance: Double { get set }
var limitTolerance: Double { get set }
func solve(guess: SolverVar, f: SolverFunc, gradient: SolverFunc?) throws -> SolverResults
func minMax(guess: SolverVar, f: SolverFunc, gradient: SolverFunc?, gradient2: SolverFunc?) throws -> SolverResults
func genNextX(x: SolverVar, value: Double, gradient: Double) -> SolverVar
}
public extension Solver {
public func minMax(guess: SolverVar, f: SolverFunc, gradient: SolverFunc? = nil, gradient2: SolverFunc? = nil) throws -> SolverResults {
let deriv = gradient != nil ? gradient! : finiteDifference(f, increment: increment)
return try solve(guess, f: deriv, gradient: gradient2)
}
public func solve(guess: SolverVar, f: SolverFunc, gradient: SolverFunc? = nil) throws -> SolverResults {
let deriv = gradient != nil ? gradient! : finiteDifference(f, increment: increment)
var values = SolverValues(result: guess, value: 0, iterations: 0, valueChange: 0, gradient: guess, lastValue: 0)
repeat {
values.result = values.iterations == 0 ? guess : genNextX(values.result, value: values.value, gradient: values.gradient)
values.value = f(values.result)
values.valueChange = values.iterations == 0 ? Double.infinity : abs(values.value - values.lastValue)
values.gradient = deriv(values.result)
log(values)
values.lastValue = values.value
values.iterations++
} while try checkConditions(values)
return values
}
internal func log(values: SolverValues) {
print("Iter:\t\(values.iterations)\tx:\t\(values.result)\tvalue:\t\(values.value)\tgradient:\t\(values.gradient)")
}
internal func checkConditions(values: SolverValues) throws -> Bool {
try checkForError(values)
return abs(values.value) > tolerance
}
internal func checkForError(values: SolverValues) throws {
if values.iterations == maxIter {
throw SolverError.MaxIterationsReached(results: values)
}
else if values.valueChange <= limitTolerance {
throw SolverError.FunctionChangeBelowTolerance(results: values)
}
}
}
|
dfbff97fb67c5027b8eefe49b13a666b
| 37.492958 | 140 | 0.647877 | false | false | false | false |
Shashi717/ImmiGuide
|
refs/heads/master
|
ImmiGuide/ImmiGuide/Tour Cell.swift
|
mit
|
1
|
//
// Tour Cell.swift
// ImmiGuide
//
// Created by Annie Tung on 2/18/17.
// Copyright © 2017 Madushani Lekam Wasam Liyanage. All rights reserved.
//
import Foundation
import UIKit
class TourCell: BaseCell {
static let identifier = "PageTourID"
let imageView: UIImageView = {
let image = UIImage(named: "Tourpage1")
let im = UIImageView(image: image)
im.translatesAutoresizingMaskIntoConstraints = false
im.alpha = 0.9
im.contentMode = .scaleAspectFill
im.clipsToBounds = true
return im
}()
let textView: UITextView = {
let view = UITextView()
view.text = "This is a textview"
view.isSelectable = false
view.isEditable = false
view.backgroundColor = UIColor.clear
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var tour: Tour? {
didSet {
guard let tourData = tour else { return }
setup(tour: tourData)
}
}
override func setupCell() {
super.setupCell()
addSubview(imageView)
addSubview(textView)
let _ = [
imageView.leftAnchor.constraint(equalTo: leftAnchor),
imageView.rightAnchor.constraint(equalTo: rightAnchor),
imageView.topAnchor.constraint(equalTo: topAnchor),
imageView.bottomAnchor.constraint(equalTo: bottomAnchor),
textView.leftAnchor.constraint(equalTo: leftAnchor),
textView.rightAnchor.constraint(equalTo: rightAnchor),
textView.topAnchor.constraint(equalTo: topAnchor, constant: 60),
textView.bottomAnchor.constraint(equalTo: bottomAnchor)
].map {$0.isActive = true}
}
private func setup(tour: Tour) {
imageView.image = tour.image
if let boldFont = UIFont(name: "Montserrat-Medium", size: 41), let regularFont = UIFont(name: "Montserrat-Light", size: 21) {
let shadow = NSShadow()
shadow.shadowColor = UIColor.darkGray
shadow.shadowOffset = CGSize(width: 1, height: 1)
shadow.shadowBlurRadius = 8
let attributedString = NSMutableAttributedString(string: tour.title, attributes: [NSForegroundColorAttributeName:UIColor.white, NSFontAttributeName:boldFont,NSShadowAttributeName:shadow])
let descriptionString = NSMutableAttributedString(string: "\n\n" + tour.description, attributes: [NSForegroundColorAttributeName:UIColor.white, NSFontAttributeName:regularFont, NSShadowAttributeName:shadow])
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let titleLength = attributedString.string.characters.count
let descriptionLength = descriptionString.string.characters.count
let titleRange = NSRange(location: 0, length: titleLength)
let descriptionRange = NSRange(location: 0, length: descriptionLength)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: titleRange)
descriptionString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: descriptionRange)
attributedString.append(descriptionString)
textView.attributedText = attributedString
} else {
print("Fonts were not found")
}
}
}
|
b723da264a3fde25e807608bf9a05fdd
| 38.370787 | 219 | 0.645548 | false | false | false | false |
Henawey/TheArabianCenter
|
refs/heads/master
|
TheArabianCenter/ShareInteractor.swift
|
mit
|
1
|
//
// ShareInteractor.swift
// TheArabianCenter
//
// Created by Ahmed Henawey on 2/23/17.
// Copyright (c) 2017 Ahmed Henawey. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
import CoreLocation
import RxSwift
import Result
protocol ShareInteractorInput
{
func shareOnFacebook(request: UI.Share.Request)
func shareOnTwitter(from viewController: UIViewController,request: UI.Share.Request)
func retrieve(request: UI.Sync.Retrieve.Request)
func retrieveImage(request: UI.Image.Download.Request)
var image: Variable<UIImage?> {get set}
var userLocation: CLLocation? {get set}
}
protocol ShareInteractorOutput
{
func presentShareSucceed(shareResponse:Share.Response)
func presentShareError(error: Share.Error)
func presentRetrieveSucceed(syncResponse:Sync.Response)
func presentRetrieveError(error: Sync.Error)
func presentRetrieveImageSucceed(response:Image.Download.Response)
func presentRetrieveImageError(error: UI.Image.Download.Error)
}
class ShareInteractor: ShareInteractorInput
{
var output: ShareInteractorOutput!
var worker: ShareWorker = ShareWorker()
// MARK: - Business logic
var cache: [Sync.Save.Request:Sync.Response] = [:]
var _image: Variable<UIImage?> = Variable(nil)
/// this is image captured by the camera in HomeViewController
var image: Variable<UIImage?> {
set{
_image = newValue
}
get{
return _image
}
}
var _userLocation: CLLocation?
/// this is user location captured by the CoreLocation in HomeViewController
var userLocation: CLLocation?{
set{
_userLocation = newValue
}
get{
return _userLocation
}
}
/// Save the data on firebase database for further use
/// and this will happen as following
///
/// 1.Check cache if request already proccesed
/// 2.Check if image is found then compress the image to save user bandwidth, otherwise error will be appread
/// 3. Upload Image for further user, Also it's required to share a link in Facebook SDK to be a network url.
/// 4. Save Request with link of the image.
/// - Parameter request: requried data to be saved
func save(request: Sync.Save.Request,attach image:UIImage? = nil,compilation:@escaping (Result<Sync.Response,Sync.Error>)->()) {
//Check cache if request already proccesed
if let response = cache[request] {
compilation(.success(response))
return
}
//Check if image is found then compress the image to save user bandwidth, otherwise error will be appread
guard let image = image,
let imageData = image.jpeg(.low) else {
compilation(.failure(Sync.Error.invalidData))
return
}
let syncWorker = SyncWorker()
// Upload Image for further user, Also it's required to share a link in Facebook SDK to be a network url
syncWorker.uploadImage (request: Image.Upload.Request(data: imageData)) { (result) in
switch result{
case let .success(response):
var request = request
request.imageLocation = response.url.absoluteString
//Save Request with link of the image
syncWorker.save(request: request, compilation: { (result) in
switch(result){
case let .success(id):
let response = Sync.Response(id: id, title: request.title, description: request.description, imageLocation: response.url.absoluteString)
//save request and response in cache
self.cache = [request:response]
compilation(.success(response))
case let .failure(error):
compilation(.failure(Sync.Error.failure(error: error)))
}
})
case let .failure(error):
compilation(.failure(Sync.Error.failure(error: error)))
}
}
}
/// Retrieve data by id from Firebase.
/// needed in DeepLinking.
/// - Parameter request: Retrieve request usually is offer id.
func retrieve(request: UI.Sync.Retrieve.Request){
guard let id = request.id else {
self.output.presentRetrieveError(error: Sync.Error.invalidData)
return
}
let syncWorker = SyncWorker()
syncWorker.retrieve(request: Sync.Retrieve.Request.init(id: id)) { (result) in
switch result{
case let .success(response):
self.output.presentRetrieveSucceed(syncResponse:response)
case let .failure(error):
self.output.presentRetrieveError(error: Sync.Error.failure(error: error))
}
}
}
func retrieveImage(request: UI.Image.Download.Request){
guard let imageLocation = request.imageLocation,
let imageURL = URL(string:imageLocation) else {
self.output.presentRetrieveImageError(error: UI.Image.Download.Error.invalidData)
return
}
let syncWorker = SyncWorker()
syncWorker.downloadImage(imageRequest: Image.Download.Request(url: imageURL), compilation: { (result) in
switch result{
case let .success(response):
self.output.presentRetrieveImageSucceed(response:response)
case let .failure(error):
self.output.presentRetrieveImageError(error: UI.Image.Download.Error.failure(error: error))
}
})
}
/// Share the offer on Twitter
///
/// - Parameters:
/// - viewController: Parent View Controller
/// - request: the data need to be shared
func shareOnTwitter(from viewController: UIViewController,request: UI.Share.Request){
guard let title = request.title,
let description = request.description,
let image = request.image else {
self.output.presentShareError(error: Share.Error.invalidData)
return
}
self.save(request: Sync.Save.Request(title: title, description: description, location: self.userLocation) ,attach: image) { (result) in
switch result{
case let .success(response):
self.worker.twitterShare(from: viewController, request: Share.Request(id: response.id, title: response.title, description: response.description, image: image)) { (result) in
switch result{
case let .success(shareResponse):
self.output.presentShareSucceed(shareResponse: shareResponse)
case let .failure(error):
self.output.presentShareError(error: error)
}
}
case let .failure(error):
self.output.presentShareError(error: Share.Error.failure(error: error))
break
}
}
}
/// Share the offer on Facebook
///
/// - Parameters:
/// - request: the data need to be shared
func shareOnFacebook(request: UI.Share.Request){
guard let title = request.title,
let description = request.description,
let image = request.image else {
self.output.presentShareError(error: Share.Error.invalidData)
return
}
self.save(request: Sync.Save.Request(title: title, description: description, location: self.userLocation), attach: image) { (result) in
switch result{
case let .success(response):
guard let imageURL = URL(string:response.imageLocation) else{
self.output.presentShareError(error: Share.Error.cannotUploadData)
return
}
self.worker.facebookShare(request: Share.Request(id: response.id, title: response.title, description: response.description,imageURL:imageURL)) { (result) in
switch result{
case let .success(shareResponse):
self.output.presentShareSucceed(shareResponse: shareResponse)
break
case let .failure(error):
self.output.presentShareError(error: error)
break
}
}
case let .failure(error):
self.output.presentShareError(error: Share.Error.failure(error: error))
break
}
}
}
}
|
676ff72418e4bdd2492aeab356dff02d
| 35.884921 | 189 | 0.576762 | false | false | false | false |
linkedin/LayoutKit
|
refs/heads/master
|
ExampleLayouts/HelloWorldAutoLayoutView.swift
|
apache-2.0
|
1
|
// Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
/**
A simple hello world layout that uses Auto Layout.
Compare to HelloWorldLayout.swift
*/
open class HelloWorldAutoLayoutView: UIView {
private lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.setContentHuggingPriority(UILayoutPriority.required, for: .vertical)
imageView.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal)
imageView.setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical)
imageView.setContentCompressionResistancePriority(UILayoutPriority.required, for: .horizontal)
imageView.image = UIImage(named: "earth.png")
return imageView
}()
private lazy var label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Hello World!"
return label
}()
public override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
addSubview(label)
let views: [String: UIView] = ["imageView": imageView, "label": label]
var constraints = [NSLayoutConstraint]()
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-4-[imageView(==50)]-4-|", options: [], metrics: nil, views: views))
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-4-[imageView(==50)]-4-[label]-8-|", options: [], metrics: nil, views: views))
constraints.append(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
NSLayoutConstraint.activate(constraints)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
dda642c3843ae94034b9e8aed8d9e18c
| 45.764706 | 170 | 0.71195 | false | false | false | false |
worchyld/FanDuelSample
|
refs/heads/master
|
FanDuelSample/FanDuelSample/FDMenuViewController.swift
|
gpl-3.0
|
1
|
//
// FDMenuViewController.swift
// FanDuelSample
//
// Created by Amarjit on 14/12/2016.
// Copyright © 2016 Amarjit. All rights reserved.
//
import UIKit
import GameplayKit
import SVProgressHUD
class FDMenuViewController: UIViewController {
var objects:[FDPlayer] = [FDPlayer]()
@IBOutlet weak var playButton: RoundedButton!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if (segue.identifier == "playSegue") {
let playVC: FDPlayGameViewController = segue.destination as! FDPlayGameViewController
playVC.objects = self.objects
}
}
@IBAction func buttonPressed(_ sender: Any) {
self.performSegue(withIdentifier: "playSegue", sender: self)
}
}
// MARK: - Functions
extension FDMenuViewController {
func setupUI() {
self.reloadData()
self.playButton.setTitle("Play", for: .normal)
self.playButton!.titleLabel?.font = UIFont(name: "Avenir", size: 40)!
self.playButton.layoutIfNeeded()
self.playButton.sizeToFit()
}
func reloadData() {
SVProgressHUD.show()
FDAPI.fetchPlayers({(success, error, playerObjects) -> Void in
SVProgressHUD.dismiss()
if (success) {
if let plyObjects = playerObjects {
self.objects = plyObjects
}
}
else {
print ("Error -- \(error?.localizedDescription as Any)")
}
})
}
}
|
c87c398fbcc160f9c71c49c411d9aceb
| 25.433735 | 106 | 0.628077 | false | false | false | false |
piscoTech/MBLibrary
|
refs/heads/master
|
MBLibrary iOS/FaqListTVC.swift
|
mit
|
1
|
//
// FaqListTableViewController.swift
// MBLibrary iOS
//
// Created by Marco Boschi on 07/08/18.
// Copyright © 2018 Marco Boschi. All rights reserved.
//
import UIKit
public class FaqListTableViewController: UITableViewController {
public var faqController: FAQController!
override public func viewDidLoad() {
super.viewDidLoad()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override public func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return faqController.FAQs.count
}
override public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "faq")!
let faqID = faqController.FAQs[indexPath.row]
cell.textLabel!.text = faqController.get(faqID)!.longTitle
cell.tag = faqController.tagForID(faqID)!
return cell
}
// MARK: - Navigation
override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showFAQ",
let faq = sender as? UITableViewCell,
let index = tableView.indexPath(for: faq) {
let dest = segue.destination as! ShowFaqViewController
dest.faqID = faqController.FAQs[index.row]
dest.faqController = faqController
}
}
}
|
212a99913b169c8b9e6185c7d028ee79
| 26.018519 | 113 | 0.742289 | false | false | false | false |
bitboylabs/selluv-ios
|
refs/heads/master
|
selluv-ios/selluv-ios/Classes/Base/Model/Manager/VersionModel.swift
|
mit
|
1
|
//
// VersionModel.swift
// selluv-ios
//
// Created by 조백근 on 2016. 11. 28..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
import SwiftyJSON
import ObjectMapper
import AlamofireObjectMapper
import RealmSwift
class VersionModel: NSObject {
let realm = try! Realm()
var items: [AnyObject]
let onGetData: Foundation.Notification = Foundation.Notification(name: NSNotification.Name(rawValue: "onGetData"), object: nil)
static let shared = VersionModel()
override init() {
self.items = []
super.init()
}
func getItems(_ term: String){
NotificationCenter.default.post(onGetData)
}
func detectRecvObjects(_ itemId: String) -> Version? {
var flag: Version?
for i in 0 ..< self.items.count {
let item = self.items[i] as? Version
if let piece = item {
if(piece.id == itemId) {
flag = piece
break
}
}
}
return flag
}
public func versionCheck(_ itemIds: [String]) -> [String: AnyObject]? {
// var add: [String] = []
var update: [String] = []
var skip: [String] = []
for (_, v) in itemIds.enumerated() {
let ver = self.detect(v)
if ver != nil {
let recv = self.detectRecvObjects(v)
let recvVersion = recv?.version ?? -1
let oldVersion = ver?.version ?? -1
if recvVersion > oldVersion {
update.append((ver?.name)!)
} else {
skip.append((ver?.name)!)
}
} else {
let recv = self.detectRecvObjects(v)
//add.append(v)
update.append((recv?.name)!)
}
}
return [/*"add": add as AnyObject,*/ "update": update as AnyObject, "skip": skip as AnyObject]
}
public func checkContain(_ itemIds: [String]) -> Bool {
let inText = itemIds.joined(separator: "\', \'")
let p = NSPredicate(format: "id in (\'%@\')", inText)
let list = realm.objects(Version.self).filter(p)
if list.count > 0 {
return true
} else {
return false
}
}
public func detect(_ itemId: String) -> Version? {
let p = NSPredicate(format: "id=%@", itemId)
let list = realm.objects(Version.self).filter(p)
if list.count > 0 {
return list.first
} else {
return nil
}
}
public func save(_ new: Version) {
try! realm.write {
realm.add(new, update: true)
self.getItems("")
}
}
func destroy(_ itemId: String) {
let p = NSPredicate(format: "id=%@", itemId)
let list = realm.objects(Version.self).filter(p)
if list.count > 0 {
try! realm.write {
realm.delete(list)
self.getItems("")
}
}
}
public func saveAllRecvObjects() {
if self.items.count == 0 {
return
}
try! realm.write {
realm.add(self.items as! [Version], update: true)
self.getItems("")
}
}
func versionCheck(updateBlock: @escaping (_ result: [String: AnyObject])->(), skipBlock: @escaping (_ result: [String: AnyObject])->()) {
LoadingIndicatorView.show("Loading")
BBProvider.sharedProvider.request(.version,
queue: networkQueue,
progress: progressClosure) { result in
LoadingIndicatorView.hide()
switch result {
case let .success(moyaResponse):
let resText = try? moyaResponse.mapString()
let data = moyaResponse.data // Data, your JSON response is probably in here!
let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etc
if let txt = resText {
let r: Response? = Response(JSONString: txt)
if r?.status == "success" {
let v: [Version] = Mapper<Version>().mapArray(JSONArray: r!.data! as! [[String : Any]])!
//항목별로 내려와서 소팅 필요없음
// let sort = v.sorted {
// $0.version < $1.version
// }
var all: [String] = []
_ = v.map() { all.append($0.id) }
self.items = v
let sorting = self.versionCheck(all)
//add, update, skip 이 내려오면 이중 add, update 만 처리하자.
updateBlock(sorting!)
skipBlock(sorting!)
self.saveAllRecvObjects()
}
}
break
case let .failure(error):
log.error("Error: \(error.localizedDescription)")
}
}
}
}
|
16453df92729c1824e0a53d857ac410d
| 32.452229 | 141 | 0.465727 | false | false | false | false |
jdkelley/Udacity-OnTheMap-ExampleApps
|
refs/heads/master
|
TheMovieManager-v1/TheMovieManager/MoviePickerViewController.swift
|
mit
|
1
|
//
// MoviePickerTableView.swift
// TheMovieManager
//
// Created by Jarrod Parkes on 2/11/15.
// Copyright (c) 2015 Jarrod Parkes. All rights reserved.
//
import UIKit
// MARK: - MoviePickerViewControllerDelegate
protocol MoviePickerViewControllerDelegate {
func moviePicker(moviePicker: MoviePickerViewController, didPickMovie movie: TMDBMovie?)
}
// MARK: - MoviePickerViewController: UIViewController
class MoviePickerViewController: UIViewController {
// MARK: Properties
// the data for the table
var movies = [TMDBMovie]()
// the delegate will typically be a view controller, waiting for the Movie Picker to return an movie
var delegate: MoviePickerViewControllerDelegate?
// the most recent data download task. We keep a reference to it so that it can be canceled every time the search text changes
var searchTask: NSURLSessionDataTask?
// MARK: Outlets
@IBOutlet weak var movieTableView: UITableView!
@IBOutlet weak var movieSearchBar: UISearchBar!
// MARK: Life Cycle
override func viewDidLoad() {
parentViewController!.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Reply, target: self, action: #selector(logout))
// configure tap recognizer
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(_:)))
tapRecognizer.numberOfTapsRequired = 1
tapRecognizer.delegate = self
view.addGestureRecognizer(tapRecognizer)
}
// MARK: Dismissals
func handleSingleTap(recognizer: UITapGestureRecognizer) {
view.endEditing(true)
}
private func cancel() {
delegate?.moviePicker(self, didPickMovie: nil)
logout()
}
func logout() {
dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK: - MoviePickerViewController: UIGestureRecognizerDelegate
extension MoviePickerViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
return movieSearchBar.isFirstResponder()
}
}
// MARK: - MoviePickerViewController: UISearchBarDelegate
extension MoviePickerViewController: UISearchBarDelegate {
// each time the search text changes we want to cancel any current download and start a new one
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
// cancel the last task
if let task = searchTask {
task.cancel()
}
// if the text is empty we are done
if searchText == "" {
movies = [TMDBMovie]()
movieTableView?.reloadData()
return
}
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
// MARK: - MoviePickerViewController: UITableViewDelegate, UITableViewDataSource
extension MoviePickerViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellReuseId = "MovieSearchCell"
let movie = movies[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(CellReuseId) as UITableViewCell!
if let releaseYear = movie.releaseYear {
cell.textLabel!.text = "\(movie.title) (\(releaseYear))"
} else {
cell.textLabel!.text = "\(movie.title)"
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let movie = movies[indexPath.row]
let controller = storyboard!.instantiateViewControllerWithIdentifier("MovieDetailViewController") as! MovieDetailViewController
controller.movie = movie
navigationController!.pushViewController(controller, animated: true)
}
}
|
507303d99a06899502759ebbe0771931
| 31.724409 | 150 | 0.688643 | false | false | false | false |
san2ride/TIY-Assignments
|
refs/heads/master
|
21/GitHubProApp/GitHubFriend.swift
|
mit
|
1
|
//
// GitHubFriend.swift
// GitHubProApp
//
// Created by don't touch me on 6/21/16.
// Copyright © 2016 trvl, LLC. All rights reserved.
//
import UIKit
class GitHubFriend: NSObject {
var username: String = ""
var gitID: Int = 0
var avatarURL: String = ""
var followersURL: String = ""
var followingURL: String = ""
var email: String = ""
var publicRepos: Int = 0
var publicGists: Int = 0
var createdAT = NSDate()
init(jsonDict: JSONDictionary) {
if let username = jsonDict["username"] as? String {
self.username = username
} else {
print("i could not parse the username")
}
if let gitID = jsonDict["id"] as? Int {
self.gitID = gitID
} else {
print("i could not parse the id")
}
if let avatarURL = jsonDict["avatar_url"] as? String {
self.avatarURL = avatarURL
} else {
print("i could not parse the avatar_url")
}
if let followersURL = jsonDict["followers_url"] as? String {
self.followersURL = followersURL
} else {
print("i could not parse the username")
}
if let followingURL = jsonDict["following_url"] as? String {
self.followingURL = followingURL
} else {
print("i could not parse the following_url")
}
if let email = jsonDict["email"] as? String {
self.email = email
} else {
print("i could not parse the email")
}
if let publicRepos = jsonDict["public_repos"] as? Int {
self.publicRepos = publicRepos
} else {
print("i could not parse the public_repos")
}
if let publicGists = jsonDict["public_gists"] as? Int {
self.publicGists = publicGists
} else {
print("i could not parse the public_gists")
}
if let createdAT = jsonDict["created_at"] as? String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
self.createdAT = dateFormatter.dateFromString(createdAT)!
} else {
print("i could not parse the created_at")
}
}
}
|
e909bf1c9b6078166ababbf2b889a02d
| 25.516484 | 69 | 0.521757 | false | false | false | false |
CodaFi/swift
|
refs/heads/main
|
test/Sema/diag_unowned_immediate_deallocation.swift
|
apache-2.0
|
15
|
// RUN: %target-typecheck-verify-swift -module-name ModuleName
protocol ClassProtocol : class {
init()
init?(failable: Void)
init(throwing: Void) throws
}
class C : ClassProtocol {
required init() {}
required init?(failable: Void) {}
required init(throwing: Void) throws {}
}
class D : C {}
func testWeakVariableBindingDiag() throws {
weak var c1 = C() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
c1 = C() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c2: C? = ModuleName.C() // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c2' declared here}}
// expected-note@-3 {{'c2' declared here}}
c2 = C() // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c3: C? = D() // expected-warning {{instance will be immediately deallocated because variable 'c3' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c3' declared here}}
// expected-note@-3 {{'c3' declared here}}
c3 = D() // expected-warning {{instance will be immediately deallocated because variable 'c3' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c4 = C(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c4' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c4' declared here}}
// expected-note@-3 {{'c4' declared here}}
c4 = C(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c4' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c5: C? = C(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c5' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c5' declared here}}
// expected-note@-3 {{'c5' declared here}}
c5 = C(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c5' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c6: C? = D(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c6' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c6' declared here}}
// expected-note@-3 {{'c6' declared here}}
c6 = D(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c6' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c7 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c7' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c7' declared here}}
// expected-note@-3 {{'c7' declared here}}
c7 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c7' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c8: C? = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c8' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c8' declared here}}
// expected-note@-3 {{'c8' declared here}}
c8 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c8' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c9: C? = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c9' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c9' declared here}}
// expected-note@-3 {{'c9' declared here}}
c9 = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c9' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c10 = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c10' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c10' declared here}}
// expected-note@-3 {{'c10' declared here}}
c10 = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c10' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c11: C? = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c11' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c11' declared here}}
// expected-note@-3 {{'c11' declared here}}
c11 = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c11' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c12: C? = try! D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c12' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c12' declared here}}
// expected-note@-3 {{'c12' declared here}}
c12 = try! D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c12' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c13 = try? C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c13' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c13' declared here}}
// expected-note@-3 {{'c13' declared here}}
c13 = try? C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c13' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c14: C? = try? C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c14' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c14' declared here}}
// expected-note@-3 {{'c14' declared here}}
c14 = try? C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c14' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
weak var c15: C? = try? D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c15' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c15' declared here}}
// expected-note@-3 {{'c15' declared here}}
c15 = try? D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c15' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
_ = c1; _ = c2; _ = c3; _ = c4; _ = c5; _ = c6; _ = c7; _ = c8; _ = c9; _ = c10; _ = c11; _ = c12; _ = c13; _ = c14; _ = c15
}
func testUnownedVariableBindingDiag() throws {
unowned(unsafe) var c = C() // expected-warning {{instance will be immediately deallocated because variable 'c' is 'unowned(unsafe)'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c' declared here}}
// expected-note@-3 {{'c' declared here}}
c = C() // expected-warning {{instance will be immediately deallocated because variable 'c' is 'unowned(unsafe)'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c1 = C() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
c1 = C() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c2: C = ModuleName.C() // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c2' declared here}}
// expected-note@-3 {{'c2' declared here}}
c2 = C() // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c3: C = D() // expected-warning {{instance will be immediately deallocated because variable 'c3' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c3' declared here}}
// expected-note@-3 {{'c3' declared here}}
c3 = D() // expected-warning {{instance will be immediately deallocated because variable 'c3' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c4 = C(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c4' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c4' declared here}}
// expected-note@-3 {{'c4' declared here}}
c4 = C(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c4' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c5: C = C(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c5' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c5' declared here}}
// expected-note@-3 {{'c5' declared here}}
c5 = C(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c5' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c6: C = D(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c6' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c6' declared here}}
// expected-note@-3 {{'c6' declared here}}
c6 = D(failable: ())! // expected-warning {{instance will be immediately deallocated because variable 'c6' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c7 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c7' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c7' declared here}}
// expected-note@-3 {{'c7' declared here}}
c7 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c7' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c8: C = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c8' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c8' declared here}}
// expected-note@-3 {{'c8' declared here}}
c8 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c8' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c9: C = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c9' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c9' declared here}}
// expected-note@-3 {{'c9' declared here}}
c9 = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c9' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c10 = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c10' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c10' declared here}}
// expected-note@-3 {{'c10' declared here}}
c10 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c10' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c11: C = try! C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c11' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c11' declared here}}
// expected-note@-3 {{'c11' declared here}}
c11 = try C(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c11' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c12: C = try! D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c12' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c12' declared here}}
// expected-note@-3 {{'c12' declared here}}
c12 = try D(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 'c12' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c13 = (try? C(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c13' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c13' declared here}}
// expected-note@-3 {{'c13' declared here}}
c13 = (try? C(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c13' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c14: C = (try? C(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c14' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c14' declared here}}
// expected-note@-3 {{'c14' declared here}}
c14 = (try? C(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c14' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var c15: C = (try? D(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c15' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c15' declared here}}
// expected-note@-3 {{'c15' declared here}}
c15 = (try? D(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 'c15' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
_ = c; _ = c1; _ = c2; _ = c3; _ = c4; _ = c5; _ = c6; _ = c7; _ = c8; _ = c9; _ = c10; _ = c11; _ = c12; _ = c13; _ = c14; _ = c15
}
func testMultipleBindingDiag() {
weak var c1 = C(), c2: C? = C(), c3: C? = D()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c1' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c2' declared here}}
// expected-warning@-7 {{instance will be immediately deallocated because variable 'c3' is 'weak'}}
// expected-note@-8 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-9 {{'c3' declared here}}
unowned let c4 = C(), c5: C = C(), c6: C = D()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c4' is 'unowned'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c4' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c5' is 'unowned'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c5' declared here}}
// expected-warning@-7 {{instance will be immediately deallocated because variable 'c6' is 'unowned'}}
// expected-note@-8 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-9 {{'c6' declared here}}
_ = c1; _ = c2; _ = c3; _ = c4; _ = c5; _ = c6
}
func testTupleAndParenBinding() throws {
weak var ((c1), c2, c3): (C?, C?, C?) = (C() as C, (D()), try D(throwing: ()))
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c1' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c2' declared here}}
// expected-warning@-7 {{instance will be immediately deallocated because variable 'c3' is 'weak'}}
// expected-note@-8 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-9 {{'c3' declared here}}
unowned let ((c4), c5, c6): (C, C, C) = (C() as C, (D()), try D(throwing: ()))
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c4' is 'unowned'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c4' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c5' is 'unowned'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c5' declared here}}
// expected-warning@-7 {{instance will be immediately deallocated because variable 'c6' is 'unowned'}}
// expected-note@-8 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-9 {{'c6' declared here}}
_ = c1; _ = c2; _ = c3; _ = c4; _ = c5; _ = c6
}
func testInitializationThroughClassArchetypeDiag<T : ClassProtocol>(_ t: T, _ p: ClassProtocol) throws {
weak var t1: T? = T() // expected-warning {{instance will be immediately deallocated because variable 't1' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t1' declared here}}
weak var t2: ClassProtocol? = T(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 't2' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t2' declared here}}
unowned let t3 = try type(of: t).init(throwing: ()) // expected-warning {{instance will be immediately deallocated because variable 't3' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t3' declared here}}
unowned(unsafe) let t4 = type(of: p).init() // expected-warning {{instance will be immediately deallocated because variable 't4' is 'unowned(unsafe)'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t4' declared here}}
let optionalTType: T.Type? = T.self
let optionalPType: ClassProtocol.Type? = type(of: p)
weak var t5 = optionalTType?.init(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 't5' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t5' declared here}}
unowned(unsafe) let t6 = try (optionalPType?.init(throwing: ()))! // expected-warning {{instance will be immediately deallocated because variable 't6' is 'unowned(unsafe)'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'t6' declared here}}
_ = t1; _ = t2; _ = t3; _ = t4; _ = t5; _ = t6
}
weak var topLevelC = C() // expected-warning {{instance will be immediately deallocated because variable 'topLevelC' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'topLevelC' declared here}}
// expected-note@-3 {{'topLevelC' declared here}}
topLevelC = C() // expected-warning {{instance will be immediately deallocated because variable 'topLevelC' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned var topLevelC1 = C() // expected-warning {{instance will be immediately deallocated because variable 'topLevelC1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'topLevelC1' declared here}}
// expected-note@-3 {{'topLevelC1' declared here}}
topLevelC1 = C() // expected-warning {{instance will be immediately deallocated because variable 'topLevelC1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
struct S {
weak var c: C? // expected-note {{'c' declared here}}
unowned var c1 = C() // expected-warning {{instance will be immediately deallocated because property 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
mutating func foo() {
c = D() // expected-warning {{instance will be immediately deallocated because property 'c' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
c1 = D() // expected-warning {{instance will be immediately deallocated because property 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
}
}
class C1 {
weak var c: C? // expected-note {{'c' declared here}}
unowned var c1 = C() // expected-warning {{instance will be immediately deallocated because property 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
func foo() {
c = D() // expected-warning {{instance will be immediately deallocated because property 'c' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
c1 = D() // expected-warning {{instance will be immediately deallocated because property 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
}
}
func testInitializationThroughMetaclassDiag(_ t: C.Type) {
weak var c1: C? = t.init() // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
let optionaCType: C.Type? = t
weak var c2 = optionaCType?.init(failable: ()) // expected-warning {{instance will be immediately deallocated because variable 'c2' is 'weak'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c2' declared here}}
_ = c1; _ = c2
}
func testInitializationThroughTupleElementDiag() {
unowned var c1 = ((C() as C, C() as C) as (C, C)).0 // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-2 {{'c1' declared here}}
// expected-note@-3 {{'c1' declared here}}
c1 = ((C() as C, C() as C) as (C, C)).0 // expected-warning {{instance will be immediately deallocated because variable 'c1' is 'unowned'}}
// expected-note@-1 {{a strong reference is required to prevent the instance from being deallocated}}
unowned let (c2, c3) = ((C() as C, C()) as (C, C), 5).0
// expected-warning@-1 {{instance will be immediately deallocated because variable 'c2' is 'unowned'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'c2' declared here}}
// expected-warning@-4 {{instance will be immediately deallocated because variable 'c3' is 'unowned'}}
// expected-note@-5 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-6 {{'c3' declared here}}
_ = c1; _ = c2; _ = c3
}
class E<T> {}
func testGenericWeakClassDiag() {
weak var e = E<String>()
// expected-warning@-1 {{instance will be immediately deallocated because variable 'e' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'e' declared here}}
_ = e
}
// The diagnostic doesn't currently support tuple shuffles.
func testDontDiagnoseThroughTupleShuffles() {
unowned let (c1, (c2, c3)): (c: C, (b: C, a: C)) = ((a: D(), b: C()), c: D())
// expected-warning@-1 {{expression shuffles the elements of this tuple; this behavior is deprecated}}
// expected-warning@-2 {{expression shuffles the elements of this tuple; this behavior is deprecated}}
unowned let c4 = ((a: C(), b: C()) as (b: C, a: C)).0
// expected-warning@-1 {{expression shuffles the elements of this tuple; this behavior is deprecated}}
_ = c1; _ = c2; _ = c3; _ = c4
}
extension Optional {
init(dontDiagnoseOnThis: Void) {
self = nil
}
}
func testDontDiagnoseOnUnrelatedInitializer() {
weak var c = C?(dontDiagnoseOnThis: ())
unowned let c1 = C?(dontDiagnoseOnThis: ())!
_ = c; _ = c1
}
class F {
var c: C?
func makeC() -> C { return C() }
}
func testDontDiagnoseThroughMembers() {
weak var c1 = F().c
weak var c2 = F().makeC()
_ = c1; _ = c2
}
func testDontDiagnoseOnStrongVariable() {
var c1 = C()
c1 = C()
_ = c1
}
func testDontDiagnoseThroughImmediatelyEvaluatedClosure() {
weak var c1 = { C() }()
unowned let c2 = { C() }()
_ = c1; _ = c2
}
|
fa40be0ea9dc3c77e6c999bf13e4da90
| 59.169355 | 175 | 0.698767 | false | false | false | false |
Hypercubesoft/HCFramework
|
refs/heads/master
|
HCFramework/Managers/HCDispatcher.swift
|
mit
|
1
|
//
// HCDispatcher.swift
//
// Created by Hypercube on 6/12/17.
// Copyright © 2017 Hypercube. All rights reserved.
//
import Foundation
/// HCDispatcher class which handles number of tasks which are in progress in order to perform some operation when all tasks are finished.
open class HCDispatcher: NSObject {
/// Number of tasks which are in progress.
open var tasksToFinish: Int = 0
/// Completion handler, i.e. operation which has to be performed when all tasks are finished (when tasksToFinish = 0)
open var completionHandler: () -> Void = {}
/// Method for setting completion handler.
///
/// - Parameter handler: Operation which has to be performed when all tasks are finished.
open func setCompletitionHandler(handler: @escaping () -> Void)
{
completionHandler = handler
}
/// Signal that a task has started.
open func startTask()
{
tasksToFinish += 1
}
/// Signal that a task is done and to check if all tasks are done.
open func endTask()
{
tasksToFinish -= 1
checkIfAllTasksDone()
}
/// Check if all tasks are done. If it is true, then completion handler is performed.
open func checkIfAllTasksDone()
{
if tasksToFinish == 0
{
completionHandler()
} else if tasksToFinish < 0
{
print("***************************************************************** tasksToFinish NEGATIVE *****************************************************************")
}
}
}
|
cc52d0cbd5b903b636a9f059531e34c4
| 28.811321 | 175 | 0.574684 | false | false | false | false |
drinkapoint/DrinkPoint-iOS
|
refs/heads/master
|
DrinkPoint/DrinkPoint/Games/Epigram/AboutViewController.swift
|
mit
|
1
|
//
// AboutViewController.swift
// DrinkPoint
//
// Created by Paul Kirk Adams on 7/28/16.
// Copyright © 2016 Paul Kirk Adams. All rights reserved.
//
import UIKit
import Crashlytics
import TwitterKit
import DigitsKit
class AboutViewController: UIViewController {
@IBOutlet weak var signOutButton: UIButton!
var logoView: UIImageView!
override func prefersStatusBarHidden() -> Bool {
return true
}
override func viewDidLoad() {
let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
navigationController?.navigationBar.titleTextAttributes = titleDict as? [String: AnyObject]
navigationController?.navigationBar.tintColor = UIColor.whiteColor()
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
navigationController?.navigationBar.shadowImage = UIImage()
Answers.logCustomEventWithName("Viewed About Epigram", customAttributes: nil)
}
@IBAction func dismiss(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func learnMore(sender: AnyObject) {
SafariHandling.presentSafariVC(NSURL(string: "http://drinkpoint.pkadams67.io")!)
}
@IBAction func signOut(sender: AnyObject) {
let sessionStore = Twitter.sharedInstance().sessionStore
if let userId = sessionStore.session()?.userID {
sessionStore.logOutUserID(userId)
}
Digits.sharedInstance().logOut()
Crashlytics.sharedInstance().setUserIdentifier(nil)
Crashlytics.sharedInstance().setUserName(nil)
Answers.logCustomEventWithName("Signed Out", customAttributes: nil)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let signInViewController: UIViewController! = storyboard.instantiateViewControllerWithIdentifier("SignInViewController")
presentViewController(signInViewController, animated: true, completion: nil)
}
}
|
09304411c2d2377af03aea818fe4c9d0
| 36.867925 | 129 | 0.722333 | false | false | false | false |
imzyf/99-projects-of-swift
|
refs/heads/master
|
016-moya-simple/016-moya-simple/DouBan.swift
|
mit
|
1
|
//
// DouBan.swift
// 016-moya-simple
//
// Created by moma on 2017/11/2.
// Copyright © 2017年 yifans. All rights reserved.
//
import Moya
let DouBanProvider = MoyaProvider<DouBan>()
// 请求分类
public enum DouBan {
case channels //获取频道列表
case playlist(channel: String) //获取歌曲
}
//请求配置
extension DouBan: TargetType {
// 服务器地址
public var baseURL: URL {
switch self {
case .channels:
return URL(string: "https://www.douban.com")!
case .playlist(_):
return URL(string: "https://douban.fm")!
}
}
//各个请求的具体路径
// https://www.douban.com/j/app/radio/channels
// https://douban.fm/j/mine/playlist?channel=3&type=n&from=mainsite
public var path: String {
switch self {
case .channels:
return "/j/app/radio/channels"
default:
return "/j/mine/playlist"
}
}
public var method: Moya.Method {
return .get
}
//请求任务事件(这里附带上参数)
public var task: Task {
switch self {
case .playlist(let channel):
var params: [String: Any] = [:]
params["channel"] = channel
params["type"] = "n"
params["from"] = "mainsite"
return .requestParameters(parameters: params,
encoding: URLEncoding.default)
default:
return .requestPlain
}
}
//是否执行Alamofire验证
public var validate: Bool {
return false
}
//这个就是做单元测试模拟的数据,只会在单元测试文件中有作用
public var sampleData: Data {
return "{}".data(using: String.Encoding.utf8)!
}
//请求头
public var headers: [String: String]? {
return nil
}
}
|
01e99deff82fb9090eb7994615af9b2d
| 21.316456 | 71 | 0.538287 | false | false | false | false |
Petrachkov/SPSwiftExtensions
|
refs/heads/master
|
SPSwiftExtensions/Classes/String+.swift
|
mit
|
1
|
//
// UIImage+.swift
// JustTaxi
//
// Created by sergey petrachkov on 30/08/16.
// Copyright © 2016 actonica. All rights reserved.
//
import Foundation
public extension UIImage{
/**
@brief This method should merge two images if possible or return bottom image without changes or nil
@discussion This method accepts two strings that represent names of images
@param bottomImageName - main image that should be a basement of a new merged image
@param topImageName - name of a top image
@param topOffset - offset
*/
class func getMergedImage(_ bottomImageName: String, topImageName: String, topOffset : CGFloat = 3) -> UIImage? {
let bottomImage = UIImage(named: bottomImageName)
let topImage = UIImage(named: topImageName)
if (bottomImage == nil) {
return nil;
}
else if (topImage == nil) {
return bottomImage;
}
let size = CGSize(width: bottomImage!.size.width, height: bottomImage!.size.height)
UIGraphicsBeginImageContext(size)
let areaSize = CGRect(x: 0, y: 0, width: size.width, height: size.height)
bottomImage!.draw(in: areaSize)
topImage!.draw(in: CGRect(x: (bottomImage!.size.width - topImage!.size.width) / 2, y: topOffset, width: topImage!.size.width, height: topImage!.size.height), blendMode: CGBlendMode.normal, alpha: 0.8)
let mergedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return mergedImage;
}
/**
@brief This method should merge two images
@discussion This method accepts two UIImage instances
@param bottomImage - main image that should be a basement of a new merged image
@param topImage - a top image
@param topOffset - offset
*/
class func getMergedImage(_ bottomImage: UIImage, topImage: UIImage, topOffset : CGFloat = 3) -> UIImage? {
var mergedImage : UIImage? = nil;
let size = CGSize(width: bottomImage.size.width, height: bottomImage.size.height)
UIGraphicsBeginImageContext(size)
let areaSize = CGRect(x: 0, y: 0, width: size.width, height: size.height)
bottomImage.draw(in: areaSize)
topImage.draw(in: CGRect(x: (bottomImage.size.width - topImage.size.width) / 2, y: topOffset, width: topImage.size.width, height: topImage.size.height), blendMode: CGBlendMode.normal, alpha: 0.8)
mergedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return mergedImage;
}
class func getMergedMarcoPin(_ bottomImage: UIImage, topImage: UIImage, topOffset : CGFloat = 3.5) -> UIImage? {
let imageSize = bottomImage.size.width - topOffset*2;
var mergedImage : UIImage? = nil;
let size = CGSize(width: bottomImage.size.width, height: bottomImage.size.height)
UIGraphicsBeginImageContext(size)
let areaSize = CGRect(x: 0, y: 0, width: size.width, height: size.height)
bottomImage.draw(in: areaSize)
//TODO: figure out +0.5 magic number
topImage.getRoundedImage(imageSize/2, imageSize: CGSize(width: imageSize, height: imageSize)).draw(in: CGRect(x: topOffset + 0.5, y: topOffset, width: imageSize, height: imageSize), blendMode: CGBlendMode.normal, alpha: 1)
mergedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return mergedImage;
}
func getRoundedImage(_ cornerRadius: CGFloat, imageSize : CGSize) -> UIImage{
// Get your image somehow
var image = self;
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale);
// Add a clip before drawing anything, in the shape of an rounded rect
UIBezierPath(roundedRect: CGRect(origin: CGPoint(x: 0, y: 0), size: imageSize), cornerRadius: cornerRadius).addClip();
// Draw your image
image.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: imageSize))
// Get the image, here setting the UIImageView image
image = UIGraphicsGetImageFromCurrentImageContext()!;
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
return image;
}
}
|
4a06ac021ce485e84b4561bbc434cb62
| 41.073684 | 224 | 0.741056 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
refs/heads/main
|
Swift/score-of-parentheses.swift
|
mit
|
2
|
/**
* https://leetcode.com/problems/score-of-parentheses/
*
*
*/
// Date: Wed Feb 24 10:46:08 PST 2021
class Solution {
func scoreOfParentheses(_ S: String) -> Int {
var stack: [Int] = [0]
for c in S {
if String(c) == "(" {
stack.append(0)
} else {
let last = stack.removeLast()
let score = stack.removeLast() + max(2 * last, 1)
stack.append(score)
}
}
return stack.removeLast()
}
}
/**
* https://leetcode.com/problems/score-of-parentheses/
*
*
*/
// Date: Wed Feb 24 10:50:53 PST 2021
class Solution {
func scoreOfParentheses(_ S: String) -> Int {
var depth = 0
var result = 0
let S = Array(S)
for index in 0 ..< S.count {
if S[index] == Character("(") {
depth += 1
} else {
depth -= 1
if S[index - 1] == Character("(") {
result += 1 << depth
}
}
}
return result
}
}
|
155a9140935ad17a5ddd729153089c34
| 22.891304 | 65 | 0.437158 | false | false | false | false |
crazypoo/PTools
|
refs/heads/master
|
PhoneNumberKit/MetadataParsing.swift
|
mit
|
2
|
//
// MetadataParsing.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 2019-02-10.
// Copyright © 2019 Roy Marmelstein. All rights reserved.
//
import Foundation
// MARK: - MetadataTerritory
public extension MetadataTerritory {
enum CodingKeys: String, CodingKey {
case codeID = "id"
case countryCode
case internationalPrefix
case mainCountryForCode
case nationalPrefix
case nationalPrefixFormattingRule
case nationalPrefixForParsing
case nationalPrefixTransformRule
case preferredExtnPrefix
case emergency
case fixedLine
case generalDesc
case mobile
case pager
case personalNumber
case premiumRate
case sharedCost
case tollFree
case voicemail
case voip
case uan
case numberFormats = "numberFormat"
case leadingDigits
case availableFormats
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// Custom parsing logic
codeID = try container.decode(String.self, forKey: .codeID)
let code = try! container.decode(String.self, forKey: .countryCode)
countryCode = UInt64(code)!
mainCountryForCode = container.decodeBoolString(forKey: .mainCountryForCode)
let possibleNationalPrefixForParsing: String? = try container.decodeIfPresent(String.self, forKey: .nationalPrefixForParsing)
let possibleNationalPrefix: String? = try container.decodeIfPresent(String.self, forKey: .nationalPrefix)
nationalPrefix = possibleNationalPrefix
nationalPrefixForParsing = (possibleNationalPrefixForParsing == nil && possibleNationalPrefix != nil) ? nationalPrefix : possibleNationalPrefixForParsing
nationalPrefixFormattingRule = try container.decodeIfPresent(String.self, forKey: .nationalPrefixFormattingRule)
let availableFormats = try? container.nestedContainer(keyedBy: CodingKeys.self, forKey: .availableFormats)
let temporaryFormatList: [MetadataPhoneNumberFormat] = availableFormats?.decodeArrayOrObject(forKey: .numberFormats) ?? [MetadataPhoneNumberFormat]()
numberFormats = temporaryFormatList.withDefaultNationalPrefixFormattingRule(nationalPrefixFormattingRule)
// Default parsing logic
internationalPrefix = try container.decodeIfPresent(String.self, forKey: .internationalPrefix)
nationalPrefixTransformRule = try container.decodeIfPresent(String.self, forKey: .nationalPrefixTransformRule)
preferredExtnPrefix = try container.decodeIfPresent(String.self, forKey: .preferredExtnPrefix)
emergency = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .emergency)
fixedLine = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .fixedLine)
generalDesc = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .generalDesc)
mobile = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .mobile)
pager = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .pager)
personalNumber = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .personalNumber)
premiumRate = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .premiumRate)
sharedCost = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .sharedCost)
tollFree = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .tollFree)
voicemail = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .voicemail)
voip = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .voip)
uan = try container.decodeIfPresent(MetadataPhoneNumberDesc.self, forKey: .uan)
leadingDigits = try container.decodeIfPresent(String.self, forKey: .leadingDigits)
}
}
// MARK: - MetadataPhoneNumberFormat
public extension MetadataPhoneNumberFormat {
enum CodingKeys: String, CodingKey {
case pattern
case format
case intlFormat
case leadingDigitsPatterns = "leadingDigits"
case nationalPrefixFormattingRule
case nationalPrefixOptionalWhenFormatting
case domesticCarrierCodeFormattingRule = "carrierCodeFormattingRule"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// Custom parsing logic
leadingDigitsPatterns = container.decodeArrayOrObject(forKey: .leadingDigitsPatterns)
nationalPrefixOptionalWhenFormatting = container.decodeBoolString(forKey: .nationalPrefixOptionalWhenFormatting)
// Default parsing logic
pattern = try container.decodeIfPresent(String.self, forKey: .pattern)
format = try container.decodeIfPresent(String.self, forKey: .format)
intlFormat = try container.decodeIfPresent(String.self, forKey: .intlFormat)
nationalPrefixFormattingRule = try container.decodeIfPresent(String.self, forKey: .nationalPrefixFormattingRule)
domesticCarrierCodeFormattingRule = try container.decodeIfPresent(String.self, forKey: .domesticCarrierCodeFormattingRule)
}
}
// MARK: - PhoneNumberMetadata
extension PhoneNumberMetadata {
enum CodingKeys: String, CodingKey {
case phoneNumberMetadata
case territories
case territory
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let metadataObject = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .phoneNumberMetadata)
let territoryObject = try metadataObject.nestedContainer(keyedBy: CodingKeys.self, forKey: .territories)
territories = try territoryObject.decode([MetadataTerritory].self, forKey: .territory)
}
}
// MARK: - Parsing helpers
private extension KeyedDecodingContainer where K: CodingKey {
/// Decodes a string to a boolean. Returns false if empty.
///
/// - Parameter key: Coding key to decode
func decodeBoolString(forKey key: KeyedDecodingContainer<K>.Key) -> Bool {
guard let value: String = try? self.decode(String.self, forKey: key) else {
return false
}
return Bool(value) ?? false
}
/// Decodes either a single object or an array into an array. Returns an empty array if empty.
///
/// - Parameter key: Coding key to decode
func decodeArrayOrObject<T: Decodable>(forKey key: KeyedDecodingContainer<K>.Key) -> [T] {
guard let array: [T] = try? self.decode([T].self, forKey: key) else {
guard let object: T = try? self.decode(T.self, forKey: key) else {
return [T]()
}
return [object]
}
return array
}
}
private extension Collection where Element == MetadataPhoneNumberFormat {
func withDefaultNationalPrefixFormattingRule(_ nationalPrefixFormattingRule: String?) -> [Element] {
return self.map { format -> MetadataPhoneNumberFormat in
var modifiedFormat = format
if modifiedFormat.nationalPrefixFormattingRule == nil {
modifiedFormat.nationalPrefixFormattingRule = nationalPrefixFormattingRule
}
return modifiedFormat
}
}
}
|
d10ce071e4564b2f1a32b07391eeb85a
| 44.993789 | 161 | 0.719244 | false | false | false | false |
ArnavChawla/InteliChat
|
refs/heads/master
|
Pods/PopupDialog/PopupDialog/Classes/PopupDialog.swift
|
apache-2.0
|
3
|
//
// PopupDialog.swift
//
// Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk)
// Author - Martin Wildfeuer (http://www.mwfire.de)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
/// Creates a Popup dialog similar to UIAlertController
final public class PopupDialog: UIViewController {
// MARK: Private / Internal
/// First init flag
fileprivate var initialized = false
/// The completion handler
fileprivate var completion: (() -> Void)? = nil
/// The custom transition presentation manager
fileprivate var presentationManager: PresentationManager!
/// Interactor class for pan gesture dismissal
fileprivate lazy var interactor: InteractiveTransition = {
return InteractiveTransition()
}()
/// Returns the controllers view
internal var popupContainerView: PopupDialogContainerView {
return view as! PopupDialogContainerView
}
/// The set of buttons
fileprivate var buttons = [PopupDialogButton]()
/// Whether keyboard has shifted view
internal var keyboardShown = false
/// Keyboard height
internal var keyboardHeight: CGFloat? = nil
// MARK: Public
/// The content view of the popup dialog
public var viewController: UIViewController
/// Whether or not to shift view for keyboard display
public var keyboardShiftsView = true
// MARK: - Initializers
/*!
Creates a standard popup dialog with title, message and image field
- parameter title: The dialog title
- parameter message: The dialog message
- parameter image: The dialog image
- parameter buttonAlignment: The dialog button alignment
- parameter transitionStyle: The dialog transition style
- parameter gestureDismissal: Indicates if dialog can be dismissed via pan gesture
- parameter completion: Completion block invoked when dialog was dismissed
- returns: Popup dialog default style
*/
public convenience init(
title: String?,
message: String?,
image: UIImage? = nil,
buttonAlignment: UILayoutConstraintAxis = .vertical,
transitionStyle: PopupDialogTransitionStyle = .bounceUp,
gestureDismissal: Bool = true,
completion: (() -> Void)? = nil) {
// Create and configure the standard popup dialog view
let viewController = PopupDialogDefaultViewController()
viewController.titleText = title
viewController.messageText = message
viewController.image = image
// Call designated initializer
self.init(viewController: viewController, buttonAlignment: buttonAlignment, transitionStyle: transitionStyle, gestureDismissal: gestureDismissal, completion: completion)
}
/*!
Creates a popup dialog containing a custom view
- parameter viewController: A custom view controller to be displayed
- parameter buttonAlignment: The dialog button alignment
- parameter transitionStyle: The dialog transition style
- parameter gestureDismissal: Indicates if dialog can be dismissed via pan gesture
- parameter completion: Completion block invoked when dialog was dismissed
- returns: Popup dialog with a custom view controller
*/
public init(
viewController: UIViewController,
buttonAlignment: UILayoutConstraintAxis = .vertical,
transitionStyle: PopupDialogTransitionStyle = .bounceUp,
gestureDismissal: Bool = true,
completion: (() -> Void)? = nil) {
self.viewController = viewController
self.completion = completion
super.init(nibName: nil, bundle: nil)
// Init the presentation manager
presentationManager = PresentationManager(transitionStyle: transitionStyle, interactor: interactor)
// Assign the interactor view controller
interactor.viewController = self
// Define presentation styles
transitioningDelegate = presentationManager
modalPresentationStyle = .custom
// Add our custom view to the container
popupContainerView.stackView.insertArrangedSubview(viewController.view, at: 0)
// Set button alignment
popupContainerView.buttonStackView.axis = buttonAlignment
// Allow for dialog dismissal on background tap and dialog pan gesture
if gestureDismissal {
let panRecognizer = UIPanGestureRecognizer(target: interactor, action: #selector(InteractiveTransition.handlePan))
popupContainerView.stackView.addGestureRecognizer(panRecognizer)
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
popupContainerView.addGestureRecognizer(tapRecognizer)
}
}
// Init with coder not implemented
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View life cycle
/// Replaces controller view with popup view
public override func loadView() {
view = PopupDialogContainerView(frame: UIScreen.main.bounds)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard !initialized else { return }
appendButtons()
addObservers()
initialized = true
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeObservers()
}
deinit {
completion?()
completion = nil
}
// MARK - Dismissal related
@objc fileprivate func handleTap(_ sender: UITapGestureRecognizer) {
// Make sure it's not a tap on the dialog but the background
let point = sender.location(in: popupContainerView.stackView)
guard !popupContainerView.stackView.point(inside: point, with: nil) else { return }
dismiss()
}
/*!
Dismisses the popup dialog
*/
public func dismiss(_ completion: (() -> Void)? = nil) {
self.dismiss(animated: true) {
completion?()
}
}
// MARK: - Button related
/*!
Appends the buttons added to the popup dialog
to the placeholder stack view
*/
fileprivate func appendButtons() {
// Add action to buttons
if buttons.isEmpty {
popupContainerView.stackView.removeArrangedSubview(popupContainerView.buttonStackView)
}
for (index, button) in buttons.enumerated() {
button.needsLeftSeparator = popupContainerView.buttonStackView.axis == .horizontal && index > 0
popupContainerView.buttonStackView.addArrangedSubview(button)
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
}
}
/*!
Adds a single PopupDialogButton to the Popup dialog
- parameter button: A PopupDialogButton instance
*/
public func addButton(_ button: PopupDialogButton) {
buttons.append(button)
}
/*!
Adds an array of PopupDialogButtons to the Popup dialog
- parameter buttons: A list of PopupDialogButton instances
*/
public func addButtons(_ buttons: [PopupDialogButton]) {
self.buttons += buttons
}
/// Calls the action closure of the button instance tapped
@objc fileprivate func buttonTapped(_ button: PopupDialogButton) {
if button.dismissOnTap {
dismiss() { button.buttonAction?() }
} else {
button.buttonAction?()
}
}
/*!
Simulates a button tap for the given index
Makes testing a breeze
- parameter index: The index of the button to tap
*/
public func tapButtonWithIndex(_ index: Int) {
let button = buttons[index]
button.buttonAction?()
}
}
// MARK: - View proxy values
extension PopupDialog {
/// The button alignment of the alert dialog
public var buttonAlignment: UILayoutConstraintAxis {
get { return popupContainerView.buttonStackView.axis }
set {
popupContainerView.buttonStackView.axis = newValue
popupContainerView.pv_layoutIfNeededAnimated()
}
}
/// The transition style
public var transitionStyle: PopupDialogTransitionStyle {
get { return presentationManager.transitionStyle }
set { presentationManager.transitionStyle = newValue }
}
}
|
3b878b07b1f7d9c2c008e56b52d224c6
| 33.941606 | 177 | 0.677251 | false | false | false | false |
malaonline/iOS
|
refs/heads/master
|
mala-ios/Model/Payment/OrderForm.swift
|
mit
|
1
|
//
// OrderForm.swift
// mala-ios
//
// Created by 王新宇 on 2/29/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
/// 订单模型
class OrderForm: BaseObjectModel {
// MARK: - Property
// MARK: 创建订单参数
/// 老师id
var teacher: Int = 0
/// 学校id
var school: Int = 0
/// 年级id
var grade: Int = 0
/// 学科id
var subject: Int = 0
/// 奖学金券id
var coupon: Int = 0
/// 课程小时数
var hours: Int = 0
/// 所选上课时间区块id
var weeklyTimeSlots: [Int]? = []
/// 直播课程id(实际对应某一间教室/班级)
var liveClassId: Int? = 0
/// 直播课程模型
var liveClass: LiveClassModel?
// MARK: 订单结果参数
/// 订单编号
var orderId: String?
/// 下单用户id(家长)
var parent: Int = 0
/// 优惠前价格/全价
var total: Int = 0
/// 优惠后价格/实际支付价格
var price: Int = 0
/// 订单状态
/// -see: MalaOrderStatus
var status: String?
/// 是否被抢买标记
/// 例如: 若支付过程中课程被抢买,此参数应为为false
var isTimeslotAllocated: Bool?
// MARK: 订单显示信息
/// 老师姓名
var teacherName: String?
/// 学科名
var subjectName: String?
/// 年级名
var gradeName: String?
/// 上课地点
var schoolName: String?
/// 上课地点 - 详细地址
var schoolAddress: String?
/// 老师头像URL
var avatarURL: String?
/// 优惠后价格/实际支付价格
var amount: Int = 0
/// 是否已建档测评标记
var evaluated: Bool?
/// 上课时间表
var timeSlots: [[TimeInterval]]? = []
/// 支付渠道
var chargeChannel: String? = "other"
/// 创建订单时间
var createdAt: TimeInterval? = 0
/// 支付时间
var paidAt: TimeInterval? = 0
/// 上课老师是否上架标记
var isTeacherPublished: Bool? = false
/// 订单创建失败结果
var result: Bool?
/// 订单创建失败错误码
var code: Int?
/// 直播课程标记
var isLiveCourse: Bool?
/// 支付渠道(枚举)
var channel: MalaPaymentChannel {
set{
self.chargeChannel = newValue.rawValue
}
get{
if let channel = MalaPaymentChannel(rawValue: self.chargeChannel ?? "other") {
return channel
}else {
return .Other
}
}
}
/// 订单状态
var orderStatus: MalaOrderStatus? {
if let status = status {
switch status {
case "u":
/// 待支付
return .penging
case "p":
/// 已完成(不可退费)
if
let timeSlots = timeSlots,
let slots = timeSlots.first,
let lastSlots = slots.first,
lastSlots <= Date().timeIntervalSince1970,
isLiveCourse == true {
return .finished
}
/// 已支付(进行中, 可退费)
if isLiveCourse == true {
return .paidRefundable
}
/// 已支付(进行中, 不可退费)
if isLiveCourse == false {
return .paid
}
break
case "r":
/// 已退款
return .refund
case "d":
/// 已取消
return .canceled
case "c":
/// 订单预览
return .confirm
default:
return nil
}
}else {
return nil
}
return nil
}
var attrAddressString: NSMutableAttributedString {
get {
return makeAddressAttrString(schoolName, schoolAddress)
}
}
var attrTeacherString: NSMutableAttributedString {
get {
return makeTeacherAttrString(liveClass?.lecturerName, liveClass?.assistantName)
}
}
// MARK: - Order attr
var orderTeacherNameAttr: NSMutableAttributedString {
get {
let attributedString = NSMutableAttributedString(string: "教师姓名:" + (teacherName ?? ""))
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(named: .protocolGary), range: NSRange(location: 0, length: 5))
return attributedString
}
}
var orderCourseInfoAttr: NSMutableAttributedString {
get {
let attributedString = NSMutableAttributedString(string: "课程名称:" + (gradeName ?? "") + " " + (subjectName ?? ""))
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(named: .protocolGary), range: NSRange(location: 0, length: 5))
return attributedString
}
}
var orderLiveCourseNameAttr: NSMutableAttributedString {
get {
let attributedString = NSMutableAttributedString(string: "课程名称:" + (liveClass?.courseName ?? ""))
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(named: .protocolGary), range: NSRange(location: 0, length: 5))
return attributedString
}
}
var orderSchoolAttr: NSMutableAttributedString {
get {
let attributedString = NSMutableAttributedString(string: "上课地点:" + (schoolName ?? ""))
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(named: .protocolGary), range: NSRange(location: 0, length: 5))
return attributedString
}
}
var orderAmountPriceAttr: NSMutableAttributedString {
get {
let attributedString = NSMutableAttributedString(string: "共 计:" + amount.priceCNY)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(named: .protocolGary), range: NSRange(location: 0, length: 9))
return attributedString
}
}
// MARK: - Instance Method
override init() {
super.init()
}
override init(dict: [String: Any]) {
super.init(dict: dict)
setValuesForKeys(dict)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// convenience method for create a order model with liveClass id
/// usually use to create a live course order
///
/// - parameter classId: id of live class(course)
///
/// - returns: order model
convenience init(classId: Int) {
self.init()
self.liveClassId = classId
}
/// convenience method for create a order model with errorCode when request failure
///
/// - parameter result: always return false when request failure
/// - parameter code: errorCode
///
/// - returns: order model
convenience init(result: Bool, code: Int) {
self.init()
self.result = result
self.code = code
}
/// convenience method for create a order model when request success
///
/// - parameter id: id
/// - parameter amount: money that user paid
///
/// - returns: order model
convenience init(id: Int, amount: Int) {
self.init()
self.id = id
self.amount = amount
}
// MARK: - Override
override func setValue(_ value: Any?, forKey key: String) {
if key == "teacher_name", let string = value as? String {
teacherName = string
return
}
if key == "teacher_avatar", let string = value as? String {
avatarURL = string
return
}
if key == "school_id", let int = value as? Int {
school = int
return
}
if key == "school", let string = value as? String {
schoolName = string
return
}
if key == "school_address", let string = value as? String {
schoolAddress = string
return
}
if key == "grade" {
if let string = value as? String { gradeName = string } else { gradeName = "" }
return
}
if key == "order_id", let string = value as? String {
orderId = string
return
}
if key == "to_pay", let int = value as? Int {
amount = int
return
}
if key == "created_at", let timeInterval = value as? TimeInterval {
createdAt = timeInterval
return
}
if key == "paid_at", let timeInterval = value as? TimeInterval {
paidAt = timeInterval
return
}
if key == "charge_channel", let string = value as? String {
chargeChannel = string
return
}
if key == "is_teacher_published", let bool = value as? Bool {
isTeacherPublished = bool
return
}
if key == "is_timeslot_allocated", let bool = value as? Bool {
isTimeslotAllocated = bool
return
}
if key == "timeslots", let array = value as? [[TimeInterval]] {
timeSlots = array
return
}
if key == "live_class", let dict = value as? [String: AnyObject] {
liveClass = LiveClassModel(dict: dict)
return
}
if key == "is_live", let bool = value as? Bool {
isLiveCourse = bool
return
}
super.setValue(value, forKey: key)
}
// MARK: - Description
override var description: String {
let keys = ["id"]
return dictionaryWithValues(forKeys: keys).description
}
// MARK: - Dictionary Method
/// 快速转出[一对一]订单参数字典
func jsonDictionary() -> JSON {
let teacher = self.teacher
let school = self.school
let grade = self.grade
let subject = self.subject
let hours = self.hours
let coupon = self.coupon
let timeslots = (self.weeklyTimeSlots ?? [])
var json: JSON = [
"teacher": teacher,
"school": school,
"grade": grade,
"subject": subject,
"hours": hours,
"coupon": coupon,
"weekly_time_slots": timeslots,
]
if coupon == 0 {
json["coupon"] = NSNull()
}
return json
}
/// 快速转出[双师直播]订单参数字典
func jsonForLiveCourse() -> JSON {
return [
"live_class": liveClassId ?? 0
]
}
}
|
844d82e8f1d6a38d9e2c14f67d2da060
| 25.945876 | 151 | 0.516404 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// RunTime
//
// Created by 伯驹 黄 on 2016/10/19.
// Copyright © 2016年 伯驹 黄. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
fileprivate lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.frame, style: .grouped)
tableView.dataSource = self
tableView.delegate = self
return tableView
}()
lazy var data: [[UIViewController.Type]] = [
[
FriendTableViewController.self,
PagingEnabled.self,
InfiniteScrollViewController.self,
ScrollViewController.self,
PagingSecondController.self,
ConvertController.self,
AutoLayoutController.self,
CollectionViewSelfSizing.self,
TableViewSelfsizing.self,
LayoutTrasition.self,
ExpandingCollectionViewController.self,
],
[
RulerControllerWithScrollView.self,
RulerController.self,
RulerControllerWithLayout.self
],
[
CardViewController.self
],
[
BubbleViewController.self,
ResizableImageVC.self,
TableNestCollectionController.self
],
[
MaskShapeLayerVC.self,
MaskViewVC.self
],
[
BlurController.self
],
[
WindowVC.self
],
[
GestureVC.self,
GestureButtonViewController.self
],
[
AlertController.self
],
[
VisionMenuVC.self
],
[
DiffableDatasourceMenuVC.self
]
]
override func viewDidLoad() {
super.viewDidLoad()
title = "UIScrollView"
let bannerView = BannerView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 130))
bannerView.set(content: ["", "", "", ""])
bannerView.pageStepTime = 1
bannerView.handleBack = {
print($0)
}
tableView.tableHeaderView = bannerView
let subView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView)
print(subView.isDescendant(of: view))
let array = NSArray(objects: "2.0", "2.3", "3.0", "4.0", "10")
guard let sum = array.value(forKeyPath: "@sum.floatValue"),
let avg = array.value(forKeyPath: "@avg.floatValue"),
let max = array.value(forKeyPath: "@max.floatValue"),
let min = array.value(forKeyPath: "@min.floatValue") else {
return
}
print(sum, avg, max, min)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.textLabel?.text = "\(data[indexPath.section][indexPath.row].classForCoder())"
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let controllerName = "\(data[indexPath.section][indexPath.row].classForCoder())"
if let controller = controllerName.fromClassName() as? UIViewController {
controller.title = controllerName
controller.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(controller, animated: true)
}
}
}
extension String {
func fromClassName() -> NSObject {
let className = Bundle.main.infoDictionary!["CFBundleName"] as! String + "." + self
let aClass = NSClassFromString(className) as! UIViewController.Type
return aClass.init()
}
}
extension UIView {
// var viewController: UIViewController? {
// var viewController: UIViewController?
// var next = self.next
// while next != nil {
// if next!.isKind(of: UIViewController.self) {
// viewController = next as? UIViewController
// break
// }
// next = next?.next
// }
// return viewController
// }
public func viewController<T: UIViewController>() -> T? {
var viewController: UIViewController?
var next = self.next
while let _next = next {
if _next.isKind(of: UIViewController.self) {
viewController = next as? UIViewController
break
}
next = _next.next
}
return viewController as? T
}
var safeAreaBottom: CGFloat {
if #available(iOS 11, *) {
if let window = UIApplication.shared.keyWindowInConnectedScenes {
return window.safeAreaInsets.bottom
}
}
return 0
}
var safeAreaTop: CGFloat {
if #available(iOS 11, *) {
if let window = UIApplication.shared.keyWindowInConnectedScenes {
return window.safeAreaInsets.top
}
}
return 0
}
}
|
ee6cf2126c9dd3532ca6bc0845477833
| 28.675127 | 112 | 0.582278 | false | false | false | false |
darina/omim
|
refs/heads/master
|
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RouteManager/RouteManagerHeaderView.swift
|
apache-2.0
|
5
|
final class RouteManagerHeaderView: UIView {
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var addLocationButton: UIButton! {
didSet {
// TODO(igrechuhin): Uncomment when start_from_my_position translation is ready.
// addLocationButton.setTitle(L("start_from_my_position"), for: .normal)
// addLocationButton.setTitleColor(UIColor.linkBlue(), for: .normal)
// addLocationButton.setTitleColor(UIColor.buttonDisabledBlueText(), for: .disabled)
// addLocationButton.tintColor = UIColor.linkBlue()
//
// let flipLR = CGAffineTransform(scaleX: -1.0, y: 1.0)
// addLocationButton.transform = flipLR
// addLocationButton.titleLabel?.transform = flipLR
// addLocationButton.imageView?.transform = flipLR
}
}
@IBOutlet weak var separator: UIView!
var isLocationButtonEnabled = true {
didSet {
addLocationButton.isEnabled = isLocationButtonEnabled
addLocationButton.tintColor = isLocationButtonEnabled ? UIColor.linkBlue() : UIColor.buttonDisabledBlueText()
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func applyTheme() {
super.applyTheme()
addLocationButton.tintColor = isLocationButtonEnabled ? UIColor.linkBlue() : UIColor.buttonDisabledBlueText()
}
}
|
86fb5f8706cb6a43684f0b64ca9d73d6
| 37.147059 | 115 | 0.727833 | false | false | false | false |
hongqingWang/HQSwiftMVVM
|
refs/heads/master
|
HQSwiftMVVM/HQSwiftMVVM/Classes/Tools/Network/HQNetWorkManager+Extension.swift
|
mit
|
1
|
//
// HQNetWorkManager+Extension.swift
// HQSwiftMVVM
//
// Created by 王红庆 on 2017/7/18.
// Copyright © 2017年 王红庆. All rights reserved.
//
import Foundation
// MARK: - 请求`Token`
extension HQNetWorkManager {
/// 根据`帐号`和`密码`获取`Token`
///
/// - Parameters:
/// - account: account
/// - password: password
/// - completion: 完成回调
func loadAccessToken(account: String, password: String, completion: @escaping (_ isSuccess: Bool)->()) {
// 从`bundle`加载`data`
let path = Bundle.main.path(forResource: "userAccount.json", ofType: nil)
let data = NSData(contentsOfFile: path!)
// 从`Bundle`加载配置的`userAccount.json`
guard let dict = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [String: AnyObject]
else {
return
}
// 直接用字典设置`userAccount`的属性
self.userAccount.yy_modelSet(with: dict ?? [:])
// 加载用户信息
self.loadUserInfo { (dict) in
self.userAccount.yy_modelSet(with: dict)
self.userAccount.saveAccount()
// 用户信息加载完成再执行,首页数据加载的完成回调
completion(true)
}
}
}
// MARK: - 用户信息
extension HQNetWorkManager {
/// 加载用户信息
func loadUserInfo(completion: @escaping (_ dict: [String: AnyObject]) -> ()) {
guard let uid = userAccount.uid else {
return
}
let params = ["uid": uid]
tokenRequest(URLString: HQUserInfoUrlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
// 完成回调
completion(json as? [String : AnyObject] ?? [:])
}
}
}
// MARK: - 首页
extension HQNetWorkManager {
/// 微博数据字典数组
///
/// - Parameters:
/// - since_id: 返回ID比since_id大的微博(即比since_id时间晚的微博),默认为0
/// - max_id: 返回ID小于或等于max_id的微博,默认为0
/// - completion: 微博字典数组/是否成功
func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String: AnyObject]]?, _ isSuccess: Bool)->()) {
// `swift`中,`Int`可以转换成`Anybject`,但是`Int 64`不行
let para = [
"since_id": "\(since_id)",
"max_id": "\(max_id > 0 ? (max_id - 1) : 0)"
]
tokenRequest(URLString: HQHomeUrlString, parameters: para as [String : AnyObject]) { (json, isSuccess) in
/*
从`json`中获取`statuses`字典数组
如果`as?`失败,`result = nil`
*/
let result = (json as AnyObject)["statuses"] as? [[String: AnyObject]]
completion(result, isSuccess)
}
}
/// 未读微博数量
///
/// - Parameter completion: unreadCount
func unreadCount(completion: @escaping (_ count: Int)->()) {
guard let uid = userAccount.uid else {
return
}
let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
let para = ["uid": uid]
tokenRequest(URLString: urlString, parameters: para as [String : AnyObject]) { (json, isSuccess) in
let dict = json as? [String: AnyObject]
let count = dict?["status"] as? Int
completion(count ?? 0)
}
}
}
|
39528d62eeff74d1757322366efee93e
| 28.254386 | 140 | 0.527136 | false | false | false | false |
cuappdev/podcast-ios
|
refs/heads/master
|
old/Podcast/Keys.swift
|
mit
|
1
|
/* hidden Keys.plist for sensitive information */
enum Keys: String {
case apiURL = "api-url"
case privacyPolicyURL = "privacypolicy-url"
case fabricAPIKey = "fabric-api-key"
case fabricBuildSecret = "fabric-build-secret"
case githubURL = "github-url"
case appDevURL = "appdev-url"
case reportFeedbackURL = "reportfeedback-url"
case facebookAppID = "facebook-app-id"
var value: String {
return Keys.keyDict[rawValue] as? String ?? ""
}
private static let keyDict: NSDictionary = {
guard let path = Bundle.main.path(forResource: "Keys", ofType: "plist"),
let dict = NSDictionary(contentsOfFile: path) else { return [:] }
return dict
}()
}
|
b7f6fc624d82df08b82327dfff4ecb9c
| 33.47619 | 80 | 0.653315 | false | false | false | false |
AngryLi/Onmyouji
|
refs/heads/master
|
Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/UIActivityIndicatorView+RxTests.swift
|
mit
|
14
|
//
// UIActivityIndicatorView+RxTests.swift
// Tests
//
// Created by Krunoslav Zaher on 11/26/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import RxCocoa
import RxSwift
import RxTest
import XCTest
final class UIActivityIndicatorViewTests: RxTest {
}
extension UIActivityIndicatorViewTests {
func testActivityIndicator_HasWeakReference() {
ensureControlObserverHasWeakReference(UIActivityIndicatorView(), { (view: UIActivityIndicatorView) -> AnyObserver<Bool> in view.rx.isAnimating.asObserver() }, { Variable<Bool>(true).asObservable() })
}
func testActivityIndicator_NextElementsSetsValue() {
let subject = UIActivityIndicatorView()
let boolSequence = Variable<Bool>(false)
let disposable = boolSequence.asObservable().bind(to: subject.rx.isAnimating)
defer { disposable.dispose() }
boolSequence.value = true
XCTAssertTrue(subject.isAnimating, "Expected animation to be started")
boolSequence.value = false
XCTAssertFalse(subject.isAnimating, "Expected animation to be stopped")
}
}
|
b8b768945f61bf5062fd1aecf98557f8
| 29.694444 | 207 | 0.727602 | false | true | false | false |
felipebv/AssetsAnalyser
|
refs/heads/master
|
Project/AssetsAnalyserTests/ExampleCode.swift
|
mit
|
1
|
//
// ExampleCode.swift
// AssetsAnalyser
//
// Created by Felipe Braunger Valio on 28/04/17.
// Copyright © 2017 Movile. All rights reserved.
//
import Cocoa
class ExampleCode {
func doNothing() {
_ = Localization.journeyPopup("banana", "carambola")
_ = Localization.journeyPopup("banana", "carambola").string
_ = Localization.aboutSatyanatha.string
_ = Localization.aboutSatyanatha
_ = Localization.reminderTime
_ = ImageAsset.btnPlayer.image
_ = ImageAsset.btnPlayer
let _: Localization = .connectionError
self.embeddedVideoAbout()
}
func embeddedVideoAbout() {
// decoy method
}
}
|
164adf622fd35b59ac0d15890922a2c8
| 23.206897 | 67 | 0.623932 | false | false | false | false |
kevintavog/Radish
|
refs/heads/master
|
src/Radish/Controllers/SingleViewWindowController-MenuHandling.swift
|
mit
|
1
|
//
// Radish
//
import AppKit
import RangicCore
// Menu handlers for SingleViewWindowController
extension SingleViewWindowController
{
@IBAction func onShowWikipediaOnMap(_ sender: Any) {
var val = false
if menuShowWikipediaOnMap.state == NSControl.StateValue.off {
menuShowWikipediaOnMap.state = NSControl.StateValue.on
val = true
} else {
menuShowWikipediaOnMap.state = NSControl.StateValue.off
val = false
}
Notifications.postNotification(Notifications.SingleView.ShowWikipediaOnMap, object: self, userInfo: ["ShowWikipediaOnMap": val])
}
@IBAction func onShowPlacenameDetails(_ sender: Any) {
var val = false
if menuShowPlacenameDetails.state == NSControl.StateValue.off {
menuShowPlacenameDetails.state = NSControl.StateValue.on
val = true
} else {
menuShowPlacenameDetails.state = NSControl.StateValue.off
val = false
}
Notifications.postNotification(Notifications.SingleView.ShowPlacenameDetails, object: self, userInfo: ["ShowPlacenameDetails": val])
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool
{
switch MenuItemTag(rawValue: menuItem.tag)! {
case .alwaysEnable:
return true
case .requiresFile:
return (mediaProvider?.mediaCount)! > 0
}
}
func tryToMoveTo(_ calculate: (_ index: Int, _ maxIndex: Int) -> Int)
{
if let provider = mediaProvider {
let count = provider.mediaCount
if count > 0 {
displayFileByIndex(calculate(currentFileIndex, count - 1))
}
}
}
@objc
override func pageUp(_ sender: Any?)
{
tryToMoveTo({ index, maxIndex in max(0, index - Preferences.pageSize) })
}
@objc
override func pageDown(_ sender: Any?)
{
tryToMoveTo({ index, maxIndex in min(maxIndex, index + Preferences.pageSize) })
}
@objc
func moveToFirstItem(_ sender: AnyObject?)
{
tryToMoveTo({ index, maxIndex in 0 })
}
@objc
func moveToLastItem(_ sender: AnyObject?)
{
tryToMoveTo({ index, maxIndex in maxIndex })
}
@objc
func moveToPercent(_ percent: Int)
{
tryToMoveTo({ index, maxIndex in (maxIndex * percent) / 100 })
}
@objc
func moveToTenPercent(_ sender: AnyObject?)
{
moveToPercent(10)
}
@objc
func moveToTwentyPercent(_ sender: AnyObject?)
{
moveToPercent(20)
}
@objc
func moveToThirtyPercent(_ sender: AnyObject?)
{
moveToPercent(30)
}
@objc
func moveToFortyPercent(_ sender: AnyObject?)
{
moveToPercent(40)
}
@objc
func moveToFiftyPercent(_ sender: AnyObject?)
{
moveToPercent(50)
}
@objc
func moveToSixtyPercent(_ sender: AnyObject?)
{
moveToPercent(60)
}
@objc
func moveToSeventyPercent(_ sender: AnyObject?)
{
moveToPercent(70)
}
@objc
func moveToEightyPercent(_ sender: AnyObject?)
{
moveToPercent(80)
}
@objc
func moveToNinetyPercent(_ sender: AnyObject?)
{
moveToPercent(90)
}
@objc
override func keyDown(with theEvent: NSEvent)
{
if let chars = theEvent.charactersIgnoringModifiers {
let modFlags = NSEvent.ModifierFlags(rawValue: theEvent.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue)
let keySequence = KeySequence(modifierFlags: modFlags, chars: chars)
if let selector = keyMappings[keySequence] {
self.performSelector(onMainThread: selector, with: theEvent.window, waitUntilDone: true)
return
} else {
// Logger.debug("Unable to find match for \(keySequence)")
}
}
super.keyDown(with: theEvent)
}
@IBAction func openFolder(_ sender: AnyObject)
{
let folders = selectFoldersToAdd()
if (folders.urls == nil) { return }
currentMediaData = nil
currentFileIndex = 0;
mediaProvider!.clear()
mediaProvider!.setRepository(FileMediaRepository())
addFolders(folders.urls!, selected: folders.selected)
}
@IBAction func addFolder(_ sender: AnyObject)
{
if (mediaProvider?.mediaCount)! < 1 {
openFolder(sender)
return
}
let folders = selectFoldersToAdd()
if (folders.urls == nil) { return }
addFolders(folders.urls!, selected: currentMediaData!.url)
updateStatusView()
}
@IBAction func refreshFiles(_ sender: AnyObject)
{
mediaProvider!.refresh()
}
@IBAction func nextFile(_ sender: AnyObject)
{
displayFileByIndex(currentFileIndex + 1)
}
@IBAction func previousFile(_ sender: AnyObject)
{
displayFileByIndex(currentFileIndex - 1)
}
@IBAction func firstFile(_ sender: AnyObject)
{
displayFileByIndex(0)
}
@IBAction func lastFile(_ sender: AnyObject)
{
displayFileByIndex(mediaProvider!.mediaCount - 1)
}
@IBAction func revealInFinder(_ sender: AnyObject)
{
if !onlyIfLocalFile(currentMediaData!.url, message: "Only local files can be revealed in the finder.", information: "\(currentMediaData!.url!)") {
return
}
NSWorkspace.shared.selectFile(currentMediaData!.url!.path, inFileViewerRootedAtPath: "")
}
@IBAction func setFileDateFromExifDate(_ sender: AnyObject)
{
if !onlyIfLocalFile(currentMediaData!.url, message: "Only local files can change dates.", information: "\(currentMediaData!.url!)") {
return
}
let filename = currentMediaData!.url.path
Logger.info("setFileDateFromExifDate: \(filename)")
let result = mediaProvider?.setFileDatesToExifDates([currentMediaData!])
if !result!.allSucceeded {
let alert = NSAlert()
alert.messageText = "Set file date of '\(filename)' failed: \(result!.errorMessage)."
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: "Close")
alert.runModal()
}
}
@IBAction func autoRotate(_ sender: AnyObject)
{
if !onlyIfLocalFile(currentMediaData!.url, message: "Only local files can be rotated.", information: "\(currentMediaData!.url!)") {
return
}
let filename = currentMediaData!.url.path
Logger.info("autoRotate: \(filename)")
let jheadInvoker = JheadInvoker.autoRotate([filename])
if jheadInvoker.processInvoker.exitCode != 0 {
let alert = NSAlert()
alert.messageText = "Auto rotate of '\(filename)' failed: \(jheadInvoker.processInvoker.error)."
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: "Close")
alert.runModal()
}
}
@IBAction func moveToTrash(_ sender: AnyObject)
{
let url = currentMediaData!.url
if !onlyIfLocalFile(url, message: "Only local files can be moved to the trash.", information: "\(url!)") {
return
}
Logger.info("moveToTrash: \((url?.path)!)")
let filename = (url?.lastPathComponent)!
NSWorkspace.shared.recycle([url!]) { newUrls, error in
if error != nil {
let alert = NSAlert()
alert.messageText = "Failed moving '\(filename)' to trash."
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: "Close")
alert.runModal()
}
else {
NSSound(contentsOfFile: self.trashSoundPath, byReference: false)?.play()
}
}
}
@IBAction func showOnMap(_ sender: AnyObject)
{
Logger.info("showOnMap '\((currentMediaData?.locationString())!)'")
if let location = currentMediaData?.location {
var url = ""
switch Preferences.showOnMap {
case .bing:
url = "http://www.bing.com/maps/default.aspx?cp=\(location.latitude)~\(location.longitude)&lvl=17&rtp=pos.\(location.latitude)_\(location.longitude)"
case .google:
url = "http://maps.google.com/maps?q=\(location.latitude),\(location.longitude)"
case .openStreetMap:
url = "http://www.openstreetmap.org/?&mlat=\(location.latitude)&mlon=\(location.longitude)#map=18/\(location.latitude)/\(location.longitude)"
}
if url.count > 0 {
NSWorkspace.shared.open(URL(string: url)!)
}
}
}
@IBAction func showOpenStreetMapFeatures(_ sender: Any) {
Logger.info("showOpenStreetMapFeatures '\((currentMediaData?.locationString())!)'")
if let location = currentMediaData?.location {
let url = "https://www.openstreetmap.org/query?lat=\(location.latitude)&lon=\(location.longitude)&mlat=\(location.latitude)&mlon=\(location.longitude)"
NSWorkspace.shared.open(URL(string: url)!)
}
}
@IBAction func copyLatLon(_ sender: Any) {
if let location = currentMediaData?.location {
NSPasteboard.general.clearContents()
NSPasteboard.general.writeObjects(["\(location.latitude),\(location.longitude)" as NSString])
}
}
@IBAction func zoomIn(_ sender: Any) {
zoomView?.zoomIn()
}
@IBAction func zoomOut(_ sender: Any) {
zoomView?.zoomOut()
}
@IBAction func zoomToActualSize(_ sender: Any) {
zoomView?.zoomToActualSize(imageSize: imageViewer.image!.size)
}
@IBAction func zoomToFit(_ sender: Any) {
zoomView?.zoomToFit()
}
func onlyIfLocalFile(_ url: URL?, message: String, information: String?) -> Bool
{
if !(url?.isFileURL)! {
let alert = NSAlert()
alert.messageText = message
if information != nil {
alert.informativeText = information!
}
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: "Close")
alert.runModal()
return false
}
return true
}
}
|
e2da0143273a1d322f2035586d161838
| 28.763533 | 165 | 0.597396 | false | false | false | false |
frootloops/swift
|
refs/heads/master
|
test/Reflection/typeref_decoding.swift
|
apache-2.0
|
1
|
// REQUIRES: no_asan
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension
// RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | %FileCheck %s
// CHECK: FIELDS:
// CHECK: =======
// CHECK: TypesToReflect.Box
// CHECK: ------------------
// CHECK: item: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: anEnum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: aTupleWithLabels: (a: TypesToReflect.C, s: TypesToReflect.S, e: TypesToReflect.E)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithVarArgs: (TypesToReflect.C, TypesToReflect.S...) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (variadic
// CHECK: (struct TypesToReflect.S))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout1: (inout TypesToReflect.C) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (inout
// CHECK: (class TypesToReflect.C))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout2: (TypesToReflect.C, inout Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (inout
// CHECK: (struct Swift.Int))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout3: (inout TypesToReflect.C, inout Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (inout
// CHECK: (class TypesToReflect.C))
// CHECK: (inout
// CHECK: (struct Swift.Int))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithShared: (__shared TypesToReflect.C) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (shared
// CHECK: (class TypesToReflect.C))
// CHECK: (result
// CHECK: (tuple))
// CHECK: TypesToReflect.S.NestedS
// CHECK: ------------------------
// CHECK: aField: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: TypesToReflect.S
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.Box<TypesToReflect.S>, TypesToReflect.Box<TypesToReflect.E>, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: (struct Swift.Int))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithThinRepresentation: @convention(thin) () -> ()
// CHECK: (function convention=thin
// CHECK: (tuple))
// CHECK: aFunctionWithCRepresentation: @convention(c) () -> ()
// CHECK: (function convention=c
// CHECK: (tuple))
// CHECK: TypesToReflect.E
// CHECK: ----------------
// CHECK: Class: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: Struct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: Enum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: Function: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (tuple))
// CHECK: Tuple: (TypesToReflect.C, TypesToReflect.S, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (struct Swift.Int))
// CHECK: IndirectTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: NestedStruct: TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S))
// CHECK: Metatype
// CHECK: EmptyCase
// CHECK: TypesToReflect.References
// CHECK: -------------------------
// CHECK: strongRef: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: weakRef: weak Swift.Optional<TypesToReflect.C>
// CHECK: (weak_storage
// CHECK: (bound_generic_enum Swift.Optional
// CHECK: (class TypesToReflect.C)))
// CHECK: unownedRef: unowned TypesToReflect.C
// CHECK: (unowned_storage
// CHECK: (class TypesToReflect.C))
// CHECK: unownedUnsafeRef: unowned(unsafe) TypesToReflect.C
// CHECK: (unmanaged_storage
// CHECK: (class TypesToReflect.C))
// CHECK: TypesToReflect.C1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, TypesToReflect.E1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: dependentMember: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, TypesToReflect.E2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.C3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, TypesToReflect.E3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Outer
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.Outer.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.C4
// CHECK: -----------------
// CHECK: TypesToReflect.S1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.Box<TypesToReflect.S1<A>>, TypesToReflect.Box<TypesToReflect.E1<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.S2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C2<A>) -> (TypesToReflect.S2<A>) -> (TypesToReflect.E2<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.Box<TypesToReflect.S2<A>>, TypesToReflect.Box<TypesToReflect.E2<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.S3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.Box<TypesToReflect.S3<A>>, TypesToReflect.Box<TypesToReflect.E3<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Outer
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.Outer.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.S4
// CHECK: -----------------
// CHECK: TypesToReflect.E1
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Int: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: Function: (A) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: Metatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E2
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S2<A>
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E2<A>
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberInner: A.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: ExistentialMetatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E3
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (metatype
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberOuter: A.Outer
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: DependentMemberInner: A.Outer.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.E4
// CHECK: -----------------
// CHECK: TypesToReflect.P1
// CHECK: -----------------
// CHECK: TypesToReflect.P2
// CHECK: -----------------
// CHECK: TypesToReflect.P3
// CHECK: -----------------
// CHECK: TypesToReflect.P4
// CHECK: -----------------
// CHECK: TypesToReflect.ClassBoundP
// CHECK: --------------------------
// CHECK: TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}})
// CHECK: -------------------------------------------------------------------------
// CHECK: TypesToReflect.HasFileprivateProtocol
// CHECK: -------------------------------------
// CHECK: x: TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}})
// CHECK: (protocol TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}}))
// CHECK: ASSOCIATED TYPES:
// CHECK: =================
// CHECK: - TypesToReflect.C1 : TypesToReflect.ClassBoundP
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P2
// CHECK: typealias Outer = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P3
// CHECK: typealias First = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: typealias Second = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.S : TypesToReflect.P4
// CHECK: typealias Result = Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: BUILTIN TYPES:
// CHECK: ==============
// CHECK: CAPTURE DESCRIPTORS:
// CHECK: ====================
// CHECK: - Capture types:
// CHECK: (sil_box
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (closure_binding index=1)
// CHECK: - Capture types:
// CHECK: (struct Swift.Int)
// CHECK: - Metadata sources:
// CHECK: - Capture types:
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=1))
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (generic_argument index=0
// CHECK: (reference_capture index=0))
|
949a2a00d148a2d2146a4f1f8b992769
| 35.010767 | 285 | 0.662393 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.