repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
narner/AudioKit
AudioKit/Common/Nodes/Playback/Player/AKAudioPlayer.swift
1
24479
// // AKAudioPlayer.swift // AudioKit // // Created by Aurelius Prochazka, Laurent Veliscek & Ryan Francesconi, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// Not so simple audio playback class open class AKAudioPlayer: AKNode, AKToggleable { // MARK: - Private variables fileprivate var internalAudioFile: AKAudioFile fileprivate var internalPlayer = AVAudioPlayerNode() fileprivate var internalMixer = AVAudioMixerNode() fileprivate var totalFrameCount: UInt32 = 0 fileprivate var startingFrame: UInt32 = 0 fileprivate var endingFrame: UInt32 = 0 fileprivate var framesToPlayCount: UInt32 = 0 fileprivate var lastCurrentTime: Double = 0 fileprivate var paused = false fileprivate var playing = false fileprivate var internalStartTime: Double = 0 fileprivate var internalEndTime: Double = 0 fileprivate var scheduledStopAction: AKScheduledAction? // MARK: - Properties /// Buffer to be played @objc fileprivate var _audioFileBuffer: AVAudioPCMBuffer? @objc open dynamic var audioFileBuffer: AVAudioPCMBuffer? { get { if _audioFileBuffer == nil { updatePCMBuffer() } return _audioFileBuffer } set { _audioFileBuffer = newValue } } /// Will be triggered when AKAudioPlayer has finished to play. /// (will not as long as loop is on) @objc open dynamic var completionHandler: AKCallback? private var _looping: Bool = false { didSet { updateBufferLooping() } } /// Boolean indicating whether or not to loop the playback (Default false) @objc open dynamic var looping: Bool { set { guard newValue != _looping else { return } _looping = newValue } get { return _looping } } /// Boolean indicating to play the buffer in reverse @objc open dynamic var reversed: Bool = false { didSet { updatePCMBuffer() } } /// Fade in duration @objc open dynamic var fadeInTime: Double = 0 { didSet { updatePCMBuffer() } } /// Fade out duration @objc open dynamic var fadeOutTime: Double = 0 { didSet { updatePCMBuffer() } } /// The current played AKAudioFile @objc open dynamic var audioFile: AKAudioFile { return internalAudioFile } /// Path to the currently loaded AKAudioFile @objc open dynamic var path: String { return audioFile.url.path } /// Total duration of one loop through of the file @objc open dynamic var duration: Double { return Double(totalFrameCount) / Double(internalAudioFile.sampleRate) } /// Output Volume (Default 1) @objc open dynamic var volume: Double = 1.0 { didSet { volume = max(volume, 0) internalPlayer.volume = Float(volume) } } /// Whether or not the audio player is currently started @objc open dynamic var isStarted: Bool { return internalPlayer.isPlaying } /// Current playback time (in seconds) @objc open dynamic var currentTime: Double { if playing { if let nodeTime = internalPlayer.lastRenderTime, let playerTime = internalPlayer.playerTime(forNodeTime: nodeTime) { return Double(playerTime.sampleTime) / playerTime.sampleRate } } return lastCurrentTime } /// Time within the audio file at the current time @objc open dynamic var playhead: Double { let endTime = Double(endingFrame) / internalAudioFile.sampleRate let startTime = Double(startingFrame) / internalAudioFile.sampleRate if endTime > startTime { if looping { return startTime + currentTime.truncatingRemainder(dividingBy: (endTime - startTime)) } else { if currentTime > endTime { return (startTime + currentTime).truncatingRemainder(dividingBy: (endTime - startTime)) } else { return (startTime + currentTime) } } } else { return 0 } } /// Pan (Default Center = 0) @objc open dynamic var pan: Double = 0.0 { didSet { pan = (-1...1).clamp(pan) internalPlayer.pan = Float(pan) } } /// sets the start time, If it is playing, player will /// restart playing from the start time each time end time is set @objc open dynamic var startTime: Double { get { return Double(startingFrame) / internalAudioFile.sampleRate } set { // since setting startTime will fill the buffer again, we only want to do this if the // data really needs to be updated if newValue > Double(endingFrame) / internalAudioFile.sampleRate && endingFrame > 0 { AKLog("ERROR: AKAudioPlayer cannot set a startTime bigger than the endTime: " + "\(Double(endingFrame) / internalAudioFile.sampleRate) seconds") } else { startingFrame = UInt32(newValue * internalAudioFile.sampleRate) AKLog("AKAudioPlayer.startTime = \(newValue), startingFrame: \(startingFrame)") // now update the buffer updatePCMBuffer() // remember this value for ease of checking redundancy later internalStartTime = newValue } } } /// sets the end time, If it is playing, player will /// restart playing from the start time each time end time is set @objc open dynamic var endTime: Double { get { return Double(endingFrame) / internalAudioFile.sampleRate } set { // since setting startTime will fill the buffer again, we only want to do this if the // data really needs to be updated if newValue == internalEndTime { //AKLog("endTime is the same, so returning: \(newValue)") return } else if newValue == 0 { endingFrame = totalFrameCount } else if newValue < Double(startingFrame) / internalAudioFile.sampleRate || newValue > Double(Double(totalFrameCount) / internalAudioFile.sampleRate) { AKLog("ERROR: AKAudioPlayer cannot set an endTime more than file's duration: \(duration) seconds or " + "less than startTime: \(Double(startingFrame) / internalAudioFile.sampleRate) seconds") } else { endingFrame = UInt32(newValue * internalAudioFile.sampleRate) AKLog("AKAudioPlayer.endTime = \(newValue), endingFrame: \(endingFrame)") // now update the buffer updatePCMBuffer() // remember this value for ease of checking redundancy later internalEndTime = newValue } } } /// Sets the time in the future when playback will commence. Recommend using play(from:to:avTime) instead. /// this will be deprecated @objc open dynamic var scheduledTime: Double = 0 { didSet { let hostTime = mach_absolute_time() scheduledAVTime = AKAudioPlayer.secondsToAVAudioTime(hostTime: hostTime, time: scheduledTime) } } /// Sheduled time @objc open dynamic var scheduledAVTime: AVAudioTime? // MARK: - Initialization /// Initialize the audio player /// /// /// Notice that completionCallBack will be triggered from a /// background thread. Any UI update should be made using: /// /// ``` /// Dispatch.main.async { /// // UI updates... /// } /// ``` /// /// - Parameters: /// - file: the AKAudioFile to play /// - looping: will loop play if set to true, or stop when play ends, so it can trig the /// completionHandler callback. Default is false (non looping) /// - completionHandler: AKCallback that will be triggered when the player end playing (useful for refreshing /// UI so we're not playing anymore, we stopped playing...) /// /// - Returns: an AKAudioPlayer if init succeeds, or nil if init fails. If fails, errors may be caught. /// @objc public init(file: AKAudioFile, looping: Bool = false, lazyBuffering: Bool = false, completionHandler: AKCallback? = nil) throws { let readFile: AKAudioFile // Open the file for reading to avoid a crash when setting frame position // if the file was instantiated for writing do { readFile = try AKAudioFile(forReading: file.url) } catch let error as NSError { AKLog("AKAudioPlayer Error: cannot open file \(file.fileNamePlusExtension) for reading") AKLog("Error: \(error)") throw error } internalAudioFile = readFile self.completionHandler = completionHandler super.init() self.looping = looping AudioKit.engine.attach(internalPlayer) AudioKit.engine.attach(internalMixer) let format = AVAudioFormat(standardFormatWithSampleRate: internalAudioFile.sampleRate, channels: internalAudioFile.channelCount) AudioKit.engine.connect(internalPlayer, to: internalMixer, format: format) avAudioNode = internalMixer internalPlayer.volume = 1.0 initialize(lazyBuffering: lazyBuffering) } fileprivate var defaultBufferOptions: AVAudioPlayerNodeBufferOptions { return looping ? [.loops, .interrupts] : [.interrupts] } // MARK: - Methods /// Start playback @objc open func start() { play(at:nil) } open func play(at when: AVAudioTime?) { if ❗️playing { if audioFileBuffer != nil { // schedule it at some point in the future / or immediately if 0 // don't schedule the buffer if it is paused as it will overwrite what is in it if ❗️paused { scheduleBuffer(atTime: scheduledAVTime, options: defaultBufferOptions) } internalPlayer.play(at: when) playing = true paused = false } else { AKLog("AKAudioPlayer Warning: cannot play an empty buffer") } } else { AKLog("AKAudioPlayer Warning: already playing") } } /// Stop playback @objc open func stop() { scheduledStopAction = nil if ❗️playing { return } lastCurrentTime = Double(startTime / internalAudioFile.sampleRate) playing = false paused = false internalPlayer.stop() } /// Pause playback open func pause() { if playing { if ❗️paused { lastCurrentTime = currentTime playing = false paused = true internalPlayer.pause() } else { AKLog("AKAudioPlayer Warning: already paused") } } else { AKLog("AKAudioPlayer Warning: Cannot pause when not playing") } } /// Restart playback from current position open func resume() { if paused { self.play() } } /// resets in and out times for playing open func reloadFile() throws { let wasPlaying = playing if wasPlaying { stop() } var newAudioFile: AKAudioFile? do { newAudioFile = try AKAudioFile(forReading: internalAudioFile.url) } catch let error as NSError { AKLog("AKAudioPlayer Error: Couldn't reLoadFile") AKLog("Error: \(error)") throw error } if let newFile = newAudioFile { internalAudioFile = newFile } internalPlayer.reset() let format = AVAudioFormat(standardFormatWithSampleRate: internalAudioFile.sampleRate, channels: internalAudioFile.channelCount) AudioKit.engine.connect(internalPlayer, to: internalMixer, format: format) initialize() if wasPlaying { start() } } /// Replace player's file with a new AKAudioFile file @objc open func replace(file: AKAudioFile) throws { internalAudioFile = file do { try reloadFile() } catch let error as NSError { AKLog("AKAudioPlayer Error: Couldn't reload replaced File: \"\(file.fileNamePlusExtension)\"") AKLog("Error: \(error)") } AKLog("AKAudioPlayer -> File with \"\(internalAudioFile.fileNamePlusExtension)\" Reloaded") } /// Default play that will use the previously set startTime and endTime properties or the full file if both are 0 open func play() { play(from: self.startTime, to: self.endTime, avTime: nil) } /// Play from startTime to endTime @objc open func play(from startTime: Double, to endTime: Double) { play(from: startTime, to: endTime, avTime: nil) } /// Play the file back from a certain time, to an end time (if set). /// You can optionally set a scheduled time to play (in seconds). /// /// - Parameters: /// - startTime: Time into the file at which to start playing back /// - endTime: Time into the file at which to playing back will stop / Loop /// - scheduledTime: use this when scheduled playback doesn't need to be in sync with other players /// otherwise use the avTime signature. /// open func play(from startTime: Double, to endTime: Double, when scheduledTime: Double) { let hostTime = mach_absolute_time() let avTime = AKAudioPlayer.secondsToAVAudioTime(hostTime: hostTime, time: scheduledTime) play(from: startTime, to: endTime, avTime: avTime) } /// Play the file back from a certain time, to an end time (if set). You can optionally set a scheduled time /// to play (in seconds). /// /// - Parameters: /// - startTime: Time into the file at which to start playing back /// - endTime: Time into the file at which to playing back will stop / Loop /// - avTime: an AVAudioTime object specifying when to schedule the playback. You can create this using the /// helper function AKAudioPlayer.secondToAVAudioTime(hostTime:time). hostTime is a call to /// mach_absolute_time(). When you have a group of players which you want to sync together it's /// important that this value be the same for all of them as a reference point. /// open func play(from startTime: Double, to endTime: Double, avTime: AVAudioTime? ) { schedule(from: startTime, to: endTime, avTime: avTime) if endingFrame > startingFrame { start() } else { AKLog("ERROR AKaudioPlayer: cannot play, \(internalAudioFile.fileNamePlusExtension) " + "is empty or segment is too short") } } open func schedule(from startTime: Double, to endTime: Double, avTime: AVAudioTime? ) { stop() if endTime > 0 { self.endTime = endTime } self.startTime = startTime scheduledAVTime = avTime } /// return the peak time in the currently loaded buffer open func getPeakTime() -> Double { guard let buffer = audioFileBuffer else { return 0 } return AKAudioFile.findPeak(pcmBuffer: buffer) } // MARK: - Static Methods /// Convert to AVAudioTime open class func secondsToAVAudioTime(hostTime: UInt64, time: Double) -> AVAudioTime { // Find the conversion factor from host ticks to seconds var timebaseInfo = mach_timebase_info() mach_timebase_info(&timebaseInfo) let hostTimeToSecFactor = Double(timebaseInfo.numer) / Double(timebaseInfo.denom) / Double(NSEC_PER_SEC) let out = AVAudioTime(hostTime: hostTime + UInt64(time / hostTimeToSecFactor)) return out } // MARK: - Private Methods fileprivate func initialize(lazyBuffering: Bool = false) { audioFileBuffer = nil totalFrameCount = UInt32(internalAudioFile.length) startingFrame = 0 endingFrame = totalFrameCount if !lazyBuffering { updatePCMBuffer() } } fileprivate func scheduleBuffer(atTime: AVAudioTime?, options: AVAudioPlayerNodeBufferOptions) { scheduledStopAction = nil if let buffer = audioFileBuffer { scheduledStopAction = nil internalPlayer.scheduleBuffer(buffer, at: atTime, options: options, completionHandler: looping ? nil : internalCompletionHandler) if atTime != nil { internalPlayer.prepare(withFrameCount: framesToPlayCount) } } } fileprivate func updateBufferLooping() { guard playing else { return } if looping { // Looping is toggled on: schedule the buffer to loop at the next loop interval. let options: AVAudioPlayerNodeBufferOptions = [.loops, .interruptsAtLoop] scheduleBuffer(atTime: nil, options: options) } else { // Looping is toggled off: schedule to stop at the end of the current loop. stopAtNextLoopEnd() } } /// Stop playback after next loop completes @objc open func stopAtNextLoopEnd() { guard playing else { return } scheduledStopAction = AKScheduledAction(interval: endTime - currentTime) { self.stop() self.completionHandler?() } } /// Fills the buffer with data read from internalAudioFile fileprivate func updatePCMBuffer() { guard internalAudioFile.length > 0 else { AKLog("AKAudioPlayer Warning: \"\(internalAudioFile.fileNamePlusExtension)\" is an empty file") return } var theStartFrame = startingFrame var theEndFrame = endingFrame // if we are going to be reversing the buffer, we need to think ahead a bit // since the edit points would be reversed as well, we swap them here: if reversed { let revEndTime = duration - startTime let revStartTime = endTime > 0 ? duration - endTime : duration theStartFrame = UInt32(revStartTime * internalAudioFile.sampleRate) theEndFrame = UInt32(revEndTime * internalAudioFile.sampleRate) } if internalAudioFile.samplesCount > 0 { internalAudioFile.framePosition = Int64(theStartFrame) framesToPlayCount = theEndFrame - theStartFrame //AKLog("framesToPlayCount: \(framesToPlayCount) frameCapacity \(totalFrameCount)") audioFileBuffer = AVAudioPCMBuffer( pcmFormat: internalAudioFile.processingFormat, frameCapacity: AVAudioFrameCount(totalFrameCount) ) do { // read the requested frame count from the file try internalAudioFile.read(into: audioFileBuffer!, frameCount: framesToPlayCount) AKLog("read \(audioFileBuffer?.frameLength ?? 0) frames into buffer") } catch { AKLog("ERROR AKaudioPlayer: Could not read data into buffer.") return } // Now, we'll reverse the data in the buffer if desired... if reversed { reverseBuffer() } if fadeInTime > 0 || fadeOutTime > 0 { fadeBuffer(inTime: fadeInTime, outTime: fadeOutTime) } } else { AKLog("ERROR updatePCMBuffer: Could not set PCM buffer -> " + "\(internalAudioFile.fileNamePlusExtension) samplesCount = 0.") } } /// Turn the buffer around! fileprivate func reverseBuffer() { guard let buffer = audioFileBuffer else { AKLog("Unable to create buffer in reverseBuffer") return } let reverseBuffer = AVAudioPCMBuffer( pcmFormat: internalAudioFile.processingFormat, frameCapacity: buffer.frameCapacity ) var j: Int = 0 let length = buffer.frameLength //AKLog("reverse() preparing \(length) frames") // i represents the normal buffer read in reverse for i in (0 ..< Int(length)).reversed() { // n is the channel for n in 0 ..< Int(buffer.format.channelCount) { // we write the reverseBuffer via the j index reverseBuffer?.floatChannelData?[n][j] = buffer.floatChannelData?[n][i] ?? 0.0 } j += 1 } // set the buffer now to be the reverse one audioFileBuffer = reverseBuffer // update this to the new value audioFileBuffer?.frameLength = length } /// Apply sample level fades to the internal buffer. /// - Parameters: /// - inTime specified in seconds, 0 if no fade /// - outTime specified in seconds, 0 if no fade fileprivate func fadeBuffer(inTime: Double = 0, outTime: Double = 0) { guard audioFileBuffer != nil else { AKLog("audioFileBuffer is nil") return } // do nothing in this case if inTime == 0 && outTime == 0 { AKLog("no fades specified.") return } let fadeBuffer = AVAudioPCMBuffer( pcmFormat: internalAudioFile.processingFormat, frameCapacity: audioFileBuffer!.frameCapacity ) let length: UInt32 = audioFileBuffer!.frameLength AKLog("fadeBuffer() inTime: \(inTime) outTime: \(outTime)") // initial starting point for the gain, if there is a fade in, start it at .01 otherwise at 1 var gain: Double = inTime > 0 ? 0.01 : 1 let sampleTime: Double = 1.0 / internalAudioFile.processingFormat.sampleRate // from -20db? let fadeInPower: Double = exp(log(10) * sampleTime / inTime) // for decay to x% amplitude (-dB) over the given decay time let fadeOutPower: Double = exp(-log(25) * sampleTime / outTime) // where in the buffer to end the fade in let fadeInSamples = Int(internalAudioFile.processingFormat.sampleRate * inTime) // where in the buffer to start the fade out let fadeOutSamples = Int(Double(length) - (internalAudioFile.processingFormat.sampleRate * outTime)) //Swift.print("fadeInPower \(fadeInPower) fadeOutPower \(fadeOutPower)") // i is the index in the buffer for i in 0 ..< Int(length) { // n is the channel for n in 0 ..< Int(audioFileBuffer!.format.channelCount) { if i < fadeInSamples && inTime > 0 { gain *= fadeInPower } else if i > fadeOutSamples && outTime > 0 { gain *= fadeOutPower } else { gain = 1.0 } //sanity check if gain > 1 { gain = 1 } let sample = audioFileBuffer!.floatChannelData![n][i] * Float(gain) fadeBuffer?.floatChannelData?[n][i] = sample } } // set the buffer now to be the faded one audioFileBuffer = fadeBuffer // update this audioFileBuffer?.frameLength = length } /// Triggered when the player reaches the end of its playing range fileprivate func internalCompletionHandler() { DispatchQueue.main.async { if self.isPlaying { self.stop() self.completionHandler?() } } } // Disconnect the node override open func disconnect() { AudioKit.detach(nodes: [self.avAudioNode]) AudioKit.engine.detach(self.internalPlayer) } }
mit
1493b121c2624aa1d464e71b26a20c55
33.895863
136
0.593369
5.095189
false
false
false
false
PurpleSweetPotatoes/SwiftKit
SwiftKit/netWork/BQImgData.swift
1
7924
// // BQImgData.swift // BQTabBarTest // // Created by MrBai on 2017/7/21. // Copyright © 2017年 MrBai. All rights reserved. // import MobileCoreServices import UIKit open class BQImgData { // MARK: - Helper Types struct BQEncodingCharacters { static let crlf = "\r\n" } struct BQBoundaryGenerator { enum BoundaryType { case initial, encapsulated, final } static func randomBoundary() -> String { return String(format: "bq.boundary.%08x%08x", arc4random(), arc4random()) } static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { let boundaryText: String switch boundaryType { case .initial: boundaryText = "--\(boundary)\(BQEncodingCharacters.crlf)" case .encapsulated: boundaryText = "\(BQEncodingCharacters.crlf)--\(boundary)\(BQEncodingCharacters.crlf)" case .final: boundaryText = "\(BQEncodingCharacters.crlf)--\(boundary)--\(BQEncodingCharacters.crlf)" } return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } } class BQBodyPart { let headers: [String: String] let bodyStream: InputStream let bodyContentLength: UInt64 var hasInitialBoundary = false var hasFinalBoundary = false init(headers: [String: String], bodyStream: InputStream, bodyContentLength: UInt64) { self.headers = headers self.bodyStream = bodyStream self.bodyContentLength = bodyContentLength } } // MARK: - Properties /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. open var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } /// The boundary used to separate the body parts in the encoded form data. public let boundary: String private var bodyParts: [BQBodyPart] private let streamBufferSize: Int // MARK: - Lifecycle /// Creates a multipart form data object. /// /// - returns: The multipart form data object. public init() { self.boundary = BQBoundaryGenerator.randomBoundary() self.bodyParts = [] self.streamBufferSize = 1024 } public func append(_ data: Data, withName name: String) { let headers = contentHeaders(withName: name) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } public func append(_ data: Data, withName name: String, mimeType: String) { let headers = contentHeaders(withName: name, mimeType: mimeType) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) let stream = InputStream(data: data) let length = UInt64(data.count) append(stream, withLength: length, headers: headers) } public func append( _ stream: InputStream, withLength length: UInt64, name: String, fileName: String, mimeType: String) { let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) append(stream, withLength: length, headers: headers) } public func append(_ stream: InputStream, withLength length: UInt64, headers: [String: String]) { let bodyPart = BQBodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) bodyParts.append(bodyPart) } public func encode() throws -> Data { var encoded = Data() bodyParts.first?.hasInitialBoundary = true bodyParts.last?.hasFinalBoundary = true for bodyPart in bodyParts { let encodedData = try encode(bodyPart) encoded.append(encodedData) } return encoded } // MARK: - Private - Body Part Encoding private func encode(_ bodyPart: BQBodyPart) throws -> Data { var encoded = Data() let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() encoded.append(initialData) let headerData = encodeHeaders(for: bodyPart) encoded.append(headerData) let bodyStreamData = try encodeBodyStream(for: bodyPart) encoded.append(bodyStreamData) if bodyPart.hasFinalBoundary { encoded.append(finalBoundaryData()) } return encoded } private func encodeHeaders(for bodyPart: BQBodyPart) -> Data { var headerText = "" for (key, value) in bodyPart.headers { headerText += "\(key): \(value)\(BQEncodingCharacters.crlf)" } headerText += BQEncodingCharacters.crlf return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! } private func encodeBodyStream(for bodyPart: BQBodyPart) throws -> Data { let inputStream = bodyPart.bodyStream inputStream.open() defer { inputStream.close() } var encoded = Data() while inputStream.hasBytesAvailable { var buffer = [UInt8](repeating: 0, count: streamBufferSize) let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) if let error = inputStream.streamError { throw error } if bytesRead > 0 { encoded.append(buffer, count: bytesRead) } else { break } } return encoded } // MARK: - Private - Mime Type private func mimeType(forPathExtension pathExtension: String) -> String { if let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() { return contentType as String } return "application/octet-stream" } // MARK: - Private - Content Headers private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { var disposition = "form-data; name=\"\(name)\"" if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } var headers = ["Content-Disposition": disposition] if let mimeType = mimeType { headers["Content-Type"] = mimeType } return headers } // MARK: - Private - Boundary Encoding private func initialBoundaryData() -> Data { return BQBoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) } private func encapsulatedBoundaryData() -> Data { return BQBoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) } private func finalBoundaryData() -> Data { return BQBoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) } }
apache-2.0
85615f4e4d0ed1bf24aa17061c9c4492
33.142241
142
0.610024
5.084082
false
false
false
false
arnaudbenard/npm-stats
Pods/Charts/Charts/Classes/Data/ChartData.swift
17
24532
// // ChartData.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartData: NSObject { internal var _yMax = Double(0.0) internal var _yMin = Double(0.0) internal var _leftAxisMax = Double(0.0) internal var _leftAxisMin = Double(0.0) internal var _rightAxisMax = Double(0.0) internal var _rightAxisMin = Double(0.0) private var _yValueSum = Double(0.0) private var _yValCount = Int(0) /// the last start value used for calcMinMax internal var _lastStart: Int = 0 /// the last end value used for calcMinMax internal var _lastEnd: Int = 0 /// the average length (in characters) across all x-value strings private var _xValAverageLength = Double(0.0) internal var _xVals: [String?]! internal var _dataSets: [ChartDataSet]! public override init() { super.init() _xVals = [String?]() _dataSets = [ChartDataSet]() } public init(xVals: [String?]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : xVals _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!) _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public convenience init(xVals: [String?]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [NSObject]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [String?]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } internal func initialize(dataSets: [ChartDataSet]) { checkIsLegal(dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueSum() calcYValueCount() calcXValAverageLength() } // calculates the average length (in characters) across all x-value strings internal func calcXValAverageLength() { if (_xVals.count == 0) { _xValAverageLength = 1 return } var sum = 1 for (var i = 0; i < _xVals.count; i++) { sum += _xVals[i] == nil ? 0 : count(_xVals[i]!) } _xValAverageLength = Double(sum) / Double(_xVals.count) } // Checks if the combination of x-values array and DataSet array is legal or not. // :param: dataSets internal func checkIsLegal(dataSets: [ChartDataSet]!) { if (dataSets == nil) { return } for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].yVals.count > _xVals.count) { println("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.") return } } } public func notifyDataChanged() { initialize(_dataSets) } /// calc minimum and maximum y value over all datasets internal func calcMinMax(#start: Int, end: Int) { if (_dataSets == nil || _dataSets.count < 1) { _yMax = 0.0 _yMin = 0.0 } else { _lastStart = start _lastEnd = end _yMin = DBL_MAX _yMax = -DBL_MAX for (var i = 0; i < _dataSets.count; i++) { _dataSets[i].calcMinMax(start: start, end: end) if (_dataSets[i].yMin < _yMin) { _yMin = _dataSets[i].yMin } if (_dataSets[i].yMax > _yMax) { _yMax = _dataSets[i].yMax } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } // left axis var firstLeft = getFirstLeft() if (firstLeft !== nil) { _leftAxisMax = firstLeft!.yMax _leftAxisMin = firstLeft!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { if (dataSet.yMin < _leftAxisMin) { _leftAxisMin = dataSet.yMin } if (dataSet.yMax > _leftAxisMax) { _leftAxisMax = dataSet.yMax } } } } // right axis var firstRight = getFirstRight() if (firstRight !== nil) { _rightAxisMax = firstRight!.yMax _rightAxisMin = firstRight!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { if (dataSet.yMin < _rightAxisMin) { _rightAxisMin = dataSet.yMin } if (dataSet.yMax > _rightAxisMax) { _rightAxisMax = dataSet.yMax } } } } // in case there is only one axis, adjust the second axis handleEmptyAxis(firstLeft, firstRight: firstRight) } } /// calculates the sum of all y-values in all datasets internal func calcYValueSum() { _yValueSum = 0 if (_dataSets == nil) { return } for (var i = 0; i < _dataSets.count; i++) { _yValueSum += fabs(_dataSets[i].yValueSum) } } /// Calculates the total number of y-values across all ChartDataSets the ChartData represents. internal func calcYValueCount() { _yValCount = 0 if (_dataSets == nil) { return } var count = 0 for (var i = 0; i < _dataSets.count; i++) { count += _dataSets[i].entryCount } _yValCount = count } /// returns the number of LineDataSets this object contains public var dataSetCount: Int { if (_dataSets == nil) { return 0 } return _dataSets.count } /// returns the smallest y-value the data object contains. public var yMin: Double { return _yMin } public func getYMin() -> Double { return _yMin } public func getYMin(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMin } else { return _rightAxisMin } } /// returns the greatest y-value the data object contains. public var yMax: Double { return _yMax } public func getYMax() -> Double { return _yMax } public func getYMax(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMax } else { return _rightAxisMax } } /// returns the average length (in characters) across all values in the x-vals array public var xValAverageLength: Double { return _xValAverageLength } /// returns the total y-value sum across all DataSet objects the this object represents. public var yValueSum: Double { return _yValueSum } /// Returns the total number of y-values across all DataSet objects the this object represents. public var yValCount: Int { return _yValCount } /// returns the x-values the chart represents public var xVals: [String?] { return _xVals } ///Adds a new x-value to the chart data. public func addXValue(xVal: String?) { _xVals.append(xVal) } /// Removes the x-value at the specified index. public func removeXValue(index: Int) { _xVals.removeAtIndex(index) } /// Returns the array of ChartDataSets this object holds. public var dataSets: [ChartDataSet] { get { return _dataSets } set { _dataSets = newValue } } /// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not. /// IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations. /// /// :param: dataSets the DataSet array to search /// :param: type /// :param: ignorecase if true, the search is not case-sensitive /// :returns: internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int { if (ignorecase) { for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].label == nil) { continue } if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame) { return i } } } else { for (var i = 0; i < dataSets.count; i++) { if (label == dataSets[i].label) { return i } } } return -1 } /// returns the total number of x-values this ChartData object represents (the size of the x-values array) public var xValCount: Int { return _xVals.count } /// Returns the labels of all DataSets as a string array. internal func dataSetLabels() -> [String] { var types = [String]() for (var i = 0; i < _dataSets.count; i++) { if (dataSets[i].label == nil) { continue } types[i] = _dataSets[i].label! } return types } /// Get the Entry for a corresponding highlight object /// /// :param: highlight /// :returns: the entry that is highlighted public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry? { return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex) } /// Returns the DataSet object with the given label. /// sensitive or not. /// IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations. /// /// :param: label /// :param: ignorecase public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet? { var index = getDataSetIndexByLabel(label, ignorecase: ignorecase) if (index < 0 || index >= _dataSets.count) { return nil } else { return _dataSets[index] } } public func getDataSetByIndex(index: Int) -> ChartDataSet! { if (_dataSets == nil || index < 0 || index >= _dataSets.count) { return nil } return _dataSets[index] } public func addDataSet(d: ChartDataSet!) { if (_dataSets == nil) { return } _yValCount += d.entryCount _yValueSum += d.yValueSum if (_dataSets.count == 0) { _yMax = d.yMax _yMin = d.yMin if (d.axisDependency == .Left) { _leftAxisMax = d.yMax _leftAxisMin = d.yMin } else { _rightAxisMax = d.yMax _rightAxisMin = d.yMin } } else { if (_yMax < d.yMax) { _yMax = d.yMax } if (_yMin > d.yMin) { _yMin = d.yMin } if (d.axisDependency == .Left) { if (_leftAxisMax < d.yMax) { _leftAxisMax = d.yMax } if (_leftAxisMin > d.yMin) { _leftAxisMin = d.yMin } } else { if (_rightAxisMax < d.yMax) { _rightAxisMax = d.yMax } if (_rightAxisMin > d.yMin) { _rightAxisMin = d.yMin } } } _dataSets.append(d) handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) } public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?) { // in case there is only one axis, adjust the second axis if (firstLeft === nil) { _leftAxisMax = _rightAxisMax _leftAxisMin = _rightAxisMin } else if (firstRight === nil) { _rightAxisMax = _leftAxisMax _rightAxisMin = _leftAxisMin } } /// Removes the given DataSet from this data object. /// Also recalculates all minimum and maximum values. /// /// :returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSet(dataSet: ChartDataSet!) -> Bool { if (_dataSets == nil || dataSet === nil) { return false } for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return removeDataSetByIndex(i) } } return false } /// Removes the DataSet at the given index in the DataSet array from the data object. /// Also recalculates all minimum and maximum values. /// /// :returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSetByIndex(index: Int) -> Bool { if (_dataSets == nil || index >= _dataSets.count || index < 0) { return false } var d = _dataSets.removeAtIndex(index) _yValCount -= d.entryCount _yValueSum -= d.yValueSum calcMinMax(start: _lastStart, end: _lastEnd) return true } /// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list. public func addEntry(e: ChartDataEntry, dataSetIndex: Int) { if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0) { var val = e.value var set = _dataSets[dataSetIndex] if (_yValCount == 0) { _yMin = val _yMax = val if (set.axisDependency == .Left) { _leftAxisMax = e.value _leftAxisMin = e.value } else { _rightAxisMax = e.value _rightAxisMin = e.value } } else { if (_yMax < val) { _yMax = val } if (_yMin > val) { _yMin = val } if (set.axisDependency == .Left) { if (_leftAxisMax < e.value) { _leftAxisMax = e.value } if (_leftAxisMin > e.value) { _leftAxisMin = e.value } } else { if (_rightAxisMax < e.value) { _rightAxisMax = e.value } if (_rightAxisMin > e.value) { _rightAxisMin = e.value } } } _yValCount += 1 _yValueSum += val handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) set.addEntry(e) } else { println("ChartData.addEntry() - dataSetIndex our of range.") } } /// Removes the given Entry object from the DataSet at the specified index. public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool { // entry null, outofbounds if (entry === nil || dataSetIndex >= _dataSets.count) { return false } // remove the entry from the dataset var removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex) if (removed) { var val = entry.value _yValCount -= 1 _yValueSum -= val calcMinMax(start: _lastStart, end: _lastEnd) } return removed } /// Removes the Entry object at the given xIndex from the ChartDataSet at the /// specified index. Returns true if an entry was removed, false if no Entry /// was found that meets the specified requirements. public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool { if (dataSetIndex >= _dataSets.count) { return false } var entry = _dataSets[dataSetIndex].entryForXIndex(xIndex) if (entry?.xIndex != xIndex) { return false } return removeEntry(entry, dataSetIndex: dataSetIndex) } /// Returns the DataSet that contains the provided Entry, or null, if no DataSet contains this entry. public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet? { if (e == nil) { return nil } for (var i = 0; i < _dataSets.count; i++) { var set = _dataSets[i] for (var j = 0; j < set.entryCount; j++) { if (e === set.entryForXIndex(e.xIndex)) { return set } } } return nil } /// Returns the index of the provided DataSet inside the DataSets array of /// this data object. Returns -1 if the DataSet was not found. public func indexOfDataSet(dataSet: ChartDataSet) -> Int { for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return i } } return -1 } public func getFirstLeft() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { return dataSet } } return nil } public func getFirstRight() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { return dataSet } } return nil } /// Returns all colors used across all DataSet objects this object represents. public func getColors() -> [UIColor]? { if (_dataSets == nil) { return nil } var clrcnt = 0 for (var i = 0; i < _dataSets.count; i++) { clrcnt += _dataSets[i].colors.count } var colors = [UIColor]() for (var i = 0; i < _dataSets.count; i++) { var clrs = _dataSets[i].colors for clr in clrs { colors.append(clr) } } return colors } /// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience. public func generateXVals(from: Int, to: Int) -> [String] { var xvals = [String]() for (var i = from; i < to; i++) { xvals.append(String(i)) } return xvals } /// Sets a custom ValueFormatter for all DataSets this data object contains. public func setValueFormatter(formatter: NSNumberFormatter!) { for set in dataSets { set.valueFormatter = formatter } } /// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains. public func setValueTextColor(color: UIColor!) { for set in dataSets { set.valueTextColor = color ?? set.valueTextColor } } /// Sets the font for all value-labels for all DataSets this data object contains. public func setValueFont(font: UIFont!) { for set in dataSets { set.valueFont = font ?? set.valueFont } } /// Enables / disables drawing values (value-text) for all DataSets this data object contains. public func setDrawValues(enabled: Bool) { for set in dataSets { set.drawValuesEnabled = enabled } } /// Enables / disables highlighting values for all DataSets this data object contains. public var highlightEnabled: Bool { get { for set in dataSets { if (!set.highlightEnabled) { return false } } return true } set { for set in dataSets { set.highlightEnabled = newValue } } } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled } /// Clears this data object from all DataSets and removes all Entries. /// Don't forget to invalidate the chart after this. public func clearValues() { dataSets.removeAll(keepCapacity: false) notifyDataChanged() } /// Checks if this data object contains the specified Entry. Returns true if so, false if not. public func contains(#entry: ChartDataEntry) -> Bool { for set in dataSets { if (set.contains(entry)) { return true } } return false } /// Checks if this data object contains the specified DataSet. Returns true if so, false if not. public func contains(#dataSet: ChartDataSet) -> Bool { for set in dataSets { if (set.isEqual(dataSet)) { return true } } return false } /// MARK: - ObjC compatibility /// returns the average length (in characters) across all values in the x-vals array public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); } }
mit
49c39d4aa91ae16d3cb6b47c64d96cc3
25.435345
128
0.473015
5.220685
false
false
false
false
brentdax/SQLKit
Sources/SQLKit/SQLQuery.swift
1
9635
// // SQLQuery.swift // LittlinkRouterPerfect // // Created by Brent Royal-Gordon on 10/30/16. // // /// Represents the results of a query. /// /// A `SQLQuery` has two purposes. One is to access the instances representing /// each row (`SQLRow`) returned by the query. The other is to create the column /// keys (`SQLColumnKey`) used to access columns in those rows. /// /// `SQLQuery` is only guaranteed to be a `Sequence`, so you may only be able to /// enumerate the rows returned by a query once. However, some clients return a /// `Collection`, `BidirectionalCollection`, or `RandomAccessCollection`; if they /// do, `SQLQuery` will support those additional protocols. /// /// - Note: Due to language limitations, `Collection`s are handled by variant types, /// such as `SQLQueryCollection`. These present identical interfaces to /// `SQLQuery`, but add additional conformances. // // WORKAROUND: #1 Swift doesn't support `where` clauses on associated types public struct SQLQuery<Client: SQLClient> where Client.RowStateSequence.Iterator.Element == Client.RowState { /// The statement executed to create this query. public let statement: SQLStatement /// The state object backing this instance. State objects are client-specific, /// and some clients may expose low-level data structures through the state /// object. public var state: Client.QueryState /// The sequence of state objects which will be used to create the `SQLRow`s /// returned by iterating over the query. public var rowStates: Client.RowStateSequence /// Provides access to the rows returned by the query. /// /// Like all iterators, `rowIterator` is single-pass—the rows in the sequence /// are consumed as they're read. Unlike most iterators, `rowIterator` is also /// a `Sequence`; it can be used in a `for` loop or with `map(_:)`. /// /// Some SQL clients allow you to make multiple passes through the rows or /// move back and forth through them. Queries on clients which support these /// features include a `rows` property. /// /// - SeeAlso: `rows`, `onlyRow()` public let rowIterator: SQLRowIterator<Client> /// Returns the only row in the result set. /// /// - Throws: If there are no rows or more than one row. /// /// - SeeAlso: `rowIterator`, `onlyRow()` public func onlyRow() throws -> SQLRow<Client> { guard let oneRow = rowIterator.next() else { throw SQLError.noRecordsFound(statement: statement) } guard rowIterator.next() == nil else { throw SQLError.extraRecordsFound(statement: statement) } return oneRow } init(statement: SQLStatement, state: Client.QueryState) { self.statement = statement self.state = state self.rowStates = Client.makeRowStateSequence(with: state) self.rowIterator = SQLRowIterator(statement: statement, rowStateIterator: rowStates.makeIterator()) } /// Returns a key for a column with the given name and type. /// /// - Parameter name: The name of the column. This may be case-sensitive. /// - Parameter valueType: The type of the column's value. Must conform to /// `SQLValue` or be an `Optional` of a type conforming to /// `SQLValue`. /// /// - Throws: If the column doesn't exist or possibly if it's the wrong type. /// /// - Note: If `valueType` is not an `Optional` type, then accessing the column's /// value will throw an error. public func columnKey<Value: SQLValue>(forName name: String, as valueType: Value.Type) throws -> SQLColumnKey<Value> { return try withErrorsPackaged(in: SQLError.makeColumnInvalid(with: statement, for: .name(name))) { guard let index = try Client.columnIndex(forName: name, as: valueType, with: state) else { throw SQLColumnError.columnMissing } return SQLColumnKey(index: index, name: name) } } /// Returns a key for a column at the given index and with the given type. /// /// - Parameter index: The zero-based index of the column in the row. /// - Parameter valueType: The type of the column's value. Must conform to /// `SQLValue` or be an `Optional` of a type conforming to /// `SQLValue`. /// /// - Throws: If the column doesn't exist or possibly if it's the wrong type. /// /// - Note: If `valueType` is not an Optional type, then accessing the column's /// value will throw an error. public func columnKey<Value: SQLValue>(at index: Int, as valueType: Value.Type) throws -> SQLColumnKey<Value> { return try withErrorsPackaged(in: SQLError.makeColumnInvalid(with: statement, for: .index(index))) { guard let name = try Client.columnName(at: index, as: valueType, with: state) else { throw SQLColumnError.columnMissing } return SQLColumnKey(index: index, name: name) } } /// The number of rows returned by the query. /// /// - Note: Although normally using `count` consumes a `Sequence`, it does not /// do so for a `SQLQuery`, so it's safe to call `count` even if the /// client otherwise doesn't support iterating over a query's rows more /// than once. public var count: Int { return Client.count(with: state) } /// Returns a key for a column with the given name and type. /// /// - Parameter name: The name of the column. This may be case-sensitive. /// - Parameter valueType: The type of the column's value. Must conform to /// `SQLValue` or be an `Optional` of a type conforming to /// `SQLValue`. /// /// - Throws: If the column doesn't exist or possibly if it's the wrong type. /// /// - Note: If `valueType` is not an Optional type, then accessing the column's /// value will throw an error. public func columnKey<Value: SQLValue>(forName name: String, as valueType: Value?.Type) throws -> SQLNullableColumnKey<Value> { let nonnull = try columnKey(forName: name, as: Value.self) return SQLNullableColumnKey(nonnull) } /// Returns a key for a column at the given index and with the given type. /// /// - Parameter index: The zero-based index of the column in the row. /// - Parameter valueType: The type of the column's value. Must conform to /// `SQLValue` or be an `Optional` of a type conforming to /// `SQLValue`. /// /// - Throws: If the column doesn't exist or possibly if it's the wrong type. /// /// - Note: If `valueType` is not an Optional type, then accessing the column's /// value will throw an error. public func columnKey<Value: SQLValue>(at index: Int, as valueType: Value?.Type) throws -> SQLNullableColumnKey<Value> { let nonnull = try columnKey(at: index, as: Value.self) return SQLNullableColumnKey(nonnull) } } extension SQLQuery where Client.RowStateSequence: Collection { /// The rows returned by the query. /// /// `rows` is a `Collection`, so it may be indexed and walked through several /// times. Depending on the client, it may also be a `BidirectionalCollection` /// (allowing walking backwards) or a `RandomAccessCollection` (allowing /// walking to any arbitrary index). /// /// If a particular client does not support the `rows` property, you can /// greedily fetch all rows into an array by writing: /// /// let array = Array(myQuery.rowIterator) /// /// - SeeAlso: `rowIterator`, `onlyRow()` public var rows: SQLRowCollection<Client> { return .init(rowStates: rowStates, statement: statement) } } extension SQLQuery where Client.RowStateSequence: BidirectionalCollection { /// The rows returned by the query. /// /// `rows` is a `Collection`, so it may be indexed and walked through several /// times. Depending on the client, it may also be a `BidirectionalCollection` /// (allowing walking backwards) or a `RandomAccessCollection` (allowing /// walking to any arbitrary index). /// /// If a particular client does not support the `rows` property, you can /// greedily fetch all rows into an array by writing: /// /// let array = Array(myQuery.rowIterator) /// /// - SeeAlso: `rowIterator`, `onlyRow()` public var rows: SQLRowBidirectionalCollection<Client> { return .init(rowStates: rowStates, statement: statement) } } extension SQLQuery where Client.RowStateSequence: RandomAccessCollection { /// The rows returned by the query. /// /// `rows` is a `Collection`, so it may be indexed and walked through several /// times. Depending on the client, it may also be a `BidirectionalCollection` /// (allowing walking backwards) or a `RandomAccessCollection` (allowing /// walking to any arbitrary index). /// /// If a particular client does not support the `rows` property, you can /// greedily fetch all rows into an array by writing: /// /// let array = Array(myQuery.rowIterator) /// /// - SeeAlso: `rowIterator`, `onlyRow()` public var rows: SQLRowRandomAccessCollection<Client> { return .init(rowStates: rowStates, statement: statement) } }
mit
42cf6959feeb1cfe5a94f66c60523526
44.654028
131
0.640299
4.376647
false
false
false
false
pinterest/plank
Sources/Core/ObjectiveCEqualityExtension.swift
1
6792
// // ObjectiveCEqualityExtension.swift // plank // // Created by Rahul Malik on 2/14/17. // // import Foundation extension ObjCFileRenderer { // MARK: Hash Method - Inspired from Mike Ash article on Equality / Hashing // https://www.mikeash.com/pyblog/friday-qa-2010-06-18-implementing-equality-and-hashing.html func renderHash(_ booleanIVarName: String = "") -> ObjCIR.Method { func schemaHashStatement(with param: Parameter, for schema: Schema) -> String { switch schema { case .enumT, .integer: // - The value equality statement is sufficient for equality testing // - All enum types are treated as Integers so we do not need to treat String Enumerations differently return "(NSUInteger)_\(param)" case .float: return " [@(_\(param)) hash]" case .boolean: // Values 1231 for true and 1237 for false are adopted from the Java hashCode specification // http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#hashCode return !booleanIVarName.isEmpty ? "(_\(booleanIVarName).\(booleanPropertyOption(propertyName: param, className: className)) ? 1231 : 1237)" : "(_\(param) ? 1231 : 1237)" case let .reference(with: ref): switch ref.force() { case let .some(.object(schemaRoot)): return schemaHashStatement(with: param, for: .object(schemaRoot)) default: fatalError("Bad reference found for schema parameter: \(param)") } default: return "[_\(param) hash]" } } let rootHashStatement = isBaseClass ? ["17"] : ["[super hash]"] let propReturnStatements = rootHashStatement + properties.map { param, prop -> String in let formattedParam = Languages.objectiveC.snakeCaseToPropertyName(param) return schemaHashStatement(with: formattedParam, for: prop.schema) } return ObjCIR.method("- (NSUInteger)hash") { [ "NSUInteger subhashes[] = {", -->[propReturnStatements.joined(separator: ",\n")], "};", "return PINIntegerArrayHash(subhashes, sizeof(subhashes) / sizeof(subhashes[0]));", ] } } // MARK: Equality Methods inspired from NSHipster article on Equality: http://nshipster.com/equality/ func renderIsEqualToClass(_ booleanIVarName: String = "") -> ObjCIR.Method { func schemaIsEqualStatement(with param: Parameter, for schema: Schema) -> String { switch schema { case .integer, .float, .enumT, .boolean: // - The value equality statement is sufficient for equality testing // - All enum types are treated as Integers so we do not need to treat String Enumerations differently return "" case .array: return ObjCIR.msg("_\(param)", ("isEqualToArray", "anObject.\(param)")) case .set: return ObjCIR.msg("_\(param)", ("isEqualToSet", "anObject.\(param)")) case .map: return ObjCIR.msg("_\(param)", ("isEqualToDictionary", "anObject.\(param)")) case .string(format: .some(.dateTime)): return ObjCIR.msg("_\(param)", ("isEqualToDate", "anObject.\(param)")) case .string(format: .none), .string(format: .some(.email)), .string(format: .some(.hostname)), .string(format: .some(.ipv4)), .string(format: .some(.ipv6)): return ObjCIR.msg("_\(param)", ("isEqualToString", "anObject.\(param)")) case .oneOf(types: _), .object, .string(format: .some(.uri)): return ObjCIR.msg("_\(param)", ("isEqual", "anObject.\(param)")) case let .reference(with: ref): switch ref.force() { case let .some(.object(schemaRoot)): return schemaIsEqualStatement(with: param, for: .object(schemaRoot)) default: fatalError("Bad reference found for schema parameter: \(param)") } } } // Performance optimization - compare primitives before resorting to more expensive `isEqual` calls let sortedProps = properties.sorted { arg1, _ in arg1.1.schema.isPrimitiveType } let propReturnStmts = sortedProps.map { param, prop -> String in let formattedParam = Languages.objectiveC.snakeCaseToPropertyName(param) switch prop.schema { case .boolean: if booleanIVarName.isEmpty { fallthrough } else { return "_\(booleanIVarName).\(booleanPropertyOption(propertyName: param, className: self.className)) == anObject.\(formattedParam)" } default: let pointerEqStmt = "_\(formattedParam) == anObject.\(formattedParam)" let deepEqStmt = schemaIsEqualStatement(with: formattedParam, for: prop.schema) return [pointerEqStmt, deepEqStmt].filter { $0 != "" }.joined(separator: " || ") } } func parentName(_ schema: Schema?) -> String? { switch schema { case let .some(.object(root)): return root.className(with: GenerationParameters()) case let .some(.reference(with: ref)): return parentName(ref.force()) default: return nil } } let superInvocation = parentName(parentDescriptor).map { ["[super isEqualTo\($0):anObject]"] } ?? [] return ObjCIR.method("- (BOOL)isEqualTo\(Languages.objectiveC.snakeCaseToCamelCase(rootSchema.name)):(\(className) *)anObject") { [ "return (", -->[(["anObject != nil"] + superInvocation + propReturnStmts) .map { "(\($0))" }.joined(separator: " &&\n")], ");", ] } } func renderIsEqual() -> ObjCIR.Method { return ObjCIR.method("- (BOOL)isEqual:(id)anObject") { [ ObjCIR.ifStmt("self == anObject") { ["return YES;"] }, self.isBaseClass ? "" : ObjCIR.ifStmt("[super isEqual:anObject] == NO") { ["return NO;"] }, ObjCIR.ifStmt("[anObject isKindOfClass:[\(self.className) class]] == NO") { ["return NO;"] }, "return [self isEqualTo\(Languages.objectiveC.snakeCaseToCamelCase(self.rootSchema.name)):anObject];", ].filter { $0 != "" } } } }
apache-2.0
83c6daf078c55fd570dfd0c541a4ef6d
46.166667
151
0.553004
4.642515
false
false
false
false
OldBulls/swift-weibo
ZNWeibo/ZNWeibo/Classes/Main/OAuth/OAuthViewController.swift
1
5778
// // OAuthViewController.swift // ZNWeibo // // Created by 臻牛 on 2016/7/9. // Copyright © 2016年 zn. All rights reserved. // import UIKit import SVProgressHUD class OAuthViewController: UIViewController { // MARK:- 控件的属性 @IBOutlet weak var webView: UIWebView! // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 1.设置导航栏的内容 setupNavigationBar() // 2.加载网页 loadPage() } } // MARK:- 设置UI界面相关 extension OAuthViewController { private func setupNavigationBar() { // 1.设置左侧的item navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(OAuthViewController.closeItemClick)) // 2.设置右侧的item navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: #selector(OAuthViewController.fillItemClick)) // 3.设置标题 title = "登录页面" } private func loadPage() { // 1.获取登录页面的URLString let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)" // 2.创建对应NSURL guard let url = NSURL(string: urlString) else { return } // 3.创建NSURLRequest对象 let request = NSURLRequest(URL: url) // 4.加载request对象 webView.loadRequest(request) webView.accessibilityLabel = "123" } } // MARK:- 事件监听函数 extension OAuthViewController { @objc private func closeItemClick() { dismissViewControllerAnimated(true, completion: nil) } @objc private func fillItemClick() { // 1.书写js代码 : javascript / java --> 雷锋和雷峰塔 let jsCode = "document.getElementById('userId').value='18622612126';document.getElementById('passwd').value='zhenniu212';" // 2.执行js代码 webView.stringByEvaluatingJavaScriptFromString(jsCode) } } // MARK:- webView的delegate方法 extension OAuthViewController : UIWebViewDelegate { // webView开始加载网页 func webViewDidStartLoad(webView: UIWebView) { SVProgressHUD.show() } // webView网页加载完成 func webViewDidFinishLoad(webView: UIWebView) { SVProgressHUD.dismiss() } // webView加载网页失败 func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { SVProgressHUD.dismiss() } // 当准备加载某一个页面时,会执行该方法 // 返回值: true -> 继续加载该页面 false -> 不会加载该页面 func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { // 1.获取加载网页的NSURL guard let url = request.URL else { return true } // 2.获取url中的字符串 let urlString = url.absoluteString // 3.判断该字符串中是否包含code guard urlString.containsString("code=") else { return true } // 4.将code截取出来 let code = urlString.componentsSeparatedByString("code=").last! ZNLog(code) //5.请求accessToken loadAccessToken(code) return false } } extension OAuthViewController { ///请求accessToken private func loadAccessToken(code : String) { NetworkTools.shareInstance.loadAccessToken(code) { (result, error) in //1.错误检查 if error != nil { ZNLog(error) return } //2.拿到结果 guard let accountDict = result else { ZNLog("没有获取授权后的结果") return } //3.字典转模型 let account = UserAccount(dict: accountDict) ZNLog("转换成的模型数据 :\(account)") //4.请求用户信息 self.loadUserInfo(account) } } private func loadUserInfo(account : UserAccount) { guard let accessToken = account.access_token else { return } guard let uid = account.uid else { return } NetworkTools.shareInstance.loadUsserInfo(accessToken, uid: uid) { (result, error) in //1.错误校验 if error != nil { ZNLog(error) return } //2.拿到用户信息的结果 guard let userInfoDict = result else { return } //3.从字典中取出头像和昵称地址 account.screen_name = userInfoDict["screen_name"] as? String account.avatar_large = userInfoDict["avatar_large"] as? String //4.将account对象保存 //获取沙盒路径 //5.保存对象 NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.shareIntance.accountPath) //更新数据 UserAccountViewModel.shareIntance.account = account //6.显示欢迎界面 self.dismissViewControllerAnimated(false, completion: { UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController() }) } } }
mit
7b3165d7d979d84c3bf06ec829a3f7e4
25.984536
155
0.558739
4.934025
false
false
false
false
iOS-Swift-Developers/Swift
实战前技术点/13.Client客户端/Pods/ProtocolBuffers-Swift/Source/UnknownFieldSet.swift
20
12390
// Protocol Buffers for Swift // // Copyright 2014 Alexey Khohklov(AlexeyXo). // Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation public func == (lhs: UnknownFieldSet, rhs: UnknownFieldSet) -> Bool { return lhs.fields == rhs.fields } public class UnknownFieldSet:Hashable,Equatable { public var fields:Dictionary<Int32,Field> convenience public init() { self.init(fields: Dictionary()) } public init(fields:Dictionary<Int32,Field>) { self.fields = fields } public var hashValue:Int { get { var hashCode:Int = 0 for value in fields.values { hashCode = (hashCode &* 31) &+ value.hashValue } return hashCode } } public func hasField(number:Int32) -> Bool { guard fields[number] != nil else { return false } return true } public func getField(number:Int32) -> Field { if let field = fields[number] { return field } return Field() } public func writeTo(codedOutputStream:CodedOutputStream) throws { var sortedKeys = Array(fields.keys) sortedKeys.sort(by: { $0 < $1 }) for number in sortedKeys { let value:Field = fields[number]! try value.writeTo(fieldNumber: number, output: codedOutputStream) } } public func writeTo(outputStream:OutputStream) throws { let codedOutput:CodedOutputStream = CodedOutputStream(stream: outputStream) try writeTo(codedOutputStream: codedOutput) try codedOutput.flush() } public func getDescription(indent:String) -> String { var output = "" var sortedKeys = Array(fields.keys) sortedKeys.sort(by: { $0 < $1 }) for number in sortedKeys { let value:Field = fields[number]! output += value.getDescription(fieldNumber: number, indent: indent) } return output } public class func builder() -> UnknownFieldSet.Builder { return UnknownFieldSet.Builder() } public class func parseFrom(codedInputStream:CodedInputStream) throws -> UnknownFieldSet { return try UnknownFieldSet.Builder().mergeFrom(codedInputStream: codedInputStream).build() } public class func parseFrom(data:Data) throws -> UnknownFieldSet { return try UnknownFieldSet.Builder().mergeFrom(data: data).build() } public class func parseFrom(inputStream:InputStream) throws -> UnknownFieldSet { return try UnknownFieldSet.Builder().mergeFrom(inputStream: inputStream).build() } public class func builderWithUnknownFields(copyFrom:UnknownFieldSet) throws -> UnknownFieldSet.Builder { return try UnknownFieldSet.Builder().merge(unknownFields: copyFrom) } public func serializedSize()->Int32 { var result:Int32 = 0 for number in fields.keys { let field:Field = fields[number]! result += field.getSerializedSize(fieldNumber: number) } return result } public func writeAsMessageSetTo(codedOutputStream:CodedOutputStream) throws { for number in fields.keys { let field:Field = fields[number]! try field.writeAsMessageSetExtensionTo(fieldNumber: number, codedOutputStream:codedOutputStream) } } public func serializedSizeAsMessageSet() -> Int32 { var result:Int32 = 0 for number in fields.keys { let field:Field = fields[number]! result += field.getSerializedSizeAsMessageSetExtension(fieldNumber: number) } return result } public func data() throws -> Data { let size = serializedSize() let data = Data(bytes: [0], count: Int(size)) let stream:CodedOutputStream = CodedOutputStream(data: data) try writeTo(codedOutputStream: stream) return Data(bytes: stream.buffer.buffer, count: Int(size)) } public class Builder { private var fields:Dictionary<Int32,Field> private var lastFieldNumber:Int32 private var lastField:Field? public init() { fields = Dictionary() lastFieldNumber = 0 } @discardableResult public func addField(field:Field, number:Int32) throws -> UnknownFieldSet.Builder { guard number != 0 else { throw ProtocolBuffersError.illegalArgument("Illegal Field Number") } if (lastField != nil && lastFieldNumber == number) { lastField = nil lastFieldNumber = 0 } fields[number]=field return self } public func getFieldBuilder(number:Int32) throws -> Field? { if (lastField != nil) { if (number == lastFieldNumber) { return lastField } _ = try addField(field: lastField!, number:lastFieldNumber) } if (number == 0) { return nil } else { let existing = fields[number] lastFieldNumber = number lastField = Field() if (existing != nil) { _ = lastField?.mergeFromField(other: existing!) } return lastField } } public func build() throws -> UnknownFieldSet { _ = try getFieldBuilder(number: 0) var result:UnknownFieldSet if (fields.count == 0) { result = UnknownFieldSet(fields: Dictionary()) } else { result = UnknownFieldSet(fields: fields) } fields.removeAll(keepingCapacity: false) return result } public func buildPartial() throws -> UnknownFieldSet? { throw ProtocolBuffersError.obvious("UnsupportedMethod") } public func clone() throws -> UnknownFieldSet? { throw ProtocolBuffersError.obvious("UnsupportedMethod") } public func isInitialized() -> Bool { return true } public func unknownFields() throws -> UnknownFieldSet { return try build() } public func setUnknownFields(unknownFields:UnknownFieldSet) throws -> UnknownFieldSet.Builder? { throw ProtocolBuffersError.obvious("UnsupportedMethod") } public func hasField(number:Int32) throws -> Bool { guard number != 0 else { throw ProtocolBuffersError.illegalArgument("Illegal Field Number") } return number == lastFieldNumber || (fields[number] != nil) } @discardableResult public func mergeField(field:Field, number:Int32) throws -> UnknownFieldSet.Builder { guard number != 0 else { throw ProtocolBuffersError.illegalArgument("Illegal Field Number") } if (try hasField(number: number)) { _ = try getFieldBuilder(number: number)?.mergeFromField(other: field) } else { _ = try addField(field: field, number:number) } return self } @discardableResult public func merge(unknownFields:UnknownFieldSet) throws -> UnknownFieldSet.Builder { for number in unknownFields.fields.keys { let field:Field = unknownFields.fields[number]! _ = try mergeField(field: field ,number:number) } return self } @discardableResult public func mergeFrom(data:Data) throws -> UnknownFieldSet.Builder { let input:CodedInputStream = CodedInputStream(data: data) try mergeFrom(codedInputStream: input) try input.checkLastTagWas(value: 0) return self } public func mergeFrom(inputStream:InputStream) throws -> UnknownFieldSet.Builder { throw ProtocolBuffersError.obvious("UnsupportedMethod") } public func mergeFrom(inputStream:InputStream, extensionRegistry:ExtensionRegistry) throws -> UnknownFieldSet.Builder { throw ProtocolBuffersError.obvious("UnsupportedMethod") } @discardableResult public func mergeVarintField(fieldNumber:Int32, value:Int64) throws -> UnknownFieldSet.Builder { guard fieldNumber != 0 else { throw ProtocolBuffersError.illegalArgument("Illegal Field Number: Zero is not a valid field number.") } try getFieldBuilder(number: fieldNumber)?.variantArray.append(value) return self } @discardableResult public func mergeFieldFrom(tag:Int32, input:CodedInputStream) throws -> Bool { let number = WireFormat.getTagFieldNumber(tag: tag) let tags = WireFormat.getTagWireType(tag: tag) guard let format = WireFormat(rawValue: tags) else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Wire Type") } switch format { case .varint: try getFieldBuilder(number: number)?.variantArray.append(try input.readInt64()) return true case .fixed32: let value = try input.readFixed32() try getFieldBuilder(number: number)?.fixed32Array.append(value) return true case .fixed64: let value = try input.readFixed64() try getFieldBuilder(number: number)?.fixed64Array.append(value) return true case .lengthDelimited: try getFieldBuilder(number: number)?.lengthDelimited.append(try input.readData()) return true case .startGroup: let subBuilder:UnknownFieldSet.Builder = UnknownFieldSet.Builder() try input.readUnknownGroup(fieldNumber: number, builder:subBuilder) try getFieldBuilder(number: number)?.groupArray.append(subBuilder.build()) return true case .endGroup: return false default: throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Wire Type") } } @discardableResult public func mergeFrom(codedInputStream:CodedInputStream) throws -> UnknownFieldSet.Builder { while (true) { let tag:Int32 = try codedInputStream.readTag() let mergeField = try mergeFieldFrom(tag: tag, input:codedInputStream) if tag == 0 || !(mergeField) { break } } return self } public func mergeFrom(codedInputStream:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> UnknownFieldSet.Builder { throw ProtocolBuffersError.obvious("UnsupportedMethod") } @discardableResult public func mergeFrom(data:Data, extensionRegistry:ExtensionRegistry) throws -> UnknownFieldSet.Builder { let input = CodedInputStream(data: data) _ = try mergeFrom(codedInputStream:input, extensionRegistry:extensionRegistry) try input.checkLastTagWas(value: 0) return self } @discardableResult public func clear() ->UnknownFieldSet.Builder { fields = Dictionary() lastFieldNumber = 0 lastField = nil return self } } }
mit
c256ce5028637df294589c652e68d392
36.77439
137
0.591606
5.45815
false
false
false
false
TheInfiniteKind/duckduckgo-iOS
DuckDuckGo/MainViewController.swift
1
12859
// // MainViewController.swift // DuckDuckGo // // Created by Mia Alexiou on 24/01/2017. // Copyright © 2017 DuckDuckGo. All rights reserved. // import UIKit import WebKit import Core class MainViewController: UIViewController { @IBOutlet weak var containerView: UIView! @IBOutlet weak var tabsButton: UIBarButtonItem! @IBOutlet weak var shareButton: UIBarButtonItem! @IBOutlet weak var backButton: UIBarButtonItem! @IBOutlet weak var forwardButton: UIBarButtonItem! fileprivate var autocompleteController: AutocompleteViewController? fileprivate lazy var groupData = GroupDataStore() fileprivate lazy var tabManager = TabManager() weak var omniBar: OmniBar? fileprivate var currentTab: Tab? { return tabManager.current } override func viewDidLoad() { super.viewDidLoad() launchTab(active: false) } override func viewDidLayoutSubviews() { updateAutocompleteSize() } func loadQueryInNewWebTab(query: String) { if let url = AppUrls.url(forQuery: query, filters: groupData) { loadUrlInNewWebTab(url: url) } } func loadUrlInNewWebTab(url: URL) { loadViewIfNeeded() if let homeTab = currentTab as? HomeTabViewController { tabManager.remove(tab: homeTab) } currentTab?.dismiss() attachWebTab(forUrl: url) refreshControls() } fileprivate func loadQueryInCurrentTab(query: String) { if let queryUrl = AppUrls.url(forQuery: query, filters: groupData) { loadUrlInCurrentTab(url: queryUrl) } } fileprivate func loadUrlInCurrentTab(url: URL) { currentTab?.load(url: url) } fileprivate func launchTab(active: Bool? = nil) { let active = active ?? true attachHomeTab(active: active) refreshControls() } fileprivate func launchTabFrom(webTab: WebTabViewController, forUrl url: URL) { launchTabFrom(webTab: webTab, forUrlRequest: URLRequest(url: url)) } fileprivate func launchTabFrom(webTab: WebTabViewController, forUrlRequest urlRequest: URLRequest) { refreshTabIcon(count: tabManager.count+1) attachSiblingWebTab(fromWebView: webTab.webView, forUrlRequest: urlRequest) refreshControls() } private func attachHomeTab(active: Bool = false) { let tab = HomeTabViewController.loadFromStoryboard() tabManager.add(tab: tab) tab.tabDelegate = self addToView(tab: tab) if active { tab.enterActiveMode() } } private func attachWebTab(forUrl url: URL) { let tab = WebTabViewController.loadFromStoryboard() tabManager.add(tab: tab) tab.tabDelegate = self tab.load(url: url) addToView(tab: tab) } private func attachSiblingWebTab(fromWebView webView: WKWebView, forUrlRequest urlRequest: URLRequest) { let tab = WebTabViewController.loadFromStoryboard() tab.attachWebView(newWebView: webView.createSiblingWebView()) tab.tabDelegate = self tabManager.add(tab: tab) tab.load(urlRequest: urlRequest) addToView(tab: tab) } private func addToView(tab: UIViewController) { if let tab = tab as? Tab { resetOmniBar(withStyle: tab.omniBarStyle) } tab.view.frame = containerView.frame tab.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] addChildViewController(tab) containerView.addSubview(tab.view) } fileprivate func select(tabAt index: Int) { let selectedTab = tabManager.select(tabAt: index) as! UIViewController addToView(tab: selectedTab) refreshControls() } fileprivate func remove(tabAt index: Int) { tabManager.remove(at: index) if tabManager.isEmpty { return } if let lastIndex = tabManager.lastIndex, index > lastIndex { select(tabAt: lastIndex) return } select(tabAt: index) } fileprivate func clearAllTabs() { tabManager.clearAll() launchTab(active: false) } private func resetOmniBar(withStyle style: OmniBar.Style) { if omniBar?.style == style { return } let omniBarText = omniBar?.textField.text omniBar = OmniBar.loadFromXib(withStyle: style) omniBar?.textField.text = omniBarText omniBar?.omniDelegate = self navigationItem.titleView = omniBar } fileprivate func refreshControls() { refreshOmniText() refreshTabIcon() refreshNavigationButtons() refreshShareButton() } private func refreshTabIcon() { refreshTabIcon(count: tabManager.count) } private func refreshTabIcon(count: Int) { tabsButton.image = TabIconMaker().icon(forTabs: count) } private func refreshNavigationButtons() { backButton.isEnabled = currentTab?.canGoBack ?? false forwardButton.isEnabled = currentTab?.canGoForward ?? false } private func refreshShareButton() { shareButton.isEnabled = currentTab?.canShare ?? false } private func refreshOmniText() { guard let tab = currentTab else { return } if tab.showsUrlInOmniBar { omniBar?.refreshText(forUrl: tab.url) } else { omniBar?.clear() } } fileprivate func updateOmniBar(withQuery updatedQuery: String) { displayAutocompleteSuggestions(forQuery: updatedQuery) } private func displayAutocompleteSuggestions(forQuery query: String) { if autocompleteController == nil { let controller = AutocompleteViewController.loadFromStoryboard() controller.delegate = self addChildViewController(controller) containerView.addSubview(controller.view) autocompleteController = controller updateAutocompleteSize() } guard let autocompleteController = autocompleteController else { return } autocompleteController.updateQuery(query: query) } private func updateAutocompleteSize() { if let omniBarWidth = omniBar?.frame.width, let autocompleteController = autocompleteController { autocompleteController.widthConstraint.constant = omniBarWidth } } fileprivate func dismissOmniBar() { omniBar?.resignFirstResponder() dismissAutcompleteSuggestions() refreshOmniText() currentTab?.omniBarWasDismissed() } private func dismissAutcompleteSuggestions() { guard let controller = autocompleteController else { return } autocompleteController = nil controller.view.removeFromSuperview() controller.removeFromParentViewController() } @IBAction func onBackPressed(_ sender: UIBarButtonItem) { currentTab?.goBack() } @IBAction func onForwardPressed(_ sender: UIBarButtonItem) { currentTab?.goForward() } @IBAction func onSharePressed(_ sender: UIBarButtonItem) { if let url = currentTab?.url { let title = currentTab?.name ?? "" var items: [Any] = [url, title] if let favicon = currentTab?.favicon { items.append(favicon) } presentShareSheet(withItems: items, fromButtonItem: sender) } } @IBAction func onSaveBookmark(_ sender: UIBarButtonItem) { if let link = currentTab?.link { groupData.addBookmark(link) makeToast(text: UserText.webSaveLinkDone) } } @IBAction func onTabButtonPressed(_ sender: UIBarButtonItem) { launchTabSwitcher() } fileprivate func launchTabSwitcher() { let controller = TabSwitcherViewController.loadFromStoryboard(delegate: self) controller.transitioningDelegate = self controller.modalPresentationStyle = .overCurrentContext present(controller, animated: true, completion: nil) } @IBAction func onBookmarksButtonPressed(_ sender: UIBarButtonItem) { launchBookmarks() } fileprivate func launchBookmarks() { let controller = BookmarksViewController.loadFromStoryboard(delegate: self) controller.modalPresentationStyle = .overCurrentContext controller.modalTransitionStyle = .crossDissolve present(controller, animated: true, completion: nil) } private func makeToast(text: String) { let x = view.bounds.size.width / 2.0 let y = view.bounds.size.height - 80 view.makeToast(text, duration: ToastManager.shared.duration, position: CGPoint(x: x, y: y)) } } extension MainViewController: OmniBarDelegate { func onOmniQueryUpdated(_ updatedQuery: String) { updateOmniBar(withQuery: updatedQuery) } func onOmniQuerySubmitted(_ query: String) { dismissOmniBar() loadQueryInCurrentTab(query: query) } func onFireButtonPressed() { dismissOmniBar() if let current = currentTab, let index = tabManager.indexOf(tab: current) { remove(tabAt: index) } if groupData.omniFireOpensNewTab { launchTab() } else { launchTabSwitcher() } } func onBookmarksButtonPressed() { launchBookmarks() } func onRefreshButtonPressed() { currentTab?.reload() } func onDismissButtonPressed() { dismissOmniBar() } } extension MainViewController: AutocompleteViewControllerDelegate { func autocomplete(selectedSuggestion suggestion: String) { dismissOmniBar() loadQueryInCurrentTab(query: suggestion) } func autocomplete(pressedPlusButtonForSuggestion suggestion: String) { omniBar?.textField.text = suggestion } func autocompleteWasDismissed() { dismissOmniBar() } } extension MainViewController: HomeTabDelegate { func homeTabDidActivateOmniBar(homeTab: HomeTabViewController) { omniBar?.becomeFirstResponder() } func homeTabDidDeactivateOmniBar(homeTab: HomeTabViewController) { omniBar?.resignFirstResponder() omniBar?.clear() } func homeTab(_ homeTab: HomeTabViewController, didRequestQuery query: String) { loadQueryInNewWebTab(query: query) } func homeTab(_ homeTab: HomeTabViewController, didRequestUrl url: URL) { loadUrlInNewWebTab(url: url) } func homeTabDidRequestTabsSwitcher(homeTab: HomeTabViewController) { launchTabSwitcher() } func homeTabDidRequestBookmarks(homeTab: HomeTabViewController) { launchBookmarks() } func homeTabDidRequestTabCount(homeTab: HomeTabViewController) -> Int { return tabManager.count } } extension MainViewController: WebTabDelegate { func webTabLoadingStateDidChange(webTab: WebTabViewController) { refreshControls() } func webTab(_ webTab: WebTabViewController, didRequestNewTabForUrl url: URL) { launchTabFrom(webTab: webTab, forUrl: url) } func webTab(_ webTab: WebTabViewController, didRequestNewTabForRequest urlRequest: URLRequest) { launchTabFrom(webTab: webTab, forUrlRequest: urlRequest) } } extension MainViewController: TabSwitcherDelegate { var tabDetails: [Link] { return tabManager.tabDetails } func tabSwitcherDidRequestNewTab(tabSwitcher: TabSwitcherViewController) { launchTab() } func tabSwitcher(_ tabSwitcher: TabSwitcherViewController, didSelectTabAt index: Int) { select(tabAt: index) } func tabSwitcher(_ tabSwitcher: TabSwitcherViewController, didRemoveTabAt index: Int) { remove(tabAt: index) } func tabSwitcherDidRequestClearAll(tabSwitcher: TabSwitcherViewController) { clearAllTabs() } } extension MainViewController: BookmarksDelegate { func bookmarksDidSelect(link: Link) { loadUrlInCurrentTab(url: link.url) } } extension MainViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return BlurAnimatedTransitioning() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return DissolveAnimatedTransitioning() } }
apache-2.0
dffd33a2053f0dd3bb38d32326fa8bea
29.614286
170
0.653056
5.038401
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/views/TKUICompactActionCell.swift
1
2596
// // TKUICompactActionCell.swift // TripKitUI-iOS // // Created by Brian Huang on 3/4/20. // Copyright © 2020 SkedGo Pty Ltd. All rights reserved. // import UIKit import TripKit class TKUICompactActionCell: UICollectionViewCell { @IBOutlet private weak var imageWrapper: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! static let identifier = "TKUICompactActionCell" static let nib = UINib(nibName: "TKUICompactActionCell", bundle: .tripKitUI) var style: TKUICardActionStyle = .normal { didSet { updateForStyle() } } var onTap: ((TKUICompactActionCell) -> Bool)? override func prepareForReuse() { super.prepareForReuse() imageView.image = nil titleLabel.text = nil updateForStyle() } override var isHighlighted: Bool { didSet { if isHighlighted { imageWrapper.backgroundColor = .tkBackgroundSelected imageWrapper.layer.borderColor = UIColor.tkLabelSecondary.cgColor } else { imageWrapper.backgroundColor = .tkBackground imageWrapper.layer.borderColor = UIColor.tkLabelQuarternary.cgColor } } } override func awakeFromNib() { super.awakeFromNib() isAccessibilityElement = true accessibilityTraits.insert(.button) contentView.backgroundColor = .clear imageWrapper.layer.cornerRadius = imageWrapper.bounds.width * 0.5 titleLabel.textColor = .tkLabelPrimary titleLabel.font = TKStyleManager.customFont(forTextStyle: .footnote) updateForStyle() } override func tintColorDidChange() { super.tintColorDidChange() updateForStyle() } private func updateForStyle() { switch style { case .bold, .destructive: let background: UIColor if style == .destructive { background = .tkStateError } else { background = tintColor ?? .clear } imageWrapper.backgroundColor = background imageWrapper.layer.borderWidth = 0 imageWrapper.layer.borderColor = nil imageWrapper.tintColor = .tkBackground case .normal: imageWrapper.backgroundColor = .tkBackground imageWrapper.layer.borderWidth = 2 imageWrapper.layer.borderColor = UIColor.tkLabelQuarternary.cgColor imageWrapper.tintColor = .tkLabelSecondary } } } extension TKUICompactActionCell { static func newInstance() -> TKUICompactActionCell { return Bundle.tripKitUI.loadNibNamed("TKUICompactActionCell", owner: self, options: nil)?.first as! TKUICompactActionCell } }
apache-2.0
6fa8b9306f7ea763b9c847f308be2162
24.441176
125
0.6921
4.82342
false
false
false
false
alvinvarghese/DeLorean
DeLoreanTests/DeLoreanReactiveTests.swift
1
2621
// // DeLoreanReactiveTests.swift // DeLorean // // Created by Junior B. on 27/03/15. // Copyright (c) 2015 Bonto.ch. All rights reserved. // import XCTest import DeLorean /// Fibonacci convenience function public func fib(start: Int) -> Int { if start == 0 || start == 1 { return start } return (fib(start - 1) + fib(start - 2)) } class DeLoreanReactiveTests: 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() } // MARK: - General Tests func testEmitter() { let expectation = expectationWithDescription("Value emit") let emitter = Emitter<Int>() emitter.subscription().onNext() { v in XCTAssert(v == 1, "Value is wrong, should be 1 is \(v)") expectation.fulfill() } emitter.emit(1) waitForExpectationsWithTimeout(3) { (error) in XCTAssertNil(error, "Timeout Error!") } } func testMapEmitter() { let expectation = expectationWithDescription("Value emit") let emitter = Emitter<Int>() let mappedEmitter = emitter.map({v in "value: \(v)"}) mappedEmitter.subscription().onNext() { v in XCTAssert(v == "value: \(1)", "String is wrong, should be \"value: \(v)\" is \"\(v)\"") expectation.fulfill() } emitter.emit(1) waitForExpectationsWithTimeout(3) { (error) in XCTAssertNil(error, "Timeout Error!") } } func testMergedEmitters() { let expectation = expectationWithDescription("Value emit") let emitter1 = Emitter<Int>() let emitter2 = Emitter<Int>() let merged = emitter1.merge(emitter2) var values = Array<Int>() merged.subscription().onNext() { v in values.append(v) if values.count == 2 { XCTAssert(values[0] == 1, "Value[0] is wrong, should be 1 is \(v)") XCTAssert(values[1] == 2, "Value[1] is wrong, should be 2 is \(v)") expectation.fulfill() } } emitter1.emit(1) emitter2.emit(2) waitForExpectationsWithTimeout(5) { (error) in XCTAssertNil(error, "Timeout Error!") } } }
mit
e98b519b24c25ab5590c782b4afdf1c4
27.48913
111
0.552079
4.434856
false
true
false
false
iadmir/Signal-iOS
Signal/src/ViewControllers/GifPicker/GifPickerLayout.swift
3
5302
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation protocol GifPickerLayoutDelegate: class { func imageInfosForLayout() -> [GiphyImageInfo] } // A Pinterest-style waterfall layout. class GifPickerLayout: UICollectionViewLayout { let TAG = "[GifPickerLayout]" public weak var delegate: GifPickerLayoutDelegate? private var itemAttributesMap = [UInt: UICollectionViewLayoutAttributes]() private var contentSize = CGSize.zero // MARK: Initializers and Factory Methods @available(*, unavailable, message:"use other constructor instead.") required init?(coder aDecoder: NSCoder) { fatalError("\(#function) is unimplemented.") } override init() { super.init() } // MARK: Methods override func invalidateLayout() { super.invalidateLayout() itemAttributesMap.removeAll() } override func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { super.invalidateLayout(with:context) itemAttributesMap.removeAll() } override func prepare() { super.prepare() guard let collectionView = collectionView else { return } guard let delegate = delegate else { return } let vInset = UInt(5) let hInset = UInt(5) let vSpacing = UInt(3) let hSpacing = UInt(3) // We use 2 or 3 columns, depending on the device. // 2 columns will show fewer GIFs at a time, // but use less network & be a more responsive experience. let screenSize = UIScreen.main.bounds.size let screenWidth = min(screenSize.width, screenSize.height) let columnCount = UInt(max(2, screenWidth / 130)) let totalViewWidth = UInt(collectionView.width()) let hTotalWhitespace = (2 * hInset) + (hSpacing * (columnCount - 1)) let hRemainderSpace = totalViewWidth - hTotalWhitespace let columnWidth = UInt(hRemainderSpace / columnCount) // We want to unevenly distribute the hSpacing between the columns // so that the left and right margins are equal, which is non-trivial // due to rounding error. let totalHSpacing = totalViewWidth - ((2 * hInset) + (columnCount * columnWidth)) // columnXs are the left edge of each column. var columnXs = [UInt]() // columnYs are the top edge of the next cell in each column. var columnYs = [UInt]() for columnIndex in 0...columnCount-1 { var columnX = hInset + (columnWidth * columnIndex) if columnCount > 1 { // We want to unevenly distribute the hSpacing between the columns // so that the left and right margins are equal, which is non-trivial // due to rounding error. columnX += ((totalHSpacing * columnIndex) / (columnCount - 1)) } columnXs.append(columnX) columnYs.append(vInset) } // Always layout all items. let imageInfos = delegate.imageInfosForLayout() var contentBottom = vInset for (cellIndex, imageInfo) in imageInfos.enumerated() { // Select a column by finding the "highest, leftmost" column. var column = 0 var cellY = columnYs[column] for (columnValue, columnYValue) in columnYs.enumerated() { if columnYValue < cellY { column = columnValue cellY = columnYValue } } let cellX = columnXs[column] let cellWidth = columnWidth let cellHeight = UInt(columnWidth * imageInfo.originalRendition.height / imageInfo.originalRendition.width) let indexPath = NSIndexPath(row: cellIndex, section: 0) let itemAttributes = UICollectionViewLayoutAttributes(forCellWith:indexPath as IndexPath) let itemFrame = CGRect(x:CGFloat(cellX), y:CGFloat(cellY), width:CGFloat(cellWidth), height:CGFloat(cellHeight)) itemAttributes.frame = itemFrame itemAttributesMap[UInt(cellIndex)] = itemAttributes columnYs[column] = cellY + cellHeight + vSpacing contentBottom = max(contentBottom, cellY + cellHeight) } // Add bottom margin. let contentHeight = contentBottom + vInset contentSize = CGSize(width:CGFloat(totalViewWidth), height:CGFloat(contentHeight)) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return itemAttributesMap.values.filter { itemAttributes in return itemAttributes.frame.intersects(rect) } } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let result = itemAttributesMap[UInt(indexPath.row)] return result } override var collectionViewContentSize: CGSize { return contentSize } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { guard let collectionView = collectionView else { return false } return collectionView.width() != newBounds.size.width } }
gpl-3.0
58462def08b67bf2f292fc88203a6fa6
35.315068
124
0.638438
5.049524
false
false
false
false
Lasithih/LIHImageSlider
LIHImageSlider/Classes/LIHSliderViewController.swift
1
8192
// // LIHSliderViewController.swift // Pods // // Created by Lasith Hettiarachchi on 3/13/16. // // import UIKit @objc public protocol LIHSliderDelegate { func itemPressedAtIndex(index: Int) } open class LIHSliderViewController: UIViewController, LIHSliderItemDelegate { //@IBOutlet weak var pageControl: UIPageControl! fileprivate var pageControl: UIPageControl! fileprivate var pageController: UIPageViewController! fileprivate var currentIndex: Int = 0 { didSet { self.pageControl.currentPage = currentIndex } } fileprivate var pageTimer: Timer? fileprivate var slider: LIHSlider! public init(slider: LIHSlider) { super.init(nibName: nil, bundle: nil) self.slider = slider } open var delegate: LIHSliderDelegate? required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { self.view.backgroundColor = UIColor.orange self.killTimer() self.activateTimer() self.pageControl = UIPageControl() if self.slider.showPageIndicator { self.view.addSubview(self.pageControl) } self.initializePager() self.pageController.view.backgroundColor = UIColor.blue } open override func viewDidLayoutSubviews() { self.pageControl.center = CGPoint(x: UIScreen.main.bounds.size.width/2, y: self.view.frame.size.height - 20) } //MARK - Private methods fileprivate func initializePager() { //Initialize page view controller self.pageControl.numberOfPages = self.slider.sliderImages.count self.pageControl.currentPage = 0 pageController = UIPageViewController(transitionStyle: self.slider.transitionStyle, navigationOrientation: self.slider.slidingOrientation, options: nil) pageController.dataSource = self pageController.delegate = self if !self.slider.userInteractionEnabled { self.removeSwipeGesture() } let startingViewController: LIHSliderItemViewController = contentViewController(atIndex: currentIndex) pageController.setViewControllers([startingViewController], direction: .forward, animated: false, completion: nil) self.view.addSubview(self.pageController.view) self.view.bringSubview(toFront: self.pageControl) pageController.didMove(toParentViewController: self) for sview in pageController.view.subviews { if sview.isKind(of: UIScrollView.self) { (sview as! UIScrollView).delegate = self } } self.killTimer() self.activateTimer() } fileprivate func removeSwipeGesture(){ for view in self.pageController.view.subviews { if let subView = view as? UIScrollView { subView.isScrollEnabled = false } } } fileprivate func setConstraints() { let top = NSLayoutConstraint(item: self.pageController.view, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0) let bottom = NSLayoutConstraint(item: self.pageController.view, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0) let left = NSLayoutConstraint(item: self.pageController.view, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0) let right = NSLayoutConstraint(item: self.pageController.view, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0) self.view.addConstraints([top,bottom,left,right]) } fileprivate func activateTimer() { self.pageTimer = Timer.scheduledTimer(timeInterval: self.slider.transitionInterval, target: self, selector: #selector(LIHSliderViewController.pageSwitchTimer(_:)), userInfo: nil, repeats: true) } fileprivate func killTimer() { self.pageTimer?.invalidate() self.pageTimer = nil } @objc func pageSwitchTimer(_ sender: AnyObject) { if currentIndex == self.slider.sliderImages.count - 1 { self.pageController.setViewControllers([self.contentViewController(atIndex: 0)], direction: UIPageViewControllerNavigationDirection.forward, animated: true, completion: { (complete) -> Void in self.currentIndex = 0 }) } else { self.pageController.setViewControllers([self.contentViewController(atIndex: self.currentIndex+1)], direction: UIPageViewControllerNavigationDirection.forward, animated: true, completion: { (complete) -> Void in self.currentIndex = self.currentIndex + 1 }) } } fileprivate func contentViewController(atIndex index: Int) -> LIHSliderItemViewController! { if self.slider.sliderImages.count == 0 || index >= self.slider.sliderImages.count { self.pageControl.isHidden = true return nil } self.pageControl.isHidden = false let contentvc: LIHSliderItemViewController? = LIHSliderItemViewController(slider: self.slider) if let pageContentvc = contentvc { if self.slider.sliderImages.count > index { pageContentvc.image = self.slider.sliderImages[index] } if self.slider.sliderDescriptions.count > index { pageContentvc.desc = self.slider.sliderDescriptions[index] } pageContentvc.index = index pageContentvc.delegate = self return pageContentvc } return nil } func itemPressedAtIndex(_ index: Int) { self.delegate?.itemPressedAtIndex(index: index) } } extension LIHSliderViewController: UIPageViewControllerDataSource, UIPageViewControllerDelegate { public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let vc = viewController as! LIHSliderItemViewController let index = vc.index if index == self.slider.sliderImages.count - 1 { return self.contentViewController(atIndex: 0) } return self.contentViewController(atIndex: index + 1) } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let vc = viewController as! LIHSliderItemViewController let index = vc.index if index == 0 { return self.contentViewController(atIndex: self.slider.sliderImages.count - 1) } return self.contentViewController(atIndex: index - 1) } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if !completed { return } self.currentIndex = (pageController?.viewControllers?.first as! LIHSliderItemViewController).index } } extension LIHSliderViewController: UIScrollViewDelegate { public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.killTimer() } public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { self.killTimer() self.activateTimer() } }
mit
d356b5052251911f0bcd048d3b6ac6d7
35.408889
227
0.65686
5.410832
false
false
false
false
SwiftGen/SwiftGen
Sources/TestUtils/TestsHelper+Strings.swift
1
1827
// // SwiftGenKit UnitTests // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import XCTest // MARK: - Compare strings public func XCTDiffStrings(_ received: String, _ expected: String, file: StaticString = #file, line: UInt = #line) { guard let error = diff(received, expected) else { return } XCTFail(error, file: file, line: line) } private func diff(_ result: String, _ expected: String) -> String? { guard result != expected else { return nil } let lhsLines = result.components(separatedBy: .newlines) let rhsLines = expected.components(separatedBy: .newlines) // try to find different line (or last if different size) var firstDiff = zip(0..., zip(lhsLines, rhsLines)).first { $1.0 != $1.1 }?.0 if firstDiff == nil && lhsLines.count != rhsLines.count { firstDiff = min(lhsLines.count, rhsLines.count) } // generate output guard let line = firstDiff else { return nil } let lhsNum = addLineNumbers(slice(lhsLines, around: line)) let rhsNum = addLineNumbers(slice(rhsLines, around: line)) return """ Mismatch at line \(line + 1) >>>>>> received \(lhsNum) ====== \(rhsNum) <<<<<< expected """ } private func slice(_ lines: [String], around index: Int, context: Int = 4) -> ArraySlice<String> { let start = max(0, index - context) let end = min(index + context, lines.count - 1) return lines[start...end] } private func addLineNumbers(_ slice: ArraySlice<String>) -> String { let middle = slice.startIndex + (slice.endIndex - slice.startIndex) / 2 return zip(slice.startIndex..., slice) .map { index, line in let number = "\(index + 1)".padding(toLength: 3, withPad: " ", startingAt: 0) let separator = (index == middle) ? ">" : "|" return "\(number)\(separator)\(line)" } .joined(separator: "\n") }
mit
1990801438650751791ef7c6a1e8c051
30.482759
116
0.650602
3.703854
false
false
false
false
Dsringari/scan4pase
Project/scan4pase/CartVC.swift
1
11441
// // CartVC.swift // scan4pase // // Created by Dhruv Sringari on 7/5/16. // Copyright © 2016 Dhruv Sringari. All rights reserved. // import UIKit import MagicalRecord // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } protocol CartVCDelegate { var iboCostSubtotal: NSDecimalNumber { get } var retailCostSubtotal: NSDecimalNumber { get } var iboCostGrandTotal: NSDecimalNumber { get } var retailCostGrandTotal: NSDecimalNumber { get } var pvTotal: NSDecimalNumber { get } var bvTotal: NSDecimalNumber { get } var quantityTotal: NSDecimalNumber { get } } class CartVC: UIViewController, UITableViewDelegate, UITableViewDataSource, CartVCDelegate { @IBOutlet var addButton: UIBarButtonItem! @IBOutlet var cart: UITableView! @IBOutlet var pvBVTotal: UILabel! @IBOutlet var subtotal: UILabel! @IBOutlet var grandTotal: UILabel! @IBOutlet var pvBVLabel: UILabel! @IBOutlet var subtotalLabel: UILabel! @IBOutlet var grandTotalLabel: UILabel! @IBOutlet var checkout: UIButton! @IBOutlet var loadingView: UIView! @IBOutlet var activitiyIndicator: UIActivityIndicatorView! var cartProducts: [CartProduct] = [] var selectedCartProduct: CartProduct? var iboCostSubtotal: NSDecimalNumber = 0 var retailCostSubtotal: NSDecimalNumber = 0 var iboCostGrandTotal: NSDecimalNumber = 0 var retailCostGrandTotal: NSDecimalNumber = 0 var pvTotal: NSDecimalNumber = 0 var bvTotal: NSDecimalNumber = 0 var quantityTotal: NSDecimalNumber = 0 override func viewDidLoad() { super.viewDidLoad() cart.delegate = self cart.dataSource = self // Do any additional setup after loading the view. loadProducts() navigationItem.leftBarButtonItem = editButtonItem NotificationCenter.default.addObserver(self, selector: #selector(calculateTotals), name: NSNotification.Name(rawValue: "settingsUpdated"), object: nil) } deinit { NotificationCenter.default.removeObserver(self) } func loadProducts() { startLoadingAnimation() UIApplication.shared.beginIgnoringInteractionEvents() ProductService.importProducts({ successful, _ in DispatchQueue.main.async(execute: { UIApplication.shared.endIgnoringInteractionEvents() if (!successful) { self.activitiyIndicator.stopAnimating() let alert = UIAlertController(title: "Error!", message: "We failed to load the products. Check your connection and try again.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Retry", style: .default, handler: { [unowned self] _ in self.loadProducts() })) self.present(alert, animated: true, completion: nil) } else { self.stopLoadingAnimation() self.reloadCart() } }) }) } func resetTotals() { iboCostSubtotal = 0 retailCostSubtotal = 0 iboCostGrandTotal = 0 retailCostGrandTotal = 0 pvTotal = 0 bvTotal = 0 quantityTotal = 0 } @objc func calculateTotals() { resetTotals() let roundUP = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) var retailCostTaxTotal: NSDecimalNumber = 0 for cartProduct in cartProducts { let product = cartProduct.product! let quantity = NSDecimalNumber(decimal: cartProduct.quantity!.decimalValue) quantityTotal = quantityTotal.adding(quantity) let qPV = product.pv!.multiplying(by: quantity, withBehavior: roundUP) let qBV = product.bv!.multiplying(by: quantity, withBehavior: roundUP) let qRetailCost = product.retailCost!.multiplying(by: quantity, withBehavior: roundUP) let qIboCost = product.iboCost!.multiplying(by: quantity, withBehavior: roundUP) if let taxPercentage = UserDefaults.standard.object(forKey: "taxPercentage") as? NSNumber, cartProduct.taxable!.boolValue { var taxPercentage = NSDecimalNumber(decimal: taxPercentage.decimalValue) taxPercentage = taxPercentage.multiplying(byPowerOf10: -2, withBehavior: roundUP) let retailTax = qRetailCost.multiplying(by: taxPercentage, withBehavior: roundUP) retailCostTaxTotal = retailCostTaxTotal.adding(retailTax, withBehavior: roundUP) } pvTotal = pvTotal.adding(qPV, withBehavior: roundUP) bvTotal = bvTotal.adding(qBV, withBehavior: roundUP) retailCostSubtotal = retailCostSubtotal.adding(qRetailCost, withBehavior: roundUP) iboCostSubtotal = iboCostSubtotal.adding(qIboCost, withBehavior: roundUP) } retailCostGrandTotal = retailCostSubtotal.adding(retailCostTaxTotal, withBehavior: roundUP) iboCostGrandTotal = iboCostSubtotal.adding(retailCostTaxTotal, withBehavior: roundUP) navigationController?.navigationBar.topItem?.title = "Cart(\(quantityTotal.stringValue))" UIView.animate(withDuration: 0.3, animations: { var formatter = NumberFormatter() formatter.numberStyle = .currency self.subtotal.text = formatter.string(from: self.iboCostSubtotal)! + " / " + formatter.string(from: self.retailCostSubtotal)! self.grandTotal.text = formatter.string(from: self.iboCostGrandTotal)! + " / " + formatter.string(from: self.retailCostGrandTotal)! formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.minimumIntegerDigits = 1 formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 self.pvBVTotal.text = formatter.string(from: self.pvTotal)! + " / " + formatter.string(from: self.bvTotal)! }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func reloadCart() { self.cartProducts = CartProduct.mr_findAll() as! [CartProduct] cartProducts.sort(by: { $0.product!.sku < $1.product!.sku }) calculateTotals() cart.reloadSections(IndexSet(integer: 0), with: .automatic) } override func viewDidAppear(_ animated: Bool) { reloadCart() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 84 } func numberOfSections(in tableView: UITableView) -> Int { if cartProducts.count == 0 { showEmptyCart() return 1 } hideBackgroundCartView() return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cartProducts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "cartCell") as? CartCell { let cartProduct = cartProducts[indexPath.row] if cartProduct.product != nil { cell.load(withCartProduct: cartProduct) } else { cartProduct.mr_deleteEntity() NSManagedObjectContext.mr_default().mr_saveToPersistentStoreAndWait() } return cell } return UITableViewCell() } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) cart.setEditing(editing, animated: true) if cart.isEditing { let emptyButton = UIBarButtonItem(title: "Empty Cart", style: .plain, target: self, action: #selector(clearCart)) navigationItem.rightBarButtonItem = emptyButton } else { navigationItem.rightBarButtonItem = addButton } } func addProduct() { performSegue(withIdentifier: "selectItem", sender: self) } @objc func clearCart() { let alert = UIAlertController(title: "Empty Cart", message: "This will delete all of the products in the cart.", preferredStyle: .actionSheet) let delete = UIAlertAction(title: "Delete All", style: .destructive, handler: { _ in for cartProduct in self.cartProducts { self.cartProducts.removeObject(cartProduct) cartProduct.mr_deleteEntity() } NSManagedObjectContext.mr_default().mr_saveToPersistentStoreAndWait() self.reloadCart() self.setEditing(false, animated: false) }) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addAction(delete) alert.addAction(cancel) present(alert, animated: true, completion: nil) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == UITableViewCellEditingStyle.delete) { let cartProduct = cartProducts[indexPath.row] cartProducts.remove(at: indexPath.row) cartProduct.mr_deleteEntity() NSManagedObjectContext.mr_default().mr_saveToPersistentStoreAndWait() tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) calculateTotals() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedCartProduct = cartProducts[indexPath.row] tableView.deselectRow(at: indexPath, animated: true) performSegue(withIdentifier: "editItem", sender: nil) } func hide() { pvBVLabel.isHidden = true subtotalLabel.isHidden = true grandTotalLabel.isHidden = true pvBVTotal.isHidden = true subtotal.isHidden = true grandTotal.isHidden = true checkout.isHidden = true } func show() { pvBVLabel.isHidden = false subtotalLabel.isHidden = false grandTotalLabel.isHidden = false pvBVTotal.isHidden = false subtotal.isHidden = false grandTotal.isHidden = false checkout.isHidden = false } func showEmptyCart() { // Display a message when the table is empty let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)) label.text = "No products in cart." label.textColor = UIColor(red: 43, green: 130, blue: 201) label.numberOfLines = 0 label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 20) label.sizeToFit() cart.backgroundView = label cart.separatorStyle = .none hide() } func hideBackgroundCartView() { cart.backgroundView = nil cart.separatorStyle = .singleLine show() } func startLoadingAnimation() { loadingView.alpha = 1 loadingView.isHidden = false activitiyIndicator.startAnimating() } func stopLoadingAnimation() { loadingView.alpha = 1 UIView.animate(withDuration: 0.3, animations: { self.loadingView.alpha = 0 }) loadingView.isHidden = true activitiyIndicator.stopAnimating() } @IBAction func checkout(_ sender: AnyObject) { } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let backItem = UIBarButtonItem() backItem.title = "Cart" navigationItem.backBarButtonItem = backItem if segue.identifier == "editItem" { let detailVC = segue.destination as! CartProductDetailVC detailVC.product = selectedCartProduct?.product detailVC.edit = true } else if segue.identifier == "config" { let configVC = segue.destination as! ConfigurationVC configVC.cartDelegate = self } } @IBAction func prepareForUnwind(_ segue: UIStoryboardSegue) { for cartProduct in self.cartProducts { self.cartProducts.removeObject(cartProduct) cartProduct.mr_deleteEntity() } NSManagedObjectContext.mr_default().mr_saveToPersistentStoreAndWait() reloadCart() } }
apache-2.0
2f715fe0aab444aba91bee5ef48cc7b3
31.225352
171
0.740822
3.874026
false
false
false
false
sschiau/swift
test/attr/attr_escaping.swift
4
9528
// RUN: %target-typecheck-verify-swift -swift-version 4 @escaping var fn : () -> Int = { 4 } // expected-error {{attribute can only be applied to types, not declarations}} func paramDeclEscaping(@escaping fn: (Int) -> Void) {} // expected-error {{attribute can only be applied to types, not declarations}} func wrongParamType(a: @escaping Int) {} // expected-error {{@escaping attribute only applies to function types}} func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{unknown attribute 'noescape'}} func takesEscaping(_ fn: @escaping () -> Int) {} // ok func callEscapingWithNoEscape(_ fn: () -> Int) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }} takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} // This is a non-escaping use: let _ = fn } typealias IntSugar = Int func callSugared(_ fn: () -> IntSugar) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }} takesEscaping(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } struct StoresClosure { var closure : () -> Int init(_ fn: () -> Int) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{14-14=@escaping }} closure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}} } func arrayPack(_ fn: () -> Int) -> [() -> Int] { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{24-24=@escaping }} return [fn] // expected-error{{using non-escaping parameter 'fn' in a context expecting an @escaping closure}} } func dictPack(_ fn: () -> Int) -> [String: () -> Int] { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{23-23=@escaping }} return ["ultimate answer": fn] // expected-error{{using non-escaping parameter 'fn' in a context expecting an @escaping closure}} } func arrayPack(_ fn: @escaping () -> Int, _ fn2 : () -> Int) -> [() -> Int] { // expected-note@-1{{parameter 'fn2' is implicitly non-escaping}} {{53-53=@escaping }} return [fn, fn2] // expected-error{{using non-escaping parameter 'fn2' in a context expecting an @escaping closure}} } } func takesEscapingBlock(_ fn: @escaping @convention(block) () -> Void) { fn() } func callEscapingWithNoEscapeBlock(_ fn: () -> Void) { // expected-note@-1{{parameter 'fn' is implicitly non-escaping}} {{42-42=@escaping }} takesEscapingBlock(fn) // expected-error{{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } func takesEscapingAutoclosure(_ fn: @autoclosure @escaping () -> Int) {} func callEscapingAutoclosureWithNoEscape(_ fn: () -> Int) { takesEscapingAutoclosure(1+1) } let foo: @escaping (Int) -> Int // expected-error{{@escaping attribute may only be used in function parameter position}} {{10-20=}} struct GenericStruct<T> {} func misuseEscaping(_ a: @escaping Int) {} // expected-error{{@escaping attribute only applies to function types}} {{26-36=}} func misuseEscaping(_ a: (@escaping Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{27-36=}} func misuseEscaping(opt a: @escaping ((Int) -> Int)?) {} // expected-error{{@escaping attribute only applies to function types}} {{28-38=}} // expected-note@-1{{closure is already escaping in optional type argument}} func misuseEscaping(_ a: (@escaping (Int) -> Int)?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-36=}} // expected-note@-1{{closure is already escaping in optional type argument}} func misuseEscaping(nest a: (((@escaping (Int) -> Int))?)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-41=}} // expected-note@-1{{closure is already escaping in optional type argument}} func misuseEscaping(iuo a: (@escaping (Int) -> Int)!) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{29-38=}} // expected-note@-1{{closure is already escaping in optional type argument}} func misuseEscaping(_ a: Optional<@escaping (Int) -> Int>, _ b: Int) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{35-44=}} func misuseEscaping(_ a: (@escaping (Int) -> Int, Int)) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-36=}} func misuseEscaping(_ a: [@escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-36=}} func misuseEscaping(_ a: [@escaping (Int) -> Int]?) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{27-36=}} func misuseEscaping(_ a: [Int : @escaping (Int) -> Int]) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{33-43=}} func misuseEscaping(_ a: GenericStruct<@escaping (Int) -> Int>) {} // expected-error{{@escaping attribute may only be used in function parameter position}} {{40-49=}} func takesEscapingGeneric<T>(_ fn: @escaping () -> T) {} func callEscapingGeneric<T>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{35-35=@escaping }} takesEscapingGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } class Super {} class Sub: Super {} func takesEscapingSuper(_ fn: @escaping () -> Super) {} func callEscapingSuper(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{30-30=@escaping }} takesEscapingSuper(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } func takesEscapingSuperGeneric<T: Super>(_ fn: @escaping () -> T) {} func callEscapingSuperGeneric(_ fn: () -> Sub) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }} takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } func callEscapingSuperGeneric<T: Sub>(_ fn: () -> T) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{45-45=@escaping }} takesEscapingSuperGeneric(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } func testModuloOptionalness() { var iuoClosure: (() -> Void)! = nil func setIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{28-28=@escaping }} iuoClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}} } var iuoClosureExplicit: (() -> Void)! func setExplicitIUOClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{36-36=@escaping }} iuoClosureExplicit = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}} } var deepOptionalClosure: (() -> Void)??? func setDeepOptionalClosure(_ fn: () -> Void) { // expected-note {{parameter 'fn' is implicitly non-escaping}} {{37-37=@escaping }} deepOptionalClosure = fn // expected-error{{assigning non-escaping parameter 'fn' to an @escaping closure}} } } // Check that functions in vararg position are @escaping func takesEscapingFunction(fn: @escaping () -> ()) {} func takesArrayOfFunctions(array: [() -> ()]) {} func takesVarargsOfFunctions(fns: () -> ()...) { takesArrayOfFunctions(array: fns) for fn in fns { takesEscapingFunction(fn: fn) } } func takesVarargsOfFunctionsExplicitEscaping(fns: @escaping () -> ()...) {} // expected-error{{@escaping attribute may only be used in function parameter position}} func takesNoEscapeFunction(fn: () -> ()) { // expected-note {{parameter 'fn' is implicitly non-escaping}} takesVarargsOfFunctions(fns: fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} } class FooClass { var stored : Optional<(()->Int)->Void> = nil var computed : (()->Int)->Void { get { return stored! } set(newValue) { stored = newValue } // ok } var computedEscaping : (@escaping ()->Int)->Void { get { return stored! } set(newValue) { stored = newValue } // expected-error{{assigning non-escaping parameter 'newValue' to an @escaping closure}} // expected-note@-1 {{parameter 'newValue' is implicitly non-escaping}} } } // A call of a closure literal should be non-escaping func takesInOut(y: inout Int) { _ = { y += 1 // no-error }() _ = ({ y += 1 // no-error })() _ = { () in y += 1 // no-error }() _ = ({ () in y += 1 // no-error })() _ = { () -> () in y += 1 // no-error }() _ = ({ () -> () in y += 1 // no-error })() } class HasIVarCaptures { var x: Int = 0 func method() { _ = { x += 1 // no-error }() _ = ({ x += 1 // no-error })() _ = { () in x += 1 // no-error }() _ = ({ () in x += 1 // no-error })() _ = { () -> () in x += 1 // no-error }() _ = ({ () -> () in x += 1 // no-error })() } } // https://bugs.swift.org/browse/SR-9760 protocol SR_9760 { typealias F = () -> Void typealias G<T> = (T) -> Void func foo<T>(_: T, _: @escaping F) // Ok func bar<T>(_: @escaping G<T>) // Ok } extension SR_9760 { func fiz<T>(_: T, _: @escaping F) {} // Ok func baz<T>(_: @escaping G<T>) {} // Ok }
apache-2.0
3991edb7f09bef0b0864b3191b4e14c6
40.789474
171
0.652813
3.755617
false
false
false
false
maximkhatskevich/MKHAPIClient
Sources/Core/3rdParty/Alamofire/ParameterEncoding.swift
1
18514
// Based on: // https://github.com/Alamofire/Alamofire/blob/master/Source/ParameterEncoding.swift // ParameterEncoding.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// HTTP method definitions. /// /// See https://tools.ietf.org/html/rfc7231#section-4.3 public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } // MARK: - /// A dictionary of parameters to apply to a `URLRequest`. public typealias Parameters = [String: Any] /// A type used to define how a set of parameters are applied to a `URLRequest`. public protocol ParameterEncoding { /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. /// /// - returns: The encoded request. func encode(_ urlRequest: URLRequest, with parameters: Parameters?) -> Result<URLRequest, RequestEncodingIssue> } // MARK: - /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as /// the HTTP body depends on the destination of the encoding. /// /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to /// `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode /// collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending /// the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). public struct URLEncoding: ParameterEncoding { // MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. /// /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` /// requests and sets as the HTTP body for requests with any other HTTP method. /// - queryString: Sets or appends encoded query string result to existing query string. /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. public enum Destination { case methodDependent, queryString, httpBody } // MARK: Properties /// Returns a default `URLEncoding` instance. public static var `default`: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.methodDependent` destination. public static var methodDependent: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.queryString` destination. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } /// Returns a `URLEncoding` instance with an `.httpBody` destination. public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination // MARK: Initialization /// Creates a `URLEncoding` instance using the specified destination. /// /// - parameter destination: The destination defining where the encoded query string is to be applied. /// /// - returns: The new `URLEncoding` instance. public init(destination: Destination = .methodDependent) { self.destination = destination } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequest, with parameters: Parameters?) -> Result<URLRequest, RequestEncodingIssue> { var urlRequest = urlRequest guard let parameters = parameters else { return .success(urlRequest) } if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? HTTPMethod.get.rawValue), encodesParametersInURL(with: method) { guard let url = urlRequest.url else { return .failure(RequestEncodingIssue(reason: "URL encoding failed - missing URL", error: nil)) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) urlComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = urlComponents.url } } else { if urlRequest.value(forHTTPHeaderField: HTTPHeaderFieldName.contentType.rawValue) == nil { urlRequest.setValue(ContentType.formURLEncoded.rawValue, forHTTPHeaderField: HTTPHeaderFieldName.contentType.rawValue) } urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) } return .success(urlRequest) } /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. /// /// - parameter key: The key of the query component. /// - parameter value: The value of the query component. /// /// - returns: The percent-escaped, URL encoded query string components. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [Any] { for value in array { components += queryComponents(fromKey: "\(key)[]", value: value) } } else if let value = value as? NSNumber { if value.isBool { components.append((escape(key), escape((value.boolValue ? "1" : "0")))) } else { components.append((escape(key), escape("\(value)"))) } } else if let bool = value as? Bool { components.append((escape(key), escape((bool ? "1" : "0")))) } else { components.append((escape(key), escape("\(value)"))) } return components } /// Returns a percent-escaped string following RFC 3986 for a query string key or value. /// /// RFC 3986 states that the following characters are "reserved" characters. /// /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" /// /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" /// should be percent-escaped in the query string. /// /// - parameter string: The string to be percent-escaped. /// /// - returns: The percent-escaped string. public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 8.3, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex..<endIndex let substring = string[range] escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? String(substring) index = endIndex } } return escaped } private func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } private func encodesParametersInURL(with method: HTTPMethod) -> Bool { switch destination { case .queryString: return true case .httpBody: return false default: break } switch method { case .get, .head, .delete: return true default: return false } } } // MARK: - /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. public struct JSONEncoding: ParameterEncoding { // MARK: Properties /// Returns a `JSONEncoding` instance with default writing options. public static var `default`: JSONEncoding { return JSONEncoding() } /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } /// The options for writing the parameters as JSON data. public let options: JSONSerialization.WritingOptions // MARK: Initialization /// Creates a `JSONEncoding` instance using the specified options. /// /// - parameter options: The options for writing the parameters as JSON data. /// /// - returns: The new `JSONEncoding` instance. public init(options: JSONSerialization.WritingOptions = []) { self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequest, with parameters: Parameters?) -> Result<URLRequest, RequestEncodingIssue> { var urlRequest = urlRequest guard let parameters = parameters else { return .success(urlRequest) } do { let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if urlRequest.value(forHTTPHeaderField: HTTPHeaderFieldName.contentType.rawValue) == nil { urlRequest.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderFieldName.contentType.rawValue) } urlRequest.httpBody = data } catch { return .failure(RequestEncodingIssue(reason: "JSON encoding failed", error: error)) } return .success(urlRequest) } /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. /// /// - parameter urlRequest: The request to apply the JSON object to. /// - parameter jsonObject: The JSON object to apply to the request. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequest, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { var urlRequest = urlRequest guard let jsonObject = jsonObject else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) if urlRequest.value(forHTTPHeaderField: HTTPHeaderFieldName.contentType.rawValue) == nil { urlRequest.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderFieldName.contentType.rawValue) } urlRequest.httpBody = data } catch { throw RequestEncodingIssue(reason: "JSON encoding failed", error: error) } return urlRequest } } // MARK: - /// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the /// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header /// field of an encoded request is set to `application/x-plist`. public struct PropertyListEncoding: ParameterEncoding { // MARK: Properties /// Returns a default `PropertyListEncoding` instance. public static var `default`: PropertyListEncoding { return PropertyListEncoding() } /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } /// The property list serialization format. public let format: PropertyListSerialization.PropertyListFormat /// The options for writing the parameters as plist data. public let options: PropertyListSerialization.WriteOptions // MARK: Initialization /// Creates a `PropertyListEncoding` instance using the specified format and options. /// /// - parameter format: The property list serialization format. /// - parameter options: The options for writing the parameters as plist data. /// /// - returns: The new `PropertyListEncoding` instance. public init( format: PropertyListSerialization.PropertyListFormat = .xml, options: PropertyListSerialization.WriteOptions = 0) { self.format = format self.options = options } // MARK: Encoding /// Creates a URL request by encoding parameters and applying them onto an existing request. /// /// - parameter urlRequest: The request to have parameters applied. /// - parameter parameters: The parameters to apply. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequest, with parameters: Parameters?) -> Result<URLRequest, RequestEncodingIssue> { var urlRequest = urlRequest guard let parameters = parameters else { return .success(urlRequest) } do { let data = try PropertyListSerialization.data( fromPropertyList: parameters, format: format, options: options ) if urlRequest.value(forHTTPHeaderField: HTTPHeaderFieldName.contentType.rawValue) == nil { urlRequest.setValue(ContentType.plist.rawValue, forHTTPHeaderField: HTTPHeaderFieldName.contentType.rawValue) } urlRequest.httpBody = data } catch { return .failure(RequestEncodingIssue(reason: "Property list encoding failed", error: error)) } return .success(urlRequest) } } // MARK: - extension NSNumber { fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } }
mit
dcee1bb923a97a5a6f2fd2f3bfc18347
43.398082
134
0.637302
5.193268
false
false
false
false
ciamic/Smashtag
Twitter/Request.swift
1
11129
// // TwitterRequest.swift // Twitter // // Created by CS193p Instructor. // Copyright (c) 2015-17 Stanford University. All rights reserved. // import Foundation import Accounts import Social import CoreLocation // Simple Twitter query class // Create an instance of it using one of the initializers // Set the requestType and parameters (if not using a convenience init that sets those) // Call fetch (or fetchTweets if fetching Tweets) // The handler passed in will be called when the information comes back from Twitter // Once a successful fetch has happened, // a follow-on TwitterRequest to get more Tweets (newer or older) can be created // using the requestFor{Newer,Older} methods private var twitterAccount: ACAccount? // Enum added from original cs193p Instructor implementation in order to handle // cases in which either the user did not have any Tweeter account or did not // give the permission to access to Tweeter accounts informations. public enum TwitterAccountError: Error { case noAccountsAvailable case noPermissionGranted case noResponseFromTwitter case errorParsingTwitterResponse } public class Request: NSObject { public let requestType: String public let parameters: [String:String] public var searchTerm: String? { return parameters[TwitterKey.query]?.components(separatedBy: "-").first?.trimmingCharacters(in: CharacterSet.whitespaces) } public enum SearchResultType: Int { case mixed case recent case popular } // designated initializer public init(_ requestType: String, _ parameters: Dictionary<String, String> = [:]) { self.requestType = requestType self.parameters = parameters } // convenience initializer for creating a TwitterRequest that is a search for Tweets public convenience init(search: String, count: Int = 0) { // , resultType resultType: SearchResultType = .Mixed, region region: CLCircularRegion? = nil) { var parameters = [TwitterKey.query : search] if count > 0 { parameters[TwitterKey.count] = "\(count)" } // switch resultType { // case .Recent: parameters[TwitterKey.ResultType] = TwitterKey.ResultTypeRecent // case .Popular: parameters[TwitterKey.ResultType] = TwitterKey.ResultTypePopular // default: break // } // if let geocode = region { // parameters[TwitterKey.Geocode] = "\(geocode.center.latitude),\(geocode.center.longitude),\(geocode.radius/1000.0)km" // } self.init(TwitterKey.searchForTweets, parameters) } // convenience "fetch" for when self is a request that returns Tweet(s) // handler is not necessarily invoked on the main queue public func fetchTweets(_ handler: @escaping ([Tweet], Error?) -> Void) { fetch { results, error in var tweets = [Tweet]() var tweetArray: NSArray? if let dictionary = results as? NSDictionary { if let tweets = dictionary[TwitterKey.tweets] as? NSArray { tweetArray = tweets } else if let tweet = Tweet(data: dictionary) { tweets = [tweet] } } else if let array = results as? NSArray { tweetArray = array } if tweetArray != nil { for tweetData in tweetArray! { if let tweet = Tweet(data: tweetData as? NSDictionary) { tweets.append(tweet) } } } handler(tweets, error) } } public typealias PropertyList = Any // send the request specified by our requestType and parameters off to Twitter // calls the handler (not necessarily on the main queue) // with the JSON results converted to a Property List public func fetch(_ handler: @escaping (PropertyList?, Error?) -> Void) { performTwitterRequest(.GET, handler: handler) } // generates a request for older Tweets than were returned by self // only makes sense if self has completed a fetch already // only makes sense for requests for Tweets public var older: Request? { if min_id == nil { if parameters[TwitterKey.maxID] != nil { return self } } else { return modifiedRequest(parametersToChange: [TwitterKey.maxID : min_id!]) } return nil } // generates a request for newer Tweets than were returned by self // only makes sense if self has completed a fetch already // only makes sense for requests for Tweets public var newer: Request? { if max_id == nil { if parameters[TwitterKey.sinceID] != nil { return self } } else { return modifiedRequest(parametersToChange: [TwitterKey.sinceID : max_id!], clearCount: true) } return nil } // MARK: - Internal Implementation // creates an appropriate SLRequest using the specified SLRequestMethod // then calls the other version of this method that takes an SLRequest // handler is not necessarily called on the main queue func performTwitterRequest(_ method: SLRequestMethod, handler: @escaping (PropertyList?, Error?) -> Void) { let jsonExtension = (self.requestType.range(of: Constants.JSONExtension) == nil) ? Constants.JSONExtension : "" let url = URL(string: "\(Constants.twitterURLPrefix)\(self.requestType)\(jsonExtension)") if let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: method, url: url, parameters: parameters) { performTwitterSLRequest(request, handler: handler) } } // sends the request to Twitter // unpackages the JSON response into a Property List // and calls handler (not necessarily on the main queue) func performTwitterSLRequest(_ request: SLRequest, handler: @escaping (PropertyList?, Error?) -> Void) { if let account = twitterAccount { request.account = account request.perform { (jsonResponse, httpResponse, _) in var propertyListResponse: PropertyList? if jsonResponse != nil { propertyListResponse = try? JSONSerialization.jsonObject(with: jsonResponse!, options: .mutableLeaves) if propertyListResponse == nil { let error = "Couldn't parse JSON response." self.log(error) //propertyListResponse = error handler(nil, TwitterAccountError.errorParsingTwitterResponse) return } } else { let error = "No response from Twitter." self.log(error) //propertyListResponse = error handler(nil, TwitterAccountError.noResponseFromTwitter) return } self.synchronize { self.captureFollowonRequestInfo(propertyListResponse) } handler(propertyListResponse, nil) } } else { let accountStore = ACAccountStore() let twitterAccountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccounts(with: twitterAccountType, options: nil) { (granted, _) in if granted { if let account = accountStore.accounts(with: twitterAccountType)?.last as? ACAccount { twitterAccount = account self.performTwitterSLRequest(request, handler: handler) } else { let error = "Couldn't discover Twitter account type." self.log(error) handler(nil, TwitterAccountError.noAccountsAvailable) } } else { let error = "Access to Twitter was not granted." self.log(error) handler(nil, TwitterAccountError.noPermissionGranted) } } } } private var min_id: String? = nil private var max_id: String? = nil // modifies parameters in an existing request to create a new one private func modifiedRequest(parametersToChange: Dictionary<String,String>, clearCount: Bool = false) -> Request { var newParameters = parameters for (key, value) in parametersToChange { newParameters[key] = value } if clearCount { newParameters[TwitterKey.count] = nil } return Request(requestType, newParameters) } // captures the min_id and max_id information // to support requestForNewer and requestForOlder private func captureFollowonRequestInfo(_ propertyListResponse: PropertyList?) { if let responseDictionary = propertyListResponse as? NSDictionary { self.max_id = responseDictionary.value(forKeyPath: TwitterKey.SearchMetadata.maxID) as? String if let next_results = responseDictionary.value(forKeyPath: TwitterKey.SearchMetadata.nextResults) as? String { for queryTerm in next_results.components(separatedBy: TwitterKey.SearchMetadata.separator) { if queryTerm.hasPrefix("?\(TwitterKey.maxID)=") { let next_id = queryTerm.components(separatedBy: "=") if next_id.count == 2 { self.min_id = next_id[1] } } } } } } // debug println with identifying prefix private func log(_ whatToLog: Any) { debugPrint("TwitterRequest: \(whatToLog)") } // synchronizes access to self across multiple threads private func synchronize(_ closure: () -> Void) { objc_sync_enter(self) closure() objc_sync_exit(self) } // constants private struct Constants { static let JSONExtension = ".json" static let twitterURLPrefix = "https://api.twitter.com/1.1/" } // keys in Twitter responses/queries struct TwitterKey { static let count = "count" static let query = "q" static let tweets = "statuses" static let resultType = "result_type" static let resultTypeRecent = "recent" static let resultTypePopular = "popular" static let geocode = "geocode" static let searchForTweets = "search/tweets" static let maxID = "max_id" static let sinceID = "since_id" struct SearchMetadata { static let maxID = "search_metadata.max_id_str" static let nextResults = "search_metadata.next_results" static let separator = "&" } } }
mit
4fcb7b8a9272edeae95dc48fd9391a1c
38.888889
158
0.605355
5.188345
false
false
false
false
PJayRushton/stats
Stats/SharedExtensions.swift
1
7746
// // Arrays.swift // TeacherTools // // Created by Parker Rushton on 10/30/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit import Marshal extension Bundle { var releaseVersionNumber: String? { return infoDictionary?["CFBundleShortVersionString"] as? String } var buildVersionNumber: String? { return infoDictionary?["CFBundleVersion"] as? String } } extension Collection where Self: ExpressibleByDictionaryLiteral, Self.Key == String, Self.Value == Any { func parsedObjects<T: Identifiable>() -> [T] { guard let json = self as? JSONObject else { return [] } let keys = Array(json.keys) let objects: [JSONObject] = keys.compactMap { try? json.value(for: $0) } return objects.compactMap { try? T(object: $0) } } } extension Optional where Wrapped: MarshaledObject { func parsedObjects<T: Identifiable>() -> [T] { guard let json = self as? JSONObject else { return [] } let keys = Array(json.keys) let objects: [JSONObject] = keys.compactMap { try? json.value(for: $0) } return objects.compactMap { try? T(object: $0) } } } extension Array where Iterator.Element == Game { var record: TeamRecord { let wasWonBools = self.compactMap { $0.wasWon } let winCount = wasWonBools.filter { $0 == true }.count let lostCount = wasWonBools.filter { $0 == false }.count return TeamRecord(gamesWon: winCount, gamesLost: lostCount) } } extension Array where Iterator.Element == AtBat { func withResult(_ code: AtBatCode) -> [AtBat] { return filter { $0.resultCode == code } } func withResults(_ codes: [AtBatCode]) -> [AtBat] { return filter { codes.contains($0.resultCode) } } var hitCount: Int { return self.filter { $0.resultCode.isHit }.count } var battingAverageCount: Int { return self.filter { $0.resultCode.countsForBA }.count } var sluggingCount: Double { return reduce(0, { $0 + $1.sluggingValue }) } } extension UUID { func userFacingCode() -> String { let unacceptableCharacters = CharacterSet(charactersIn: "0Oo1IiLl") let strippedString = self.uuidString.trimmingCharacters(in: unacceptableCharacters) return strippedString.last4 } } extension String { subscript(i: Int) -> Character { return self[index(startIndex, offsetBy: i)] } subscript(i: Int) -> String { return String(self[i] as Character) } // subscript(r: Range<Int>) -> String { // let start = index(startIndex, offsetBy: r.lowerBound) // let end = index(startIndex, offsetBy: r.upperBound - r.lowerBound) // return String(self[Range(start ..< end)]) // } var firstLetter: String { return self[0] } var last4: String { return String(suffix(4)) } var isValidEmail: Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } var isValidPhoneNumber: Bool { do { let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue) let matches = detector.matches(in: self, options: [], range: NSMakeRange(0, self.count)) if let res = matches.first { return res.resultType == .phoneNumber && res.range.location == 0 && res.range.length == self.count } else { return false } } catch { return false } } var digits: String { return components(separatedBy: CharacterSet.decimalDigits.inverted).joined() } static var seasonSuggestion: String { let currentMonth = Calendar.current.component(.month, from: Date()) let currentYear = Calendar.current.component(.year, from: Date()) var season = "" switch currentMonth { case 0...5: season = "Spring" case 6...8: season = "Summer" case 9...12: season = "Fall" default: break } return "\(season) \(currentYear)" } // var jerseyNumberFontString: NSAttributedString { // let nsSelf = self as NSString // let firstRange = nsSelf.localizedStandardRange(of: "(") // let secondRange = nsSelf.localizedStandardRange(of: ")") // guard firstRange.length == 1 && secondRange.length == 1 else { return NSAttributedString(string: self) } // // let length = secondRange.location - (firstRange.location + 1) // guard length > 0 else { return NSAttributedString(string: self) } // let numbersRange = NSRange(location: firstRange.location + 1, length: length) // let attributedString = NSMutableAttributedString(string: self) // attributedString.addAttributes([: FontType.jersey.font(withSize: 22)], range: numbersRange) // // return attributedString // } } extension Double { var displayString: String { return String(format: "%.3f", self) } } extension Array { func step(from: Index, to:Index, interval: Int = 1) -> Array<Element> { let strde = stride(from: from, to: to, by: interval) var arr = Array<Element>() for i in strde { arr.append(self[i]) } return arr } func randomElement() -> Element? { guard self.count > 0 else { return nil } let randomIndex = Int.random(0..<self.count) return self[randomIndex] } } extension Int { static func random(_ range: Range<Int>) -> Int { return range.lowerBound + (Int(arc4random_uniform(UInt32(range.upperBound - range.lowerBound)))) } var randomDigitsString: String { guard self > 0 else { return "" } var digitsString = "" for _ in 0..<self { let newDigit = Int(arc4random_uniform(9)) digitsString += String(newDigit) } return digitsString } var doubleValue: Double { return Double(self) } } extension Sequence where Iterator.Element == StringLiteralType { func marshaled() -> JSONObject { var json = JSONObject() for value in self { json[value] = true } return json } func marshaledArray() -> JSONObject { var json = JSONObject() for (index, value) in enumerated() { json["\(index)"] = value } return json } } extension UIViewController { var embededInNavigationController: UINavigationController { return UINavigationController(rootViewController: self) } } extension UIView { func rotate(duration: CFTimeInterval = 2, count: Float = Float.greatestFiniteMagnitude) { let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotation.toValue = CGFloat.pi * 2 rotation.duration = duration rotation.isCumulative = true rotation.repeatCount = count layer.add(rotation, forKey: "rotationAnimation") } func fadeTransition(duration:CFTimeInterval) { let animation:CATransition = CATransition() animation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseInEaseOut) animation.type = kCATransitionFade animation.duration = duration layer.add(animation, forKey: kCATransitionFade) } }
mit
0cbf651b681c4ae0fb54b3cc15923d07
27.899254
114
0.6
4.39059
false
false
false
false
gxf2015/DYZB
DYZB/DYZB/Classes/Main/Model/AncnorGroup.swift
1
740
// // AncnorGroup.swift // DYZB // // Created by guo xiaofei on 2017/8/14. // Copyright © 2017年 guo xiaofei. All rights reserved. // import UIKit import HandyJSON class AncnorGroup: HandyJSON { var room_list : [AncnorModel]? var tag_name : String = "" var icon_name = "home_header_normal" var icon_url : String = "" required init(){} } class AncnorModel: HandyJSON { var room_id : Int = 0 var vertical_src : String = "" var icon_name = "home_header_normal" var isVertical : Int = 0 var room_name : String = "" var nickname : String = "" var online : Int = 0 var anchor_city : String = "" required init(){} }
mit
95fa392873080fec7c907a8202a360f4
15.377778
55
0.56038
3.648515
false
false
false
false
huonw/swift
test/SILGen/keypath_application.swift
1
4690
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s class A {} class B {} protocol P {} protocol Q {} // CHECK-LABEL: sil hidden @{{.*}}loadable func loadable(readonly: A, writable: inout A, value: B, kp: KeyPath<A, B>, wkp: WritableKeyPath<A, B>, rkp: ReferenceWritableKeyPath<A, B>) { // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: [[ROOT_COPY:%.*]] = copy_value %0 // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[KP_COPY:%.*]] = copy_value %3 // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly // CHECK: [[BORROWED_KP_COPY:%.*]] = begin_borrow [[KP_COPY]] // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B // CHECK: apply [[PROJECT]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[BORROWED_KP_COPY]]) // CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]] // CHECK: destroy_value [[RESULT]] _ = readonly[keyPath: kp] _ = writable[keyPath: kp] _ = readonly[keyPath: wkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: wkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: rkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: rkp] // CHECK: function_ref @{{.*}}_projectKeyPathWritable writable[keyPath: wkp] = value // CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable readonly[keyPath: rkp] = value // CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden @{{.*}}addressOnly func addressOnly(readonly: P, writable: inout P, value: Q, kp: KeyPath<P, Q>, wkp: WritableKeyPath<P, Q>, rkp: ReferenceWritableKeyPath<P, Q>) { // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: kp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: kp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: wkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: wkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: rkp] // CHECK: function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: rkp] // CHECK: function_ref @{{.*}}_projectKeyPathWritable writable[keyPath: wkp] = value // CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable readonly[keyPath: rkp] = value // CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden @{{.*}}reabstracted func reabstracted(readonly: @escaping () -> (), writable: inout () -> (), value: @escaping (A) -> B, kp: KeyPath<() -> (), (A) -> B>, wkp: WritableKeyPath<() -> (), (A) -> B>, rkp: ReferenceWritableKeyPath<() -> (), (A) -> B>) { // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: kp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: kp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: wkp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: wkp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = readonly[keyPath: rkp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly _ = writable[keyPath: rkp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathWritable writable[keyPath: wkp] = value // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable readonly[keyPath: rkp] = value // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden @{{.*}}partial func partial<A>(valueA: A, valueB: Int, pkpA: PartialKeyPath<A>, pkpB: PartialKeyPath<Int>, akp: AnyKeyPath) { // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: pkpA] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: pkpB] }
apache-2.0
7bf89970743354eff468ef58fe3e4e85
36.822581
87
0.590832
4.1875
false
false
false
false
seanhenry/rescodegen
spec/files/plural/Strings.swift
1
718
import Foundation struct Strings { enum Singular: String { case first_key = "First key" case key_with_format = "Key with format %ld" case key_without_description = "Key without description" var localizedString: String { return NSLocalizedString(rawValue, comment: "") } } enum Plural: String { case downloads_remaining = "%lu downloads remaining" case souls_days = "%lu souls, %lu days" func localizedString(args: CVarArgType...) -> String { let localized = NSLocalizedString(rawValue, comment: "") return String(format: localized, locale: NSLocale.currentLocale(), arguments: args) } } }
mit
668367760588acd7ceb827afd2576a69
28.916667
95
0.615599
4.786667
false
false
false
false
garethknowles/JBDatePicker
JBDatePicker/Classes/JBDatePickerWeekDaysView.swift
1
5199
// // JBDatePickerWeekDaysView.swift // JBDatePicker // // Created by Joost van Breukelen on 24-10-16. // Copyright © 2016 Joost van Breukelen. All rights reserved. // import UIKit public final class JBDatePickerWeekDaysView: UIStackView { // MARK: - Properties private weak var datePickerView: JBDatePickerView! private var firstWeekDay: JBWeekDay! private var weekdayNameSymbols = [String]() private var weekdayLabels = [UILabel]() private var weekdayLabelTextColor: UIColor! // MARK: - Initialization public init(datePickerView: JBDatePickerView) { self.datePickerView = datePickerView super.init(frame: .zero) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: - Setup private func setup() { guard datePickerView != nil else {return} //stackView setup self.axis = .horizontal self.distribution = .fillEqually self.translatesAutoresizingMaskIntoConstraints = false //get preferences firstWeekDay = datePickerView.delegate?.firstWeekDay //setup appearance self.weekdayLabelTextColor = datePickerView.delegate?.colorForWeekDaysViewText //get weekday name symbols if let preferredLanguage = Bundle.main.preferredLocalizations.first { if datePickerView.delegate?.shouldLocalize == true { datePickerView.calendar.locale = Locale(identifier: preferredLanguage) } } weekdayNameSymbols = datePickerView.calendar.shortWeekdaySymbols //adjust order of weekDayNameSymbols if needed let firstWeekdayIndex = firstWeekDay.rawValue - 1 if firstWeekdayIndex >= 0 { //create new array order by slicing according to firstweekday let sliceOne = weekdayNameSymbols[firstWeekdayIndex...6] let sliceTwo = weekdayNameSymbols[0..<firstWeekdayIndex] weekdayNameSymbols = Array(sliceOne + sliceTwo) } //create and place labels. Setup constraints for i in 0...6 { //this containerView is used to prevent visible stretching of the weekDaylabel while turning the device let labelContainerView = UIView() labelContainerView.backgroundColor = datePickerView.delegate?.colorForWeekDaysViewBackground self.addArrangedSubview(labelContainerView) let weekDayLabel = UILabel() weekDayLabel.textAlignment = .center weekDayLabel.text = weekdayNameSymbols[i].uppercased() weekDayLabel.textColor = weekdayLabelTextColor weekDayLabel.translatesAutoresizingMaskIntoConstraints = false weekdayLabels.append(weekDayLabel) labelContainerView.addSubview(weekDayLabel) weekDayLabel.centerXAnchor.constraint(equalTo: labelContainerView.centerXAnchor).isActive = true weekDayLabel.centerYAnchor.constraint(equalTo: labelContainerView.centerYAnchor).isActive = true } } public override func layoutSubviews() { updateLayout() } func updateLayout() { //get preferred font guard let preferredFont = datePickerView.delegate?.fontForWeekDaysViewText else { return } //get preferred size let preferredSize = preferredFont.fontSize let sizeOfFont: CGFloat //calculate fontsize to be used switch preferredSize { case .verySmall: sizeOfFont = min(frame.size.width, frame.size.height) / 4 case .small: sizeOfFont = min(frame.size.width, frame.size.height) / 3.5 case .medium: sizeOfFont = min(frame.size.width, frame.size.height) / 3 case .large: sizeOfFont = min(frame.size.width, frame.size.height) / 2 case .veryLarge: sizeOfFont = min(frame.size.width, frame.size.height) / 1.5 } //get font to be used let fontToUse: UIFont switch preferredFont.fontName.isEmpty { case true: fontToUse = UIFont.systemFont(ofSize: sizeOfFont, weight: UIFontWeightRegular) case false: if let customFont = UIFont(name: preferredFont.fontName, size: sizeOfFont) { fontToUse = customFont } else { print("custom font '\(preferredFont.fontName)' for weekdaysView not available. JBDatePicker will use system font instead") fontToUse = UIFont.systemFont(ofSize: sizeOfFont, weight: UIFontWeightRegular) } } //set text and font on labels for (index, label) in weekdayLabels.enumerated() { let labelText = weekdayNameSymbols[index] label.attributedText = NSMutableAttributedString(string: labelText, attributes:[NSFontAttributeName:fontToUse]) } } }
mit
589beeedf5361f4a9fd349e101d9bf83
35.097222
139
0.63409
5.380952
false
false
false
false
zjjzmw1/myGifSwift
myGifSwift/CodeFragment/Category/String+JCString.swift
1
11738
// // String+JCString.swift // JCSwiftKitDemo // // Created by molin.JC on 2017/1/6. // Copyright © 2017年 molin. All rights reserved. // import Foundation import UIKit import SwiftDate extension String { /// 以下这几种情况都认为的空 public static func isEmptyString(str: String?) -> Bool { if str == nil { return true } else if (str == "") { return true } else if (str == "<null>") { return true } else if (str == "(null)") { return true } else if (str == "null") { return true } return false } /// 移除两个字符串之间的字符串后的结果 public func removeAllSubString(beginStr: String, endStr: String) -> String { NSLog(self) var last = String.init(format: "%@",self) for _ in 0...self.components(separatedBy: beginStr).count + 1 { if last.contain(ofString: beginStr) && last.contain(ofString: endStr) { let tempStr: NSString = NSString.init(string: last) let starRange = tempStr.range(of: beginStr) let endRange = tempStr.range(of: endStr) let range: NSRange! = NSMakeRange(starRange.location, endRange.location - starRange.location + 1) let lastStr: String? = tempStr.substring(with: range) last = tempStr.replacingOccurrences(of: lastStr ?? "", with: "") } else { last = self } } return last } /// 移除前两个两个字符串之间的字符串后的结果 public func removeFirstSubString(beginStr: String, endStr: String) -> String { var last = String.init(format: "%@",self) if last.contain(ofString: beginStr) && last.contain(ofString: endStr) { let tempStr: NSString = NSString.init(string: last) let starRange = tempStr.range(of: beginStr) let endRange = tempStr.range(of: endStr) let range: NSRange! = NSMakeRange(starRange.location, endRange.location - starRange.location + 1) let lastStr: String? = tempStr.substring(with: range) last = tempStr.replacingOccurrences(of: lastStr ?? "", with: "") } else { last = self } return last } /// 获取两个字符串直接的字符串 public func getSubStr(beginStr: String, endStr: String) -> String { let tempStr: NSString = NSString.init(string: self) let starRange = tempStr.range(of: beginStr) let endRange = tempStr.range(of: endStr) let range: NSRange! = NSMakeRange(starRange.location + starRange.length, endRange.location - starRange.location - starRange.length) let lastStr: String? = tempStr.substring(with: range) return lastStr ?? self } public var length: Int { get { return self.characters.count; } } func toNumber() -> NSNumber? { let number = NumberFormatter.init().number(from: self); return number; } func toInt() -> Int? { let number = self.toNumber(); if (number != nil) { return number?.intValue; } return 0; } func toFloat() -> Float? { let number = self.toNumber(); if (number != nil) { return number?.floatValue; } return 0; } func toDouble() -> Double? { let number = self.toNumber(); if (number != nil) { return number?.doubleValue; } return 0; } func toBool() -> Bool? { let number = self.toInt()!; if (number > 0) { return true; } let lowercased = self.lowercased() switch lowercased { case "true", "yes", "1": return true; case "false", "no", "0": return false; default: return false; } } /// UTF8StringEncoding编码转换成Data func dataUsingUTF8StringEncoding() -> Data? { return self.data(using: String.Encoding.utf8); } /// 获取当前的日期,格式为:yyyy-MM-dd HH:mm:ss static func dateString() -> String { return NSDate.init().string(); } /// 获取当前的日期, 格式自定义 func dateString(format: String) -> String { return NSDate.init().stringWithFormat(format: format); } /// 时间戳字符串转换为日期格式 func toDateStr(format: String?) -> String { var formatStr = "yyyy-MM-dd" if (format != nil) { formatStr = format! } //转换为时间 let timeInterval:TimeInterval = TimeInterval(self)! let date = Date(timeIntervalSince1970: timeInterval) //格式话输出 let dformatter = DateFormatter() dformatter.dateFormat = formatStr return dformatter.string(from: date) } /// 两个时间戳的差几天 func toDays(endDateString: String?) -> Int { if endDateString == nil { return 0 } else { let dformatter = DateFormatter() dformatter.dateFormat = "yyyy-MM-dd" let timeInterval0:TimeInterval = TimeInterval(self)! let date0 = Date(timeIntervalSince1970: timeInterval0) let timeInterval1:TimeInterval = TimeInterval(self)! let date1 = Date(timeIntervalSince1970: timeInterval1) if date0 == nil { return 0 } let timeInter = date1.timeIntervalSince(date0)/(3600*24) return Int(timeInter) } } /// ISO8601格式的字符串转换为 固定格式的字符串 func toDateStrISO8601(formate: String?) -> String { var format = "yyyy-MM-dd" if formate != nil { format = formate! } let isoFormate = ISO8601DateTimeFormatter.init() isoFormate.formatOptions = .withInternetDateTimeExtended let date = isoFormate.date(from: self) let dateStr = date?.stringWithFormat(format: format) ?? "" return dateStr } /// ISO8601格式的字符串转换为 固定格式的字符串 func toDateStrISO8601ToDate(formate: String?) -> Date { let isoFormate = ISO8601DateTimeFormatter.init() isoFormate.formatOptions = .withInternetDateTimeExtended let date = isoFormate.date(from: self) if let date = date { return date } else { return Date() } } /// 两个时间戳的差几天 func toDaysISO8601(endDateString: String?) -> Int { if endDateString == nil { return 0 } else { let isoFormate = ISO8601DateTimeFormatter.init() isoFormate.formatOptions = .withInternetDateTimeExtended let date0 = isoFormate.date(from: self) let date1 = isoFormate.date(from: endDateString!) if date0 == nil || date1 == nil { return 0 } let timeInter = (date1?.timeIntervalSince(date0!))!/(3600*24) return Int(timeInter) } } func sizeFor(size: CGSize, font: UIFont = FONT_PingFang(fontSize: 15)) -> CGSize { return self.sizeFor(size: size, font: font, lineBreakMode: .byWordWrapping) } /// 根据字体大小,所要显示的size,以及字段样式来计算文本的size /// /// - Parameters: /// - font: 字体 /// - size: 所要显示的size /// - lineBreakMode: 字段样式 /// - Returns: CGSize大小 func sizeFor(size: CGSize, font: UIFont = FONT_PingFang(fontSize: 15), lineBreakMode: NSLineBreakMode = NSLineBreakMode.byWordWrapping) -> CGSize { var attr = Dictionary<String, Any>.init(); attr[NSFontAttributeName] = font; if (lineBreakMode != NSLineBreakMode.byWordWrapping) { let paragraphStyle = NSMutableParagraphStyle.init(); paragraphStyle.lineBreakMode = lineBreakMode; attr[NSParagraphStyleAttributeName] = paragraphStyle; } let rect = (self as NSString).boundingRect(with: size, options: [NSStringDrawingOptions.usesLineFragmentOrigin, NSStringDrawingOptions.usesFontLeading], attributes: attr, context: nil); return rect.size; } /// 去掉头尾的空格 func stringByTrimSpace() -> String { let set = CharacterSet.whitespacesAndNewlines; return self.trimmingCharacters(in: set); } /// 替换掉某个字符串 /// /// - Parameters: /// - replacement: 要替换成的字符串 /// - targets: 要被替换的字符串 /// - Returns: String func stringReplacement(replacement: String, targets: String...) -> String? { var complete = self; for target in targets { complete = complete.replacingOccurrences(of: target, with: replacement); } return complete; } /// 是否包含某字符串 func contain(ofString: String) -> Bool { return (self.range(of: ofString) != nil); } /// 根据正则表达式判断 /// /// - Parameter format: 正则表达式的样式 /// - Returns: Bool func evaluate(format: String) -> Bool { let predicate = NSPredicate.init(format: "SELF MATCHES %@", format); return predicate.evaluate(with: self); } /// 邮箱的正则表达式 func regexpEmail() -> Bool { let format = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; return self.evaluate(format: format); } /// IP地址的正则表达式 func regexpIp() -> Bool { let format = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)" return self.evaluate(format: format); } /// HTTP链接 (例如 http://www.baidu.com ) func regexpHTTP() -> Bool { let format = "([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.\',;]*)?" return self.evaluate(format: format); } /// UUID static func stringWithUUID() -> String { let uuid = CFUUIDCreate(nil); let str = CFUUIDCreateString(nil, uuid); return str! as String; } /// 判断是否是为整数 func isPureInteger() -> Bool { let scanner = Scanner.init(string: self); var integerValue: Int?; return scanner.scanInt(&integerValue!) && scanner.isAtEnd; } /// 判断是否为浮点数,可做小数判断 func isPureFloat() -> Bool { let scanner = Scanner.init(string: self); var floatValue: Float?; return scanner.scanFloat(&floatValue!) && scanner.isAtEnd; } /// 输出格式:123,456;每隔三个就有"," static func stringFormatterWithDecimal(number: NSNumber) -> String { return String.stringFormatter(style: NumberFormatter.Style.decimal, number: number); } /// number转换百分比: 12,345,600% static func stringFormatterWithPercent(number: NSNumber) -> String { return String.stringFormatter(style: NumberFormatter.Style.percent, number: number); } /// 设置NSNumber输出的格式 /// /// - Parameters: /// - style: 格式 /// - number: NSNumber数据 /// - Returns: String static func stringFormatter(style: NumberFormatter.Style, number: NSNumber) -> String { let formatter = NumberFormatter.init(); formatter.numberStyle = style; return formatter.string(from: number)!; } }
mit
68799c8142bdf52c18bea5d89e4a66ce
31.851632
193
0.567338
4.215918
false
false
false
false
rvanmelle/QuickSettings
SettingsExample/QuickSettings/QSSettingsOptionsViewController.swift
1
2321
// // SettingsOptionsViewController.swift // SettingsExample // // Created by Reid van Melle on 2016-10-30. // Copyright © 2016 Reid van Melle. All rights reserved. // import Foundation // Settings Options protocol QSSettingsOptionsViewControllerDelegate : class { func settingsOptionsViewController(settingsVC: QSSettingsOptionsViewController, didSelect option: String, for key: String) } class QSSettingsOptionsViewController: QSSettingsBaseViewController { weak var delegate: QSSettingsOptionsViewControllerDelegate? fileprivate var options: QSSettingsOptions fileprivate var selected: String fileprivate var optionKey: String init(options: QSSettingsOptions, key: String, selected: String, delegate: QSSettingsOptionsViewControllerDelegate) { self.selected = selected self.options = options self.optionKey = key //super.init(nibName: nil, bundle: nil) super.init(style: .grouped) self.delegate = delegate } required init?(coder aDecoder: NSCoder) { fatalError() } override func viewDidLoad() { super.viewDidLoad() self.tableView.dataSource = self self.tableView.delegate = self } } extension QSSettingsOptionsViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) selected = cell!.textLabel!.text! delegate?.settingsOptionsViewController(settingsVC: self, didSelect: selected, for: optionKey) tableView.reloadData() } } extension QSSettingsOptionsViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.options.count } public override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return options.description(for: selected) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = QSSettingsTableCell.dequeue(tableView, for: indexPath) let val = options.options[indexPath.row] cell.textLabel?.text = val cell.accessoryType = val == selected ? .checkmark : .none return cell } }
mit
b7dc085fc335e4bcc8edd1bff543ba0c
31.676056
126
0.714224
4.989247
false
false
false
false
tkester/swift-algorithm-club
Knuth-Morris-Pratt/KnuthMorrisPratt.playground/Contents.swift
1
3435
//: Playground - noun: a place where people can play // last checked with Xcode 9.0b4 #if swift(>=4.0) print("Hello, Swift4!") #endif func ZetaAlgorithm(ptnr: String) -> [Int]? { let pattern = Array(ptnr.characters) let patternLength: Int = pattern.count guard patternLength > 0 else { return nil } var zeta: [Int] = [Int](repeating: 0, count: patternLength) var left: Int = 0 var right: Int = 0 var k_1: Int = 0 var betaLength: Int = 0 var textIndex: Int = 0 var patternIndex: Int = 0 for k in 1 ..< patternLength { if k > right { patternIndex = 0 while k + patternIndex < patternLength && pattern[k + patternIndex] == pattern[patternIndex] { patternIndex = patternIndex + 1 } zeta[k] = patternIndex if zeta[k] > 0 { left = k right = k + zeta[k] - 1 } } else { k_1 = k - left + 1 betaLength = right - k + 1 if zeta[k_1 - 1] < betaLength { zeta[k] = zeta[k_1 - 1] } else if zeta[k_1 - 1] >= betaLength { textIndex = betaLength patternIndex = right + 1 while patternIndex < patternLength && pattern[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } zeta[k] = patternIndex - k left = k right = patternIndex - 1 } } } return zeta } extension String { func indexesOf(ptnr: String) -> [Int]? { let text = Array(self.characters) let pattern = Array(ptnr.characters) let textLength: Int = text.count let patternLength: Int = pattern.count guard patternLength > 0 else { return nil } var suffixPrefix: [Int] = [Int](repeating: 0, count: patternLength) var textIndex: Int = 0 var patternIndex: Int = 0 var indexes: [Int] = [Int]() /* Pre-processing stage: computing the table for the shifts (through Z-Algorithm) */ let zeta = ZetaAlgorithm(ptnr: ptnr) for patternIndex in (1 ..< patternLength).reversed() { textIndex = patternIndex + zeta![patternIndex] - 1 suffixPrefix[textIndex] = zeta![patternIndex] } /* Search stage: scanning the text for pattern matching */ textIndex = 0 patternIndex = 0 while textIndex + (patternLength - patternIndex - 1) < textLength { while patternIndex < patternLength && text[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } if patternIndex == patternLength { indexes.append(textIndex - patternIndex) } if patternIndex == 0 { textIndex = textIndex + 1 } else { patternIndex = suffixPrefix[patternIndex - 1] } } guard !indexes.isEmpty else { return nil } return indexes } } /* Examples */ let dna = "ACCCGGTTTTAAAGAACCACCATAAGATATAGACAGATATAGGACAGATATAGAGACAAAACCCCATACCCCAATATTTTTTTGGGGAGAAAAACACCACAGATAGATACACAGACTACACGAGATACGACATACAGCAGCATAACGACAACAGCAGATAGACGATCATAACAGCAATCAGACCGAGCGCAGCAGCTTTTAAGCACCAGCCCCACAAAAAACGACAATFATCATCATATACAGACGACGACACGACATATCACACGACAGCATA" dna.indexesOf(ptnr: "CATA") // [20, 64, 130, 140, 166, 234, 255, 270] let concert = "🎼🎹🎹🎸🎸🎻🎻🎷🎺🎤👏👏👏" concert.indexesOf(ptnr: "🎻🎷") // [6]
mit
034179a4a4ef5aa76ab42d7e6f617874
25.904762
286
0.60531
3.466258
false
false
false
false
L-Zephyr/Drafter
Sources/Drafter/AST/Common/AccessControlLevel.swift
1
1711
// // Created by LZephyr on 2018/9/8. // import Foundation /// 访问权限,OC只有`public`和`private` enum AccessControlLevel: Int, AutoCodable { case `private` = 0 case `fileprivate` = 1 case `internal` = 2 case `public` = 3 case `open` = 4 } extension AccessControlLevel: ExpressibleByStringLiteral { public init(stringLiteral value: String) { switch value { case "open": self = .open case "public": self = .public case "internal": self = .internal case "fileprivate": self = .fileprivate case "private": self = .private default: self = .internal } } } extension AccessControlLevel: CustomStringConvertible { var description: String { switch self { case .open: return "open" case .public: return "public" case .internal: return "internal" case .fileprivate: return "fileprivate" case .private: return "private" } } } extension AccessControlLevel: Comparable { static func ==(_ lhs: AccessControlLevel, _ rhs: AccessControlLevel) -> Bool { switch (lhs, rhs) { case (.open, .open): fallthrough case (.public, .public): fallthrough case (.internal, .internal): fallthrough case (.fileprivate, .fileprivate): fallthrough case (.private, .private): return true default: return false } } static func <(_ lhs: AccessControlLevel, _ rhs: AccessControlLevel) -> Bool { return lhs.rawValue < rhs.rawValue } }
mit
b710ce548f6609b3270f5406c618c01d
23.57971
82
0.556342
4.631148
false
false
false
false
bitrise-io/sample-test-ios-quick
BitriseTestingSample/BitriseTestingSample/AppDelegate.swift
3
6167
// // AppDelegate.swift // BitriseTestingSample // // Created by Viktor Benei on 6/17/15. // Copyright (c) 2015 Bitrise. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.bitrise.BitriseTestingSample" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("BitriseTestingSample", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("BitriseTestingSample.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
7fce87c7b17b7e8f7f784b981c4085ed
54.558559
290
0.717529
5.752799
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/TXTReader/BookDetail/Views/BookDetailHeader.swift
1
2335
// // BookDetailHeader.swift // zhuishushenqi // // Created by Nory Cao on 16/10/4. // Copyright © 2016年 QS. All rights reserved. // import UIKit typealias AddButtonAction = (_ isSelected:Bool,_ model:BookDetail)->Void class BookDetailHeader: UIView { var addBtnAction:AddButtonAction? var startReading:AddButtonAction? var model:BookDetail?{ didSet{ name.text = model?.title if let book = model { let exist = ZSBookManager.shared.existBookId(bookId: book._id) if exist{ addButton.isSelected = true } } authorWidth.text = model?.author let widthttt = (authorWidth.text ?? "").qs_width(UIFont.boldSystemFont(ofSize: 13), height: 21) authorWidthh.constant = widthttt typeWidth.text = model?.minorCate == "" ? model?.majorCate : model?.minorCate let typeConst = (typeWidth.text ?? "").qs_width(UIFont.systemFont(ofSize: 13), height: 21) typeWidthConst.constant = typeConst + 5 words.text = "\(Int(model?.wordCount ?? "0")!/10000)万字" let created = model?.updated ?? "2014-02-23T16:48:18.179Z" self.new.qs_setCreateTime(createTime: created,append: "") self.icon.qs_setBookCoverWithURLString(urlString: self.model?.cover ?? "qqqqqqqq") } } @IBOutlet weak var name: UILabel! @IBOutlet weak var icon: UIImageView! @IBOutlet weak var authorWidthh: NSLayoutConstraint! @IBOutlet weak var new: UILabel! @IBOutlet weak var words: UILabel! @IBOutlet weak var authorWidth: UILabel! @IBOutlet weak var typeWidthConst: NSLayoutConstraint! @IBOutlet weak var typeWidth: UILabel! @IBOutlet weak var addButton: UIButton! @IBAction func readingStart(_ sender: UIButton) { if let action = startReading { if let model = self.model { action(sender.isSelected,model) } } } @IBAction func addBook(_ sender: UIButton) { sender.isSelected = !sender.isSelected if let action = addBtnAction { if let model = self.model { action(sender.isSelected,model) } } } }
mit
27a2cb8274020e8a3cc88884a94b2b35
32.257143
107
0.591924
4.311111
false
false
false
false
adamcohenrose/fastlane
fastlane/swift/SocketClient.swift
5
11141
// // SocketClient.swift // FastlaneSwiftRunner // // Created by Joshua Liebowitz on 7/30/17. // Copyright © 2017 Joshua Liebowitz. All rights reserved. // // // ** NOTE ** // This file is provided by fastlane and WILL be overwritten in future updates // If you want to add extra functionality to this project, create a new file in a // new group so that it won't be marked for upgrade // import Foundation public enum SocketClientResponse: Error { case alreadyClosedSockets case malformedRequest case malformedResponse case serverError case clientInitiatedCancelAcknowledged case commandTimeout(seconds: Int) case connectionFailure case success(returnedObject: String?, closureArgumentValue: String?) } class SocketClient: NSObject { enum SocketStatus { case ready case closed } static let connectTimeoutSeconds = 2 static let defaultCommandTimeoutSeconds = 3_600 // Hopefully 1 hr is enough ¯\_(ツ)_/¯ static let doneToken = "done" // TODO: remove these static let cancelToken = "cancelFastlaneRun" fileprivate var inputStream: InputStream! fileprivate var outputStream: OutputStream! fileprivate var cleaningUpAfterDone = false fileprivate let dispatchGroup: DispatchGroup = DispatchGroup() fileprivate let commandTimeoutSeconds: Int private let streamQueue: DispatchQueue private let host: String private let port: UInt32 let maxReadLength = 65_536 // max for ipc on 10.12 is kern.ipc.maxsockbuf: 8388608 ($sysctl kern.ipc.maxsockbuf) weak private(set) var socketDelegate: SocketClientDelegateProtocol? public private(set) var socketStatus: SocketStatus // localhost only, this prevents other computers from connecting init(host: String = "localhost", port: UInt32 = 2000, commandTimeoutSeconds: Int = defaultCommandTimeoutSeconds, socketDelegate: SocketClientDelegateProtocol) { self.host = host self.port = port self.commandTimeoutSeconds = commandTimeoutSeconds self.streamQueue = DispatchQueue(label: "streamQueue") self.socketStatus = .closed self.socketDelegate = socketDelegate super.init() } func connectAndOpenStreams() { var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? self.streamQueue.async { CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, self.host as CFString, self.port, &readStream, &writeStream) self.inputStream = readStream!.takeRetainedValue() self.outputStream = writeStream!.takeRetainedValue() self.inputStream.delegate = self self.outputStream.delegate = self self.inputStream.schedule(in: .main, forMode: .defaultRunLoopMode) self.outputStream.schedule(in: .main, forMode: .defaultRunLoopMode) } self.dispatchGroup.enter() self.streamQueue.async { self.inputStream.open() } self.dispatchGroup.enter() self.streamQueue.async { self.outputStream.open() } let secondsToWait = DispatchTimeInterval.seconds(SocketClient.connectTimeoutSeconds) let connectTimeout = DispatchTime.now() + secondsToWait let timeoutResult = self.dispatchGroup.wait(timeout: connectTimeout) let failureMessage = "Couldn't connect to ruby process within: \(SocketClient.connectTimeoutSeconds) seconds" let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait) guard success else { self.socketDelegate?.commandExecuted(serverResponse: .connectionFailure) return } self.socketStatus = .ready self.socketDelegate?.connectionsOpened() } public func send(rubyCommand: RubyCommandable) { verbose(message: "sending: \(rubyCommand.json)") send(string: rubyCommand.json) } public func sendComplete() { closeSession(sendAbort: true) } private func testDispatchTimeoutResult(_ timeoutResult: DispatchTimeoutResult, failureMessage: String, timeToWait: DispatchTimeInterval) -> Bool { switch timeoutResult { case .success: return true case .timedOut: log(message: "Timeout: \(failureMessage)") if case .seconds(let seconds) = timeToWait { socketDelegate?.commandExecuted(serverResponse: .commandTimeout(seconds: seconds)) } return false } } private func stopInputSession() { inputStream.close() } private func stopOutputSession() { outputStream.close() } private func sendThroughQueue(string: String) { streamQueue.async { let data = string.data(using: .utf8)! _ = data.withUnsafeBytes { self.outputStream.write($0, maxLength: data.count) } } } private func privateSend(string: String) { self.dispatchGroup.enter() sendThroughQueue(string: string) let timeoutSeconds = self.cleaningUpAfterDone ? 1 : self.commandTimeoutSeconds let timeToWait = DispatchTimeInterval.seconds(timeoutSeconds) let commandTimeout = DispatchTime.now() + timeToWait let timeoutResult = self.dispatchGroup.wait(timeout: commandTimeout) _ = testDispatchTimeoutResult(timeoutResult, failureMessage: "Ruby process didn't return after: \(SocketClient.connectTimeoutSeconds) seconds", timeToWait: timeToWait) } private func send(string: String) { guard !self.cleaningUpAfterDone else { // This will happen after we abort if there are commands waiting to be executed // Need to check state of SocketClient in command runner to make sure we can accept `send` socketDelegate?.commandExecuted(serverResponse: .alreadyClosedSockets) return } if string == SocketClient.doneToken { self.cleaningUpAfterDone = true } privateSend(string: string) } func closeSession(sendAbort: Bool = true) { self.socketStatus = .closed stopInputSession() if sendAbort { send(rubyCommand: ControlCommand(commandType: .done)) } stopOutputSession() self.socketDelegate?.connectionsClosed() } } extension SocketClient: StreamDelegate { func stream(_ aStream: Stream, handle eventCode: Stream.Event) { guard !self.cleaningUpAfterDone else { // Still getting response from server eventhough we are done. // No big deal, we're closing the streams anyway. // That being said, we need to balance out the dispatchGroups self.dispatchGroup.leave() return } if aStream === self.inputStream { switch eventCode { case Stream.Event.openCompleted: self.dispatchGroup.leave() case Stream.Event.errorOccurred: verbose(message: "input stream error occurred") closeSession(sendAbort: true) case Stream.Event.hasBytesAvailable: read() case Stream.Event.endEncountered: // nothing special here break case Stream.Event.hasSpaceAvailable: // we don't care about this break default: verbose(message: "input stream caused unrecognized event: \(eventCode)") } } else if aStream === self.outputStream { switch eventCode { case Stream.Event.openCompleted: self.dispatchGroup.leave() case Stream.Event.errorOccurred: // probably safe to close all the things because Ruby already disconnected verbose(message: "output stream recevied error") break case Stream.Event.endEncountered: // nothing special here break case Stream.Event.hasSpaceAvailable: // we don't care about this break default: verbose(message: "output stream caused unrecognized event: \(eventCode)") } } } func read() { var buffer = [UInt8](repeating: 0, count: maxReadLength) var output = "" while self.inputStream!.hasBytesAvailable { let bytesRead: Int = inputStream!.read(&buffer, maxLength: buffer.count) if bytesRead >= 0 { output += NSString(bytes: UnsafePointer(buffer), length: bytesRead, encoding: String.Encoding.utf8.rawValue)! as String } else { verbose(message: "Stream read() error") } } processResponse(string: output) } func handleFailure(message: [String]) { log(message: "Encountered a problem: \(message.joined(separator:"\n"))") let shutdownCommand = ControlCommand(commandType: .cancel(cancelReason: .serverError)) self.send(rubyCommand: shutdownCommand) } func processResponse(string: String) { guard string.count > 0 else { self.socketDelegate?.commandExecuted(serverResponse: .malformedResponse) self.handleFailure(message: ["empty response from ruby process"]) return } let responseString = string.trimmingCharacters(in: .whitespacesAndNewlines) let socketResponse = SocketResponse(payload: responseString) verbose(message: "response is: \(responseString)") switch socketResponse.responseType { case .clientInitiatedCancel: self.socketDelegate?.commandExecuted(serverResponse: .clientInitiatedCancelAcknowledged) self.closeSession(sendAbort: false) case .failure(let failureInformation): self.socketDelegate?.commandExecuted(serverResponse: .serverError) self.handleFailure(message: failureInformation) case .parseFailure(let failureInformation): self.socketDelegate?.commandExecuted(serverResponse: .malformedResponse) self.handleFailure(message: failureInformation) case .readyForNext(let returnedObject, let closureArgumentValue): self.socketDelegate?.commandExecuted(serverResponse: .success(returnedObject: returnedObject, closureArgumentValue: closureArgumentValue)) // cool, ready for next command break } self.dispatchGroup.leave() // should now pull the next piece of work } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.2]
mit
0333444a8923f866148640e5ede6ae45
35.392157
175
0.633261
5.225716
false
false
false
false
CatchChat/Yep
Yep/Views/Cells/GeniusInterview/GeniusInterviewCell.swift
1
1479
// // GeniusInterviewCell.swift // Yep // // Created by NIX on 16/5/27. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit import YepKit import Navi class GeniusInterviewCell: UITableViewCell { @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var numberLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var detailLabel: UILabel! @IBOutlet weak var accessoryImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() numberLabel.font = UIFont.systemFontOfSize(16) numberLabel.textColor = UIColor.yepTintColor() titleLabel.font = UIFont.systemFontOfSize(16) titleLabel.textColor = UIColor.blackColor() detailLabel.font = UIFont.systemFontOfSize(13) detailLabel.textColor = UIColor(red: 142/255.0, green: 142/255.0, blue: 147/255.0, alpha: 1) accessoryImageView.tintColor = UIColor.yepCellAccessoryImageViewTintColor() } func configure(withGeniusInterview geniusInterview: GeniusInterview) { let avatar = PlainAvatar(avatarURLString: geniusInterview.user.avatarURLString, avatarStyle: miniAvatarStyle) avatarImageView.navi_setAvatar(avatar, withFadeTransitionDuration: avatarFadeTransitionDuration) numberLabel.text = String(format: "#%02d", geniusInterview.number) titleLabel.text = geniusInterview.title detailLabel.text = geniusInterview.detail } }
mit
c0e6ba499f6aca655c2da356c464de28
31.086957
117
0.726287
4.513761
false
false
false
false
yq616775291/DiliDili-Fun
Pods/Kingfisher/Sources/ImageView+Kingfisher.swift
2
18490
// // ImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2016 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(OSX) import AppKit typealias ImageView = NSImageView public typealias IndicatorView = NSProgressIndicator #else import UIKit typealias ImageView = UIImageView public typealias IndicatorView = UIActivityIndicatorView #endif // MARK: - Set Images /** * Set image to use from web. */ extension ImageView { /** Set an image with a resource. It will ask for Kingfisher's manager to get the image for the `cacheKey` property in `resource`. The memory and disk will be searched first. If the manager does not find it, it will try to download the image at the `resource.downloadURL` and store it with `resource.cacheKey` for next use. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL. It will ask for Kingfisher's manager to get the image for the URL. The memory and disk will be searched first with `URL.absoluteString` as the cache key. If the manager does not find it, it will try to download the image at this URL and store the image with `URL.absoluteString` as cache key for next use. If you need to specify the key other than `URL.absoluteString`, please use resource version of these APIs with `resource.cacheKey` set to what you want. - parameter URL: The URL of image. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a resource and a placeholder image. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: Image?) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL and a placeholder image. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: Image?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a resource, a placaholder image and options. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL, a placaholder image and options. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retrieving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a resource, a placeholder image, options and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(resource, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL, a placeholder image, options and completion handler. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ public func kf_setImageWithResource(resource: Resource, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { let showIndicatorWhenLoading = kf_showIndicatorWhenLoading var indicator: IndicatorView? = nil if showIndicatorWhenLoading { indicator = kf_indicator indicator?.hidden = false indicator?.kf_startAnimating() } image = placeholderImage kf_setWebURL(resource.downloadURL) let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo, progressBlock: { receivedSize, totalSize in if let progressBlock = progressBlock { progressBlock(receivedSize: receivedSize, totalSize: totalSize) } }, completionHandler: {[weak self] image, error, cacheType, imageURL in dispatch_async_safely_to_main_queue { guard let sSelf = self where imageURL == sSelf.kf_webURL else { completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) return } sSelf.kf_setImageTask(nil) guard let image = image else { indicator?.kf_stopAnimating() completionHandler?(image: nil, error: error, cacheType: cacheType, imageURL: imageURL) return } if let transitionItem = optionsInfo?.kf_firstMatchIgnoringAssociatedValue(.Transition(.None)), case .Transition(let transition) = transitionItem where cacheType == .None { #if !os(OSX) UIView.transitionWithView(sSelf, duration: 0.0, options: [], animations: { indicator?.kf_stopAnimating() }, completion: { finished in UIView.transitionWithView(sSelf, duration: transition.duration, options: transition.animationOptions, animations: { transition.animations?(sSelf, image) }, completion: { finished in transition.completion?(finished) completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) }) }) #endif } else { indicator?.kf_stopAnimating() sSelf.image = image completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) } } }) kf_setImageTask(task) return task } /** Set an image with a URL, a placeholder image, options, progress handler and completion handler. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: Image?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithResource(Resource(downloadURL: URL), placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: progressBlock, completionHandler: completionHandler) } } extension ImageView { /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func kf_cancelDownloadTask() { kf_imageTask?.downloadTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var showIndicatorWhenLoadingKey: Void? private var imageTaskKey: Void? extension ImageView { /// Get the image URL binded to this image view. public var kf_webURL: NSURL? { return objc_getAssociatedObject(self, &lastURLKey) as? NSURL } private func kf_setWebURL(URL: NSURL) { objc_setAssociatedObject(self, &lastURLKey, URL, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Whether show an animating indicator when the image view is loading an image or not. /// Default is false. public var kf_showIndicatorWhenLoading: Bool { get { if let result = objc_getAssociatedObject(self, &showIndicatorWhenLoadingKey) as? NSNumber { return result.boolValue } else { return false } } set { if kf_showIndicatorWhenLoading == newValue { return } else { if newValue { #if os(OSX) let indicator = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) indicator.controlSize = .SmallControlSize indicator.style = .SpinningStyle #else #if os(tvOS) let indicatorStyle = UIActivityIndicatorViewStyle.White #else let indicatorStyle = UIActivityIndicatorViewStyle.Gray #endif let indicator = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle) indicator.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin, .FlexibleTopMargin] #endif indicator.kf_center = CGPoint(x: CGRectGetMidX(bounds), y: CGRectGetMidY(bounds)) indicator.hidden = true self.addSubview(indicator) kf_setIndicator(indicator) } else { kf_indicator?.removeFromSuperview() kf_setIndicator(nil) } objc_setAssociatedObject(self, &showIndicatorWhenLoadingKey, NSNumber(bool: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } /// The indicator view showing when loading. This will be `nil` if `kf_showIndicatorWhenLoading` is false. /// You may want to use this to set the indicator style or color when you set `kf_showIndicatorWhenLoading` to true. public var kf_indicator: IndicatorView? { return objc_getAssociatedObject(self, &indicatorKey) as? IndicatorView } private func kf_setIndicator(indicator: IndicatorView?) { objc_setAssociatedObject(self, &indicatorKey, indicator, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } private var kf_imageTask: RetrieveImageTask? { return objc_getAssociatedObject(self, &imageTaskKey) as? RetrieveImageTask } private func kf_setImageTask(task: RetrieveImageTask?) { objc_setAssociatedObject(self, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } extension IndicatorView { func kf_startAnimating() { #if os(OSX) startAnimation(nil) #else startAnimating() #endif hidden = false } func kf_stopAnimating() { #if os(OSX) stopAnimation(nil) #else stopAnimating() #endif hidden = true } #if os(OSX) var kf_center: CGPoint { get { return CGPoint(x: frame.origin.x + frame.size.width / 2.0, y: frame.origin.y + frame.size.height / 2.0 ) } set { let newFrame = CGRect(x: newValue.x - frame.size.width / 2.0, y: newValue.y - frame.size.height / 2.0, width: frame.size.width, height: frame.size.height) frame = newFrame } } #else var kf_center: CGPoint { get { return center } set { center = newValue } } #endif }
mit
4163b8fb736ad2f14f7436085abd6ca3
42.711584
242
0.621687
5.705029
false
false
false
false
mohshin-shah/MSTabBarController
MSTabBarController/MSTabBarController.swift
1
5413
// // MSTabBarController.swift // // // Created by Mohshin Shah on 06/11/2016. // Copyright © 2016 Mohshin Shah. All rights reserved. // import Foundation import UIKit /** You use the MSTabarControllerDelegate protocol when you want to trace the behavior of a tab bar selection while animating. */ public protocol MSTabBarControllerDelegate: NSObjectProtocol { /** This is used for informing the conforming class before performing the switching to the destination controller with animation - parameter sourceController: Currently selected view controller. - parameter destinationController: Destination view controller. */ func willSelectViewController(_ sourceController: UIViewController, destinationController: UIViewController) /** This is used for informing the conforming class after performing the switching to the destination controller with animation - parameter destinationController: Currently selected view controller. */ func didSelectedViewController(_ destinationController: UIViewController) } /** @class MSTabBarController @brief Creates pretty animation while selecting or panning the view @superclass SuperClass: UITabBarController\n */ open class MSTabBarController: UITabBarController { ///MSTabBarControllerDelegate delegate public var ms_delegate: MSTabBarControllerDelegate? //Check whether it is interactive animation var isInteractive = false ///Pan gesture direction var panDirectionRight = false /// Main Non Interactive transition instance (MSTabAnimator) var transition = MSTabAnimator() /// Pan gesture recognizer var panGestureRecognizer: UIPanGestureRecognizer? override open func viewDidLoad() { super.viewDidLoad() self.setUp() } ///Setting up configuration func setUp() { //Creating pan gesture panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector (handlePan(sender:))) panGestureRecognizer?.delegate = self delegate = self view.addGestureRecognizer(panGestureRecognizer!) } ///Handles the pan gesture func handlePan(sender: UIPanGestureRecognizer) { //Translation let translation = sender.translation(in: sender.view) //Ratio var ratio = translation.x / (sender.view?.bounds.width)! if !panDirectionRight { ratio *= -1 } //Checking the gesture state switch sender.state { case .began: var newSelectedIndex = selectedIndex newSelectedIndex += panDirectionRight ? -1 : +1 isInteractive = true self.selectedIndex = newSelectedIndex return case .changed: transition.update(ratio) return case .ended,.cancelled: transition.finish() isInteractive = false //Callback to the delegate ms_delegate?.didSelectedViewController(selectedViewController!) return default: break } } } extension MSTabBarController : UIGestureRecognizerDelegate { public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { //Velocity let velocity: CGPoint = (panGestureRecognizer?.velocity(in: gestureRecognizer.view))! // accept only horizontal gestures if (fabs(velocity.x) < fabs(velocity.y)) { return false } //Detecting the pan direction panDirectionRight = velocity.x > 0 if (panDirectionRight && selectedIndex == 0) { return false } if (!panDirectionRight && selectedIndex == (viewControllers?.count)! - 1) { return false } return true } } extension MSTabBarController : UITabBarControllerDelegate { public func tabBarController(_ tabBarController: UITabBarController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return isInteractive ? transition : nil } public func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { let fromIndex = viewControllers?.index(of: fromVC) let toIndex = viewControllers?.index(of: toVC) transition.isPresenting = (fromIndex! < toIndex!) //Delegate call back before animating ms_delegate?.willSelectViewController(fromVC, destinationController: toVC) return transition } public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { return !transition.isAnimating } public func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { //Callback to the delegate ms_delegate?.didSelectedViewController(viewController) } }
mit
b6c60a0613c577f9d2e2a2f3d9245e97
30.283237
206
0.654287
6.307692
false
false
false
false
awind/Pixel
Pixel/PixelOAuthClient.swift
1
7678
// // PixelOAuthClient.swift // Pixel // // Created by SongFei on 15/12/6. // Copyright © 2015年 SongFei. All rights reserved. // import UIKit import Alamofire class PixelOAuthClient { typealias SuccessHandler = (accessToken: OAuthAccessToken?) -> Void typealias FailureHandler = (error: NSError) -> Void struct OAuth { static let version = "1.0" static let signatureMethod = "HMAC-SHA1" } struct SwifterError { static let domain = "SwifterErrorDomain" static let appOnlyAuthenticationErrorCode = 1 } struct OAuthAccessToken { var key: String var secret: String var verifier: String? init(key: String, secret: String) { self.key = key self.secret = secret } init(queryString: String) { var attributes = queryString.paramtersFromQueryString() self.key = attributes["oauth_token"]! self.secret = attributes["oauth_token_secret"]! } } var consumerKey: String var consumerSecret: String var oauthToken: OAuthAccessToken var apiURL :NSURL var dataEncoding: NSStringEncoding init(consumerKey: String, consumerSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret self.dataEncoding = NSUTF8StringEncoding self.oauthToken = OAuthAccessToken(key: "", secret: "") self.apiURL = NSURL(string: "https://api.500px.com/v1")! } init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret self.oauthToken = OAuthAccessToken(key: accessToken, secret: accessTokenSecret) self.apiURL = NSURL(string: "https://api.500px.com/v1")! self.dataEncoding = NSUTF8StringEncoding } func postOAuthRequestTokenWithCallbackURL(callbackURL: NSURL, success: SuccessHandler, failure: FailureHandler?) { let path = "/oauth/request_token" var parameters = Dictionary<String, String>() parameters["oauth_callback"] = callbackURL.absoluteString let url = NSURL(string: "\(self.apiURL)\(path)")! self.post(url, parameters: parameters) { response in let responseString = String(response) self.oauthToken = OAuthAccessToken(queryString: responseString) // print("\(responseString) and and \(self.oauthToken)") success(accessToken: self.oauthToken) } } func postOAuthAccessTokenWithRequestToken(callbackURL: NSURL, success: SuccessHandler, failure: FailureHandler?) { if let verifier = self.oauthToken.verifier { let path = "/oauth/access_token" var parameters = Dictionary<String, String>() parameters["oauth_token"] = self.oauthToken.key parameters["oauth_verifier"] = verifier parameters["oauth_callback"] = callbackURL.absoluteString let url = NSURL(string: "\(self.apiURL)\(path)")! self.post(url, parameters: parameters) { responseString in let responseString = String(responseString) self.oauthToken = OAuthAccessToken(queryString: responseString) success(accessToken: self.oauthToken) } } else { let userInfo = [NSLocalizedFailureReasonErrorKey: "Bad OAuth response received from server"] let error = NSError(domain: SwifterError.domain, code: NSURLErrorBadServerResponse, userInfo: userInfo) failure?(error: error) } } func post(url: NSURL, parameters: Dictionary<String, String>, completion: (response: String) -> ()) { let headers = ["Authorization": self.authorizationHeaderForMethod("POST", url: url, parameters: parameters)] Alamofire.request(.POST, url, parameters: nil, encoding: .URLEncodedInURL, headers: headers) .responseString { response in if response.result.error != nil { return } let responseResult = response.result.value! as String completion(response: responseResult as String) } } func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, String>) -> String { var authorizationParameters = Dictionary<String, String>() authorizationParameters["oauth_version"] = OAuth.version authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod authorizationParameters["oauth_consumer_key"] = self.consumerKey authorizationParameters["oauth_timestamp"] = String(Int(NSDate().timeIntervalSince1970)) authorizationParameters["oauth_nonce"] = NSUUID().UUIDString if !self.oauthToken.key.isEmpty { authorizationParameters["oauth_token"] = self.oauthToken.key } for (key, value): (String, String) in parameters { if key.hasPrefix("oauth_") { authorizationParameters.updateValue(value, forKey: key) } } let finalParameters = authorizationParameters +| parameters authorizationParameters["oauth_signature"] = self.oauthSignatureForMethod(method, url: url, parameters: finalParameters, accessToken: self.oauthToken) var authorizationParameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String] authorizationParameterComponents.sortInPlace { $0 < $1 } var headerComponents = [String]() for component in authorizationParameterComponents { let subcomponent = component.componentsSeparatedByString("=") as [String] if subcomponent.count == 2 { headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"") } } // print("OAuth " + headerComponents.joinWithSeparator(", ")) return "OAuth " + headerComponents.joinWithSeparator(",") } func oauthSignatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, String>, accessToken token: OAuthAccessToken?) -> String { var tokenSecret: NSString = "" if token != nil { tokenSecret = token!.secret.urlEncodedStringWithEncoding(self.dataEncoding) } let encodedConsumerSecret = self.consumerSecret.urlEncodedStringWithEncoding(self.dataEncoding) let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)" var parameterComponents = parameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String] parameterComponents.sortInPlace { $0 < $1 } let parameterString = parameterComponents.joinWithSeparator("&") let encodedParameterString = parameterString.urlEncodedStringWithEncoding(self.dataEncoding) let encodedURL = url.absoluteString.urlEncodedStringWithEncoding(self.dataEncoding) let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)" // let signature = signatureBaseString.SHA1DigestWithKey(signingKey) return signatureBaseString.SHA1DigestWithKey(signingKey).base64EncodedStringWithOptions([]) } }
apache-2.0
9e3fd1abd110b5731583029732ca4dd2
38.561856
168
0.637264
5.680977
false
false
false
false
Karumi/KataSuperHeroesIOS
KataSuperHeroes/UIColor.swift
1
2804
import Foundation import UIKit extension UIColor { convenience init(rgba: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if rgba.hasPrefix("#") { let hex = String(rgba.dropFirst()) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexInt64(&hexValue) { switch hex.count { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string") } } else { print("Scan hex error") } } else { print("Invalid RGB string, missing '#' as prefix", terminator: "") } self.init(red:red, green:green, blue:blue, alpha:alpha) } static var windowBackgroundColor: UIColor { return UIColor(rgba: "#22282FFF") } static var loadingColor: UIColor { return UIColor(rgba: "#4D5B69FF") } static var tabBarColor: UIColor { return UIColor(rgba: "#4D5B69FF") } static var tabBarTintColor: UIColor { return UIColor(rgba: "#17D1FFFF") } static var navigationBarColor: UIColor { return UIColor(rgba: "#404B57FF") } static var navigationBarTitleColor: UIColor { return UIColor(rgba: "#F5F5F5FF") } static var gradientStartColor: UIColor { return UIColor(rgba: "#2C343C00") } static var gradientEndColor: UIColor { return UIColor(rgba: "#2C343CE5") } static var cellBackgroundColor: UIColor { return UIColor(rgba: "#22282fFF") } }
apache-2.0
f9c472688e2178fd549eadde00699051
32.380952
78
0.495007
4.141802
false
false
false
false
brentdax/swift
stdlib/public/SDK/ARKit/ARKit.swift
7
7472
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import ARKit @available(iOS, introduced: 11.0) extension ARCamera { /** A value describing the camera's tracking state. */ @_frozen public enum TrackingState { public enum Reason { /** Tracking is limited due to initialization in progress. */ case initializing /** Tracking is limited due to a excessive motion of the camera. */ case excessiveMotion /** Tracking is limited due to a lack of features visible to the camera. */ case insufficientFeatures /** Tracking is limited due to a relocalization in progress. */ @available(iOS, introduced: 11.3) case relocalizing } /** Tracking is not available. */ case notAvailable /** Tracking is limited. See tracking reason for details. */ case limited(Reason) /** Tracking is normal. */ case normal } /** The tracking state of the camera. */ public var trackingState: TrackingState { switch __trackingState { case .notAvailable: return .notAvailable case .normal: return .normal case .limited: let reason: TrackingState.Reason if #available(iOS 11.3, *) { switch __trackingStateReason { case .initializing: reason = .initializing case .relocalizing: reason = .relocalizing case .excessiveMotion: reason = .excessiveMotion default: reason = .insufficientFeatures } } else { switch __trackingStateReason { case .initializing: reason = .initializing case .excessiveMotion: reason = .excessiveMotion default: reason = .insufficientFeatures } } return .limited(reason) } } @available(iOS, introduced: 12.0) @nonobjc public func unprojectPoint( _ point: CGPoint, ontoPlane planeTransform: simd_float4x4, orientation: UIInterfaceOrientation, viewportSize: CGSize ) -> simd_float3? { let result = __unprojectPoint( point, ontoPlaneWithTransform: planeTransform, orientation: orientation, viewportSize: viewportSize) if result.x.isNaN || result.y.isNaN || result.z.isNaN { return nil } return result } } @available(iOS, introduced: 12.0) extension ARSCNView { @nonobjc public func unprojectPoint( _ point: CGPoint, ontoPlane planeTransform: simd_float4x4 ) -> simd_float3? { let result = __unprojectPoint( point, ontoPlaneWithTransform: planeTransform) if result.x.isNaN || result.y.isNaN || result.z.isNaN { return nil } return result } } @available(iOS, introduced: 11.0) extension ARPointCloud { /** The 3D points comprising the point cloud. */ @nonobjc public var points: [vector_float3] { let buffer = UnsafeBufferPointer(start: __points, count: Int(__count)) return Array(buffer) } /** The 3D point identifiers comprising the point cloud. */ @nonobjc public var identifiers: [UInt64] { let buffer = UnsafeBufferPointer(start: __identifiers, count: Int(__count)) return Array(buffer) } } @available(iOS, introduced: 11.0) extension ARFaceGeometry { /** The mesh vertices of the geometry. */ @nonobjc public var vertices: [vector_float3] { let buffer = UnsafeBufferPointer(start: __vertices, count: Int(__vertexCount)) return Array(buffer) } /** The texture coordinates of the geometry. */ @nonobjc public var textureCoordinates: [vector_float2] { let buffer = UnsafeBufferPointer(start: __textureCoordinates, count: Int(__textureCoordinateCount)) return Array(buffer) } /** The triangle indices of the geometry. */ @nonobjc public var triangleIndices: [Int16] { let buffer = UnsafeBufferPointer(start: __triangleIndices, count: Int(triangleCount * 3)) return Array(buffer) } } @available(iOS, introduced: 11.3) extension ARPlaneGeometry { /** The mesh vertices of the geometry. */ @nonobjc public var vertices: [vector_float3] { let buffer = UnsafeBufferPointer(start: __vertices, count: Int(__vertexCount)) return Array(buffer) } /** The texture coordinates of the geometry. */ @nonobjc public var textureCoordinates: [vector_float2] { let buffer = UnsafeBufferPointer(start: __textureCoordinates, count: Int(__textureCoordinateCount)) return Array(buffer) } /** The triangle indices of the geometry. */ @nonobjc public var triangleIndices: [Int16] { let buffer = UnsafeBufferPointer(start: __triangleIndices, count: Int(triangleCount * 3)) return Array(buffer) } /** The vertices of the geometry's outermost boundary. */ @nonobjc public var boundaryVertices: [vector_float3] { let buffer = UnsafeBufferPointer(start: __boundaryVertices, count: Int(__boundaryVertexCount)) return Array(buffer) } } @available(iOS, introduced: 12.0) extension ARPlaneAnchor { /** A value describing the classification of a plane anchor. */ public enum Classification { public enum Status { /** Plane classification is currently unavailable. */ case notAvailable /** ARKit has not yet determined the classification of this plane. */ case undetermined /** ARKit is confident the plane is not any of the known classes. */ case unknown } /** The classification is not any of the known classes. */ case none(Status) case wall case floor case ceiling case table case seat } /** Classification of the plane. */ public var classification: ARPlaneAnchor.Classification { switch __classification { case .wall: return .wall case .floor: return .floor case .ceiling: return .ceiling case .table: return .table case .seat: return .seat case .none: fallthrough default: switch __classificationStatus { case .notAvailable: return .none(.notAvailable) case .unknown: return .none(.unknown) case .undetermined: fallthrough case .known: fallthrough default: return .none(.undetermined) } } } }
apache-2.0
9343f2858c6f67bbfbf17159ed1cadb0
29.008032
107
0.575214
5.038436
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Extensions/ExtensionNSTextField.swift
1
4923
// // ExtensionNSTextField.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa import ProfilePayloads extension NSTextField { func highlighSubstrings(for payload: PayloadSubkey) { var highlighted = false // Highlight formatting errors IMPORTANT: Must be first of the highlights if let formatString = payload.format, self.highlightSubstringsNotMatching(format: formatString) { highlighted = true } if let substitutionVariables = payload.substitutionVariables { if self.highlightSubstringsMatching(substitutionVariables: substitutionVariables) { highlighted = true } self.updateTrackingAreas() } if !highlighted { self.allowsEditingTextAttributes = false self.textColor = .labelColor } } private func highlightSubstringsMatching(substitutionVariables: [String: [String: String]]) -> Bool { guard let font = self.font, let payloadTextField = self as? PayloadTextField else { return false } // Reset payloadTextField.substitutionVariables.removeAll() do { let regex = try NSRegularExpression(pattern: substitutionVariables.keys.joined(separator: "|"), options: []) let regexMatches = regex.matches(in: self.stringValue, options: [], range: NSRange(location: 0, length: self.stringValue.count)) if regexMatches.isEmpty { return false } let attributedString = NSMutableAttributedString(attributedString: self.attributedStringValue) // NSMutableAttributedString(string: self.stringValue, attributes: [.foregroundColor: NSColor.labelColor, .font: font]) self.textColor = nil for match in regexMatches { guard let substring = self.stringValue.substring(with: match.range) else { Log.shared.error(message: "Failed to create substring at range: \(match.range) for string: \(self.stringValue)", category: String(describing: self)) continue } let attributedSubstring = NSMutableAttributedString(string: String(substring), attributes: [.font: font]) attributedSubstring.addAttribute(.foregroundColor, value: NSColor.systemPurple, range: NSRange(location: 0, length: substring.count)) if let substitutionVariable = substitutionVariables[String(substring)] { payloadTextField.substitutionVariables[match.range] = [String(substring): substitutionVariable] } attributedString.replaceCharacters(in: match.range, with: attributedSubstring) } self.allowsEditingTextAttributes = true self.attributedStringValue = attributedString return true } catch { Log.shared.error(message: "Failed to create a regular expression from the substitutionVariables: \(substitutionVariables)", category: String(describing: self)) } return false } private func highlightSubstringsNotMatching(format: String) -> Bool { guard let font = self.font else { return false } do { let regex = try NSRegularExpression(pattern: format, options: []) let regexMatches = regex.matches(in: self.stringValue, options: [], range: NSRange(location: 0, length: self.stringValue.count)) let attributedString = NSMutableAttributedString(string: self.stringValue, attributes: [.foregroundColor: NSColor.systemRed, .font: font]) self.textColor = nil for match in regexMatches { guard let substring = self.stringValue.substring(with: match.range) else { Log.shared.error(message: "Failed to create substring at range: \(match.range) for string: \(self.stringValue)", category: String(describing: self)) continue } let attributedSubstring = NSMutableAttributedString(string: String(substring), attributes: [.font: font]) attributedSubstring.addAttribute(.foregroundColor, value: NSColor.labelColor, range: NSRange(location: 0, length: substring.count)) attributedString.replaceCharacters(in: match.range, with: attributedSubstring) } self.allowsEditingTextAttributes = true self.attributedStringValue = attributedString return true } catch { Log.shared.error(message: "Failed to create a regular expression from the string: \(format)", category: String(describing: self)) } return false } } extension String { func substring(with nsrange: NSRange) -> Substring? { guard let range = Range(nsrange, in: self) else { return nil } return self[range] } }
mit
d7090849b1d9955d7350fa80154c7fd7
45.87619
227
0.656237
5.373362
false
false
false
false
BarakRL/SBrick-iOS
Example/SBrick-iOS/ViewController.swift
1
4199
// // ViewController.swift // SBrick-iOS // // Created by Barak Harel on 04/03/2017. // Copyright (c) 2017 Barak Harel. All rights reserved. // import UIKit import SBrick import CoreBluetooth import AVFoundation class ViewController: UIViewController, SBrickManagerDelegate, SBrickDelegate { @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var sensorTypeLabel: UILabel! @IBOutlet weak var sensorValueLabel: UILabel! var manager: SBrickManager! var sbrick: SBrick? override func viewDidLoad() { super.viewDidLoad() manager = SBrickManager(delegate: self) statusLabel.text = "Discovering..." manager.startDiscovery() } func sbrickManager(_ sbrickManager: SBrickManager, didDiscover sbrick: SBrick) { //stop for now sbrickManager.stopDiscovery() statusLabel.text = "Found: \(sbrick.manufacturerData.deviceIdentifier)" //connect sbrick.delegate = self sbrickManager.connect(to: sbrick) } func sbrickManager(_ sbrickManager: SBrickManager, didUpdateBluetoothState bluetoothState: CBManagerState) { } func sbrickConnected(_ sbrick: SBrick) { statusLabel.text = "SBrick connected!" self.sbrick = sbrick } var adcTimer: Timer? func testSensor() { guard let sbrick = self.sbrick else { return } sbrick.send(command: .enableSensor(port: .port2)) adcTimer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true, block: { [weak self] (timer) in guard let sbrick = self?.sbrick else { return } sbrick.send(command: .querySensor(port: .port2)) { [weak self] (bytes) in if let sensorData = SBrickSensorData(bytes: bytes) { self?.sensorTypeLabel.text = "\(sensorData.sensorType)" self?.sensorValueLabel.text = "\(sensorData.sensorValue)" print("sensor type: \(sensorData.sensorType) value:\(sensorData.sensorValue)") } } }) } func sbrickDisconnected(_ sbrick: SBrick) { statusLabel.text = "SBrick disconnected :(" self.sbrick = nil } func sbrickReady(_ sbrick: SBrick) { statusLabel.text = "SBrick ready!" testSensor() } func sbrick(_ sbrick: SBrick, didRead data: Data?) { guard let data = data else { return } print("sbrick [\(sbrick.name)] did read: \([UInt8](data))") } @IBAction func stop(_ sender: Any) { guard let sbrick = manager.sbricks.first else { return } //sbrick.send(command: .stop(channelId: 0)) sbrick.port1.stop() } @IBAction func halfPowerCW(_ sender: Any) { guard let sbrick = manager.sbricks.first else { return } //sbrick.send(command: .drive(channelId: 0, cw: true, power: 0x80)) { bytes in // print("ok") //} sbrick.port1.drive(power: 0x80, isCW: true) } @IBAction func fullPowerCW(_ sender: Any) { guard let sbrick = manager.sbricks.first else { return } //sbrick.send(command: .drive(channelId: 0, cw: true, power: 0xFF)) { bytes in // print("ok") //} sbrick.port1.drive(power: 0xFF, isCW: true) } @IBAction func halfPowerCCW(_ sender: Any) { guard let sbrick = manager.sbricks.first else { return } //sbrick.send(command: .drive(channelId: 0, cw: false, power: 0x80)) { bytes in // print("ok") //} sbrick.port1.drive(power: 0x80, isCW: false) } @IBAction func fullPowerCCW(_ sender: Any) { guard let sbrick = manager.sbricks.first else { return } //sbrick.send(command: .drive(channelId: 0, cw: false, power: 0xFF)) { bytes in // print("ok") //} sbrick.port1.drive(power: 0xFF, isCW: false) } }
mit
e77a0dd5fd894820b0af5bf3bddeca3f
28.570423
112
0.564182
4.161546
false
false
false
false
honghaoz/2048-Solver-AI
2048 AI/Components/Settings/View/BlackSlider.swift
1
1833
// Copyright © 2019 ChouTi. All rights reserved. import ChouTiUI import UIKit class BlackSlider: UISlider { var trackHeight: CGFloat = 5.0 override func trackRect(forBounds bounds: CGRect) -> CGRect { let y = (bounds.height - trackHeight) / 2.0 return CGRect(x: 0, y: y, width: bounds.width, height: trackHeight) } // MARK: - Init Methods required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } private func commonInit() { setupViews() } private func setupViews() { setMinimumTrackImage(UIImage.imageWithColor(UIColor.black), for: .normal) setMaximumTrackImage(UIImage.imageWithColor(UIColor.black), for: .normal) let thumbImage = UIImage.imageWithBorderRectangle(size: CGSize(width: 26, height: 26), borderWidth: 10.0, borderColor: UIColor.black, fillColor: SharedColors.BackgroundColor) setThumbImage(thumbImage, for: .normal) } } extension UIImage { class func imageWithBorderRectangle(size: CGSize, borderWidth: CGFloat, borderColor: UIColor, fillColor: UIColor = UIColor.clear) -> UIImage? { UIGraphicsBeginImageContext(size) defer { UIGraphicsEndImageContext() } let context = UIGraphicsGetCurrentContext() let rect = CGRect(origin: .zero, size: size) context?.setFillColor(fillColor.cgColor) context?.fill(rect) context?.setStrokeColor(borderColor.cgColor) context?.setLineWidth(borderWidth) context?.stroke(rect) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil } return image } }
gpl-2.0
fae5a80cfe57e44a4520fcec34db89b2
27.625
145
0.648472
4.637975
false
false
false
false
zmeyc/SQLite.swift
Tests/SQLite/SchemaTests.swift
4
42374
import XCTest import SQLite class SchemaTests : XCTestCase { func test_drop_compilesDropTableExpression() { XCTAssertEqual("DROP TABLE \"table\"", table.drop()) XCTAssertEqual("DROP TABLE IF EXISTS \"table\"", table.drop(ifExists: true)) } func test_drop_compilesDropVirtualTableExpression() { XCTAssertEqual("DROP TABLE \"virtual_table\"", virtualTable.drop()) XCTAssertEqual("DROP TABLE IF EXISTS \"virtual_table\"", virtualTable.drop(ifExists: true)) } func test_drop_compilesDropViewExpression() { XCTAssertEqual("DROP VIEW \"view\"", _view.drop()) XCTAssertEqual("DROP VIEW IF EXISTS \"view\"", _view.drop(ifExists: true)) } func test_create_withBuilder_compilesCreateTableExpression() { XCTAssertEqual( "CREATE TABLE \"table\" (" + "\"blob\" BLOB NOT NULL, " + "\"blobOptional\" BLOB, " + "\"double\" REAL NOT NULL, " + "\"doubleOptional\" REAL, " + "\"int64\" INTEGER NOT NULL, " + "\"int64Optional\" INTEGER, " + "\"string\" TEXT NOT NULL, " + "\"stringOptional\" TEXT" + ")", table.create { t in t.column(data) t.column(dataOptional) t.column(double) t.column(doubleOptional) t.column(int64) t.column(int64Optional) t.column(string) t.column(stringOptional) } ) XCTAssertEqual( "CREATE TEMPORARY TABLE \"table\" (\"int64\" INTEGER NOT NULL)", table.create(temporary: true) { $0.column(int64) } ) XCTAssertEqual( "CREATE TABLE IF NOT EXISTS \"table\" (\"int64\" INTEGER NOT NULL)", table.create(ifNotExists: true) { $0.column(int64) } ) XCTAssertEqual( "CREATE TEMPORARY TABLE IF NOT EXISTS \"table\" (\"int64\" INTEGER NOT NULL)", table.create(temporary: true, ifNotExists: true) { $0.column(int64) } ) } func test_create_withQuery_compilesCreateTableExpression() { XCTAssertEqual( "CREATE TABLE \"table\" AS SELECT \"int64\" FROM \"view\"", table.create(_view.select(int64)) ) } // thoroughness test for ambiguity func test_column_compilesColumnDefinitionExpression() { XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL)", table.create { t in t.column(int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE)", table.create { t in t.column(int64, unique: true) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0))", table.create { t in t.column(int64, check: int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0))", table.create { t in t.column(int64, check: int64Optional > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL DEFAULT (\"int64\"))", table.create { t in t.column(int64, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL DEFAULT (0))", table.create { t in t.column(int64, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0))", table.create { t in t.column(int64, unique: true, check: int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0))", table.create { t in t.column(int64, unique: true, check: int64Optional > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE DEFAULT (\"int64\"))", table.create { t in t.column(int64, unique: true, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE DEFAULT (0))", table.create { t in t.column(int64, unique: true, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0))", table.create { t in t.column(int64, unique: true, check: int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0))", table.create { t in t.column(int64, unique: true, check: int64Optional > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64, unique: true, check: int64 > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64, unique: true, check: int64Optional > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) DEFAULT (0))", table.create { t in t.column(int64, unique: true, check: int64 > 0, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (0))", table.create { t in t.column(int64, unique: true, check: int64Optional > 0, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64, check: int64 > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64, check: int64Optional > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (0))", table.create { t in t.column(int64, check: int64 > 0, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (0))", table.create { t in t.column(int64, check: int64Optional > 0, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0))", table.create { t in t.column(int64, primaryKey: true, check: int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0))", table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL DEFAULT (\"int64\"))", table.create { t in t.column(int64, primaryKey: true, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0))", table.create { t in t.column(int64, primaryKey: true, check: int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0))", table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64, primaryKey: true, check: int64 > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER)", table.create { t in t.column(int64Optional) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE)", table.create { t in t.column(int64Optional, unique: true) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0))", table.create { t in t.column(int64Optional, check: int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0))", table.create { t in t.column(int64Optional, check: int64Optional > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (\"int64\"))", table.create { t in t.column(int64Optional, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (\"int64Optional\"))", table.create { t in t.column(int64Optional, defaultValue: int64Optional) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (0))", table.create { t in t.column(int64Optional, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0))", table.create { t in t.column(int64Optional, unique: true, check: int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0))", table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (\"int64\"))", table.create { t in t.column(int64Optional, unique: true, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (\"int64Optional\"))", table.create { t in t.column(int64Optional, unique: true, defaultValue: int64Optional) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (0))", table.create { t in t.column(int64Optional, unique: true, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0))", table.create { t in t.column(int64Optional, unique: true, check: int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0))", table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64Optional\"))", table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: int64Optional) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64Optional\"))", table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: int64Optional) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (0))", table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (0))", table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))", table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (\"int64Optional\"))", table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: int64Optional) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (\"int64Optional\"))", table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: int64Optional) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (0))", table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (0))", table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: 0) } ) } func test_column_withIntegerExpression_compilesPrimaryKeyAutoincrementColumnDefinitionExpression() { XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)", table.create { t in t.column(int64, primaryKey: .Autoincrement) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (\"int64\" > 0))", table.create { t in t.column(int64, primaryKey: .Autoincrement, check: int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (\"int64Optional\" > 0))", table.create { t in t.column(int64, primaryKey: .Autoincrement, check: int64Optional > 0) } ) } func test_column_withIntegerExpression_compilesReferentialColumnDefinitionExpression() { XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64, references: qualifiedTable, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64, unique: true, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64, check: int64 > 0, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64, check: int64Optional > 0, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64, unique: true, check: int64 > 0, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64, unique: true, check: int64Optional > 0, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64Optional, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64Optional, unique: true, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64Optional, check: int64 > 0, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64Optional, check: int64Optional > 0, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, references: table, int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, references: table, int64) } ) } func test_column_withStringExpression_compilesCollatedColumnDefinitionExpression() { XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL COLLATE RTRIM)", table.create { t in t.column(string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE COLLATE RTRIM)", table.create { t in t.column(string, unique: true, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') COLLATE RTRIM)", table.create { t in t.column(string, check: string != "", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') COLLATE RTRIM)", table.create { t in t.column(string, check: stringOptional != "", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(string, defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(string, defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') COLLATE RTRIM)", table.create { t in t.column(string, unique: true, check: string != "", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') COLLATE RTRIM)", table.create { t in t.column(string, unique: true, check: stringOptional != "", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(string, unique: true, defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(string, unique: true, defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(string, unique: true, check: string != "", defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(string, unique: true, check: stringOptional != "", defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(string, unique: true, check: string != "", defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(string, unique: true, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(string, check: string != "", defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(string, check: stringOptional != "", defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(string, check: string != "", defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(string, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL COLLATE RTRIM)", table.create { t in t.column(stringOptional, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') COLLATE RTRIM)", table.create { t in t.column(stringOptional, check: string != "", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') COLLATE RTRIM)", table.create { t in t.column(stringOptional, check: stringOptional != "", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT (\"stringOptional\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, defaultValue: stringOptional, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(stringOptional, defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, check: string != "", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT (\"stringOptional\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, defaultValue: stringOptional, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: stringOptional, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: stringOptional, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, check: string != "", defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: string, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, check: string != "", defaultValue: stringOptional, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)", table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: stringOptional, collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(stringOptional, check: string != "", defaultValue: "string", collate: .Rtrim) } ) XCTAssertEqual( "CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)", table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) } ) } func test_primaryKey_compilesPrimaryKeyExpression() { XCTAssertEqual( "CREATE TABLE \"table\" (PRIMARY KEY (\"int64\"))", table.create { t in t.primaryKey(int64) } ) XCTAssertEqual( "CREATE TABLE \"table\" (PRIMARY KEY (\"int64\", \"string\"))", table.create { t in t.primaryKey(int64, string) } ) XCTAssertEqual( "CREATE TABLE \"table\" (PRIMARY KEY (\"int64\", \"string\", \"double\"))", table.create { t in t.primaryKey(int64, string, double) } ) } func test_unique_compilesUniqueExpression() { XCTAssertEqual( "CREATE TABLE \"table\" (UNIQUE (\"int64\"))", table.create { t in t.unique(int64) } ) } func test_check_compilesCheckExpression() { XCTAssertEqual( "CREATE TABLE \"table\" (CHECK ((\"int64\" > 0)))", table.create { t in t.check(int64 > 0) } ) XCTAssertEqual( "CREATE TABLE \"table\" (CHECK ((\"int64Optional\" > 0)))", table.create { t in t.check(int64Optional > 0) } ) } func test_foreignKey_compilesForeignKeyExpression() { XCTAssertEqual( "CREATE TABLE \"table\" (FOREIGN KEY (\"string\") REFERENCES \"table\" (\"string\"))", table.create { t in t.foreignKey(string, references: table, string) } ) XCTAssertEqual( "CREATE TABLE \"table\" (FOREIGN KEY (\"stringOptional\") REFERENCES \"table\" (\"string\"))", table.create { t in t.foreignKey(stringOptional, references: table, string) } ) XCTAssertEqual( "CREATE TABLE \"table\" (FOREIGN KEY (\"string\") REFERENCES \"table\" (\"string\") ON UPDATE CASCADE ON DELETE SET NULL)", table.create { t in t.foreignKey(string, references: table, string, update: .Cascade, delete: .SetNull) } ) XCTAssertEqual( "CREATE TABLE \"table\" (FOREIGN KEY (\"string\", \"string\") REFERENCES \"table\" (\"string\", \"string\"))", table.create { t in t.foreignKey((string, string), references: table, (string, string)) } ) XCTAssertEqual( "CREATE TABLE \"table\" (FOREIGN KEY (\"string\", \"string\", \"string\") REFERENCES \"table\" (\"string\", \"string\", \"string\"))", table.create { t in t.foreignKey((string, string, string), references: table, (string, string, string)) } ) } func test_addColumn_compilesAlterTableExpression() { XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL DEFAULT (1)", table.addColumn(int64, defaultValue: 1) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (1)", table.addColumn(int64, check: int64 > 0, defaultValue: 1) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (1)", table.addColumn(int64, check: int64Optional > 0, defaultValue: 1) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER", table.addColumn(int64Optional) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0)", table.addColumn(int64Optional, check: int64 > 0) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0)", table.addColumn(int64Optional, check: int64Optional > 0) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER DEFAULT (1)", table.addColumn(int64Optional, defaultValue: 1) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (1)", table.addColumn(int64Optional, check: int64 > 0, defaultValue: 1) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (1)", table.addColumn(int64Optional, check: int64Optional > 0, defaultValue: 1) ) } func test_addColumn_withIntegerExpression_compilesReferentialAlterTableExpression() { XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\")", table.addColumn(int64, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE REFERENCES \"table\" (\"int64\")", table.addColumn(int64, unique: true, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")", table.addColumn(int64, check: int64 > 0, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")", table.addColumn(int64, check: int64Optional > 0, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")", table.addColumn(int64, unique: true, check: int64 > 0, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")", table.addColumn(int64, unique: true, check: int64Optional > 0, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER REFERENCES \"table\" (\"int64\")", table.addColumn(int64Optional, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE REFERENCES \"table\" (\"int64\")", table.addColumn(int64Optional, unique: true, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")", table.addColumn(int64Optional, check: int64 > 0, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")", table.addColumn(int64Optional, check: int64Optional > 0, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")", table.addColumn(int64Optional, unique: true, check: int64 > 0, references: table, int64) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")", table.addColumn(int64Optional, unique: true, check: int64Optional > 0, references: table, int64) ) } func test_addColumn_withStringExpression_compilesCollatedAlterTableExpression() { XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM", table.addColumn(string, defaultValue: "string", collate: .Rtrim) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM", table.addColumn(string, check: string != "", defaultValue: "string", collate: .Rtrim) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM", table.addColumn(string, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT COLLATE RTRIM", table.addColumn(stringOptional, collate: .Rtrim) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"string\" != '') COLLATE RTRIM", table.addColumn(stringOptional, check: string != "", collate: .Rtrim) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"stringOptional\" != '') COLLATE RTRIM", table.addColumn(stringOptional, check: stringOptional != "", collate: .Rtrim) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM", table.addColumn(stringOptional, check: string != "", defaultValue: "string", collate: .Rtrim) ) XCTAssertEqual( "ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM", table.addColumn(stringOptional, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) ) } func test_rename_compilesAlterTableRenameToExpression() { XCTAssertEqual("ALTER TABLE \"old\" RENAME TO \"table\"", Table("old").rename(table)) } func test_createIndex_compilesCreateIndexExpression() { XCTAssertEqual("CREATE INDEX \"index_table_on_int64\" ON \"table\" (\"int64\")", table.createIndex(int64)) XCTAssertEqual( "CREATE UNIQUE INDEX \"index_table_on_int64\" ON \"table\" (\"int64\")", table.createIndex([int64], unique: true) ) XCTAssertEqual( "CREATE INDEX IF NOT EXISTS \"index_table_on_int64\" ON \"table\" (\"int64\")", table.createIndex([int64], ifNotExists: true) ) XCTAssertEqual( "CREATE UNIQUE INDEX IF NOT EXISTS \"index_table_on_int64\" ON \"table\" (\"int64\")", table.createIndex([int64], unique: true, ifNotExists: true) ) XCTAssertEqual( "CREATE UNIQUE INDEX IF NOT EXISTS \"main\".\"index_table_on_int64\" ON \"table\" (\"int64\")", qualifiedTable.createIndex([int64], unique: true, ifNotExists: true) ) } func test_dropIndex_compilesCreateIndexExpression() { XCTAssertEqual("DROP INDEX \"index_table_on_int64\"", table.dropIndex(int64)) XCTAssertEqual("DROP INDEX IF EXISTS \"index_table_on_int64\"", table.dropIndex([int64], ifExists: true)) } func test_create_onView_compilesCreateViewExpression() { XCTAssertEqual( "CREATE VIEW \"view\" AS SELECT \"int64\" FROM \"table\"", _view.create(table.select(int64)) ) XCTAssertEqual( "CREATE TEMPORARY VIEW \"view\" AS SELECT \"int64\" FROM \"table\"", _view.create(table.select(int64), temporary: true) ) XCTAssertEqual( "CREATE VIEW IF NOT EXISTS \"view\" AS SELECT \"int64\" FROM \"table\"", _view.create(table.select(int64), ifNotExists: true) ) XCTAssertEqual( "CREATE TEMPORARY VIEW IF NOT EXISTS \"view\" AS SELECT \"int64\" FROM \"table\"", _view.create(table.select(int64), temporary: true, ifNotExists: true) ) } func test_create_onVirtualTable_compilesCreateVirtualTableExpression() { XCTAssertEqual( "CREATE VIRTUAL TABLE \"virtual_table\" USING \"custom\"('foo', 'bar')", virtualTable.create(Module("custom", ["foo", "bar"])) ) } func test_rename_onVirtualTable_compilesAlterTableRenameToExpression() { XCTAssertEqual( "ALTER TABLE \"old\" RENAME TO \"virtual_table\"", VirtualTable("old").rename(virtualTable) ) } }
mit
b679796a9fffc6f313fc3a1cb92de757
53.676129
155
0.582598
4.344269
false
false
false
false
arieeel1110/Strawberry
ParseStarterProject/TextViewController.swift
2
1967
// // TextViewController.swift // ParseStarterProject-Swift // // Created by Ariel on 9/11/15. // Copyright (c) 2015 Parse. All rights reserved. // import UIKit class TextViewController: UIViewController { @IBOutlet weak var text: UITextView! @IBOutlet weak var author: UILabel! @IBOutlet weak var picture: UIImageView! @IBOutlet weak var textTitle: UITextView! var passedText:String! var passedAuthor:String! var passedPic:UIImage! var passedTitle:String! override func viewDidLoad() { super.viewDidLoad() text.layer.cornerRadius = 20; textTitle.text = passedTitle text.text = passedText picture.image = maskRoundedImage(passedPic) author.text = passedAuthor // Do any additional setup after loading the view. } func maskRoundedImage(image: UIImage) -> UIImage { let imageView = UIImageView(image: image) var layer: CALayer = CALayer() layer = imageView.layer layer.masksToBounds = true layer.cornerRadius = CGFloat(27) UIGraphicsBeginImageContext(imageView.bounds.size) layer.renderInContext(UIGraphicsGetCurrentContext()) var roundedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return roundedImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
efe58ff15ebb31a0bdb80819636eae71
25.581081
106
0.648704
5.330623
false
false
false
false
zisko/swift
test/SILGen/generic_tuples.swift
1
1633
// RUN: %target-swift-frontend -emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s func dup<T>(_ x: T) -> (T, T) { return (x,x) } // CHECK-LABEL: sil hidden @$S14generic_tuples3dup{{[_0-9a-zA-Z]*}}F // CHECK: ([[RESULT_0:%.*]] : @trivial $*T, [[RESULT_1:%.*]] : @trivial $*T, [[XVAR:%.*]] : @trivial $*T): // CHECK-NEXT: debug_value_addr [[XVAR]] : $*T, let, name "x" // CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_0]] // CHECK-NEXT: copy_addr [[XVAR]] to [initialization] [[RESULT_1]] // CHECK-NEXT: destroy_addr [[XVAR]] // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] // <rdar://problem/13822463> // Specializing a generic function on a tuple type changes the number of // SIL parameters, which caused a failure in the ownership conventions code. struct Blub {} // CHECK-LABEL: sil hidden @$S14generic_tuples3foo{{[_0-9a-zA-Z]*}}F func foo<T>(_ x: T) {} // CHECK-LABEL: sil hidden @$S14generic_tuples3bar{{[_0-9a-zA-Z]*}}F func bar(_ x: (Blub, Blub)) { foo(x) } // rdar://26279628 // A type parameter constrained to be a concrete type must be handled // as that concrete type throughout SILGen. That's especially true // if it's constrained to be a tuple. protocol HasAssoc { associatedtype A } extension HasAssoc where A == (Int, Int) { func returnTupleAlias() -> A { return (0, 0) } } // CHECK-LABEL: sil hidden @$S14generic_tuples8HasAssocPAASi_Sit1ARtzrlE16returnTupleAliasSi_SityF : $@convention(method) <Self where Self : HasAssoc, Self.A == (Int, Int)> (@in_guaranteed Self) -> (Int, Int) { // CHECK: return {{.*}} : $(Int, Int)
apache-2.0
05828b1df78942e4d2900fadc98f34bc
40.871795
210
0.640539
3.06379
false
false
false
false
alexito4/slox
Sources/LoxCore/Lox.swift
1
3601
// // Lox.swift // slox // // Created by Alejandro Martinez on 29/01/2017. // Copyright © 2017 Alejandro Martinez. All rights reserved. // import Foundation public final class Lox { public final class Logger { public var output: (String) -> Void public var error: (String) -> Void init() { output = { Swift.print($0) } error = { var stderr = FileHandle.standardError Swift.print($0, to: &stderr) } } func print(_ text: String) { output(text) } func report(_ text: String) { error(text) } } public static var logger = Logger() static let interpreter = Interpreter() public static func runFile(path: String) throws { let url = URL(fileURLWithPath: path) let code = try String(contentsOf: url) run(code) if hadError { exit(65) } if hadRuntimeError { exit(70) } } public static func runPrompt() { while true { print("> ") guard let code = readLine() else { continue } run(code) hadError = false } } public static func runCode(_ code: String) { defer { // Clean up static state in case it gets run multiple times hadError = false } run(code) } private static func run(_ code: String) { let scanner = Scanner(source: code) let tokens = scanner.scanTokens() let parser = Parser(tokens: tokens) let statements = parser.parse() // Stop if there was a syntax error. guard !hadError else { return } let resolver = Resolver(interpreter: interpreter) resolver.resolve(statements: statements) // Stop if there was a resolution error. guard !hadError else { return } interpreter.interpret(statements) /* if !hadError { precondition(expr != nil, "Parser didn't return an Expression but there was no error reported") print(AstPrinter().print(expr: expr!)) }*/ } // MARK: - Error Reporting // MARK: Compile time error static func error(line: Int, message: String) { report(line: line, where: "", message: message) } static func error(token: Token, message: String) { if token.type == .eof { report(line: token.line, where: " at end", message: message) } else { report(line: token.line, where: " at '\(token.lexeme)'", message: message) } } static var hadError = false static func report(line: Int, where location: String, message: String) { Lox.logger.report("[line \(line)] Error\(location): \(message)") hadError = true } // MARK: Runtime errors static var hadRuntimeError = false static func runtimeError(error: Error) { guard let interError = error as? InterpreterError else { fatalError() } guard case let InterpreterError.runtime(token, message) = interError else { fatalError() } var stderr = FileHandle.standardError print("\(message)\n[line \(token.line)]", to: &stderr) hadRuntimeError = true } } extension FileHandle: TextOutputStream { public func write(_ string: String) { guard let data = string.data(using: .utf8) else { return } write(data) } }
mit
16d7f56bc4021dcb12f99895805458c8
24
104
0.548333
4.545455
false
false
false
false
LinShiwei/WeatherDemo
Carthage/Checkouts/Alamofire/Tests/DownloadTests.swift
1
16565
// // DownloadTests.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import Foundation import XCTest class DownloadInitializationTestCase: BaseTestCase { let searchPathDirectory: FileManager.SearchPathDirectory = .cachesDirectory let searchPathDomain: FileManager.SearchPathDomainMask = .userDomainMask func testDownloadClassMethodWithMethodURLAndDestination() { // Given let urlString = "https://httpbin.org/" // When let request = Alamofire.download(urlString) // Then XCTAssertNotNil(request.request) XCTAssertEqual(request.request?.httpMethod, "GET") XCTAssertEqual(request.request?.url?.absoluteString, urlString) XCTAssertNil(request.response) } func testDownloadClassMethodWithMethodURLHeadersAndDestination() { // Given let urlString = "https://httpbin.org/" let headers = ["Authorization": "123456"] // When let request = Alamofire.download(urlString, headers: headers) // Then XCTAssertNotNil(request.request) XCTAssertEqual(request.request?.httpMethod, "GET") XCTAssertEqual(request.request?.url?.absoluteString, urlString) XCTAssertEqual(request.request?.value(forHTTPHeaderField: "Authorization"), "123456") XCTAssertNil(request.response) } } // MARK: - class DownloadResponseTestCase: BaseTestCase { private var randomCachesFileURL: URL { return FileManager.cachesDirectoryURL.appendingPathComponent("\(UUID().uuidString).json") } func testDownloadRequest() { // Given let fileURL = randomCachesFileURL let numberOfLines = 100 let urlString = "https://httpbin.org/stream/\(numberOfLines)" let destination: DownloadRequest.DownloadFileDestination = { _, _ in (fileURL, []) } let expectation = self.expectation(description: "Download request should download data to file: \(urlString)") var response: DefaultDownloadResponse? // When Alamofire.download(urlString, to: destination) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.destinationURL) XCTAssertNil(response?.resumeData) XCTAssertNil(response?.error) if let destinationURL = response?.destinationURL { XCTAssertTrue(FileManager.default.fileExists(atPath: destinationURL.path)) if let data = try? Data(contentsOf: destinationURL) { XCTAssertGreaterThan(data.count, 0) } else { XCTFail("data should exist for contents of destinationURL") } } } func testDownloadRequestWithProgress() { // Given let randomBytes = 4 * 1024 * 1024 let urlString = "https://httpbin.org/bytes/\(randomBytes)" let expectation = self.expectation(description: "Bytes download progress should be reported: \(urlString)") var progressValues: [Double] = [] var response: DefaultDownloadResponse? // When Alamofire.download(urlString) .downloadProgress { progress in progressValues.append(progress.fractionCompleted) } .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.temporaryURL) XCTAssertNil(response?.destinationURL) XCTAssertNil(response?.resumeData) XCTAssertNil(response?.error) var previousProgress: Double = progressValues.first ?? 0.0 for progress in progressValues { XCTAssertGreaterThanOrEqual(progress, previousProgress) previousProgress = progress } if let lastProgressValue = progressValues.last { XCTAssertEqual(lastProgressValue, 1.0) } else { XCTFail("last item in progressValues should not be nil") } } func testDownloadRequestWithParameters() { // Given let urlString = "https://httpbin.org/get" let parameters = ["foo": "bar"] let expectation = self.expectation(description: "Download request should download data to file") var response: DefaultDownloadResponse? // When Alamofire.download(urlString, parameters: parameters) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.temporaryURL) XCTAssertNil(response?.destinationURL) XCTAssertNil(response?.resumeData) XCTAssertNil(response?.error) if let temporaryURL = response?.temporaryURL, let data = try? Data(contentsOf: temporaryURL), let jsonObject = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)), let json = jsonObject as? [String: Any], let args = json["args"] as? [String: String] { XCTAssertEqual(args["foo"], "bar") } else { XCTFail("args parameter in JSON should not be nil") } } func testDownloadRequestWithHeaders() { // Given let fileURL = randomCachesFileURL let urlString = "https://httpbin.org/get" let headers = ["Authorization": "123456"] let destination: DownloadRequest.DownloadFileDestination = { _, _ in (fileURL, []) } let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)") var response: DefaultDownloadResponse? // When Alamofire.download(urlString, headers: headers, to: destination) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.destinationURL) XCTAssertNil(response?.resumeData) XCTAssertNil(response?.error) if let data = try? Data(contentsOf: fileURL), let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []), let json = jsonObject as? [String: Any], let headers = json["headers"] as? [String: String] { XCTAssertEqual(headers["Authorization"], "123456") } else { XCTFail("headers parameter in JSON should not be nil") } } func testThatDownloadingFileAndMovingToDirectoryThatDoesNotExistThrowsError() { // Given let fileURL = FileManager.cachesDirectoryURL.appendingPathComponent("some/random/folder/test_output.json") let expectation = self.expectation(description: "Download request should download data but fail to move file") var response: DefaultDownloadResponse? // When Alamofire.download("https://httpbin.org/get", to: { _, _ in (fileURL, [])}) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.temporaryURL) XCTAssertNotNil(response?.destinationURL) XCTAssertNil(response?.resumeData) XCTAssertNotNil(response?.error) if let error = response?.error as? CocoaError { XCTAssertEqual(error.code, .fileNoSuchFile) } else { XCTFail("error should not be nil") } } func testThatDownloadOptionsCanCreateIntermediateDirectoriesPriorToMovingFile() { // Given let fileURL = FileManager.cachesDirectoryURL.appendingPathComponent("some/random/folder/test_output.json") let expectation = self.expectation(description: "Download request should download data to file: \(fileURL)") var response: DefaultDownloadResponse? // When Alamofire.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.createIntermediateDirectories])}) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.temporaryURL) XCTAssertNotNil(response?.destinationURL) XCTAssertNil(response?.resumeData) XCTAssertNil(response?.error) } func testThatDownloadingFileAndMovingToDestinationThatIsOccupiedThrowsError() { do { // Given let directoryURL = FileManager.cachesDirectoryURL.appendingPathComponent("some/random/folder") try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) let fileURL = directoryURL.appendingPathComponent("test_output.json") try "random_data".write(to: fileURL, atomically: true, encoding: .utf8) let expectation = self.expectation(description: "Download should complete but fail to move file") var response: DefaultDownloadResponse? // When Alamofire.download("https://httpbin.org/get", to: { _, _ in (fileURL, [])}) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.temporaryURL) XCTAssertNotNil(response?.destinationURL) XCTAssertNil(response?.resumeData) XCTAssertNotNil(response?.error) if let error = response?.error as? CocoaError { XCTAssertEqual(error.code, .fileWriteFileExists) } else { XCTFail("error should not be nil") } } catch { XCTFail("Test encountered unexpected error: \(error)") } } func testThatDownloadOptionsCanRemovePreviousFilePriorToMovingFile() { do { // Given let directoryURL = FileManager.cachesDirectoryURL.appendingPathComponent("some/random/folder") try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) let fileURL = directoryURL.appendingPathComponent("test_output.json") let expectation = self.expectation(description: "Download should complete and move file to URL: \(fileURL)") var response: DefaultDownloadResponse? // When Alamofire.download("https://httpbin.org/get", to: { _, _ in (fileURL, [.removePreviousFile])}) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.temporaryURL) XCTAssertNotNil(response?.destinationURL) XCTAssertNil(response?.resumeData) XCTAssertNil(response?.error) } catch { XCTFail("Test encountered unexpected error: \(error)") } } } // MARK: - class DownloadResumeDataTestCase: BaseTestCase { let urlString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg" func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() { // Given let expectation = self.expectation(description: "Download should be cancelled") var response: DefaultDownloadResponse? // When let download = Alamofire.download(urlString) .response { resp in response = resp expectation.fulfill() } download.cancel() waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNil(response?.destinationURL) XCTAssertNil(response?.resumeData) XCTAssertNotNil(response?.error) XCTAssertNil(download.resumeData) } func testThatCancelledDownloadResponseDataMatchesResumeData() { // Given let expectation = self.expectation(description: "Download should be cancelled") var cancelled = false var response: DefaultDownloadResponse? // When let download = Alamofire.download(urlString) download.downloadProgress { progress in guard !cancelled else { return } if progress.fractionCompleted > 0.1 { download.cancel() cancelled = true } } download.response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNil(response?.destinationURL) XCTAssertNotNil(response?.error) XCTAssertNotNil(response?.resumeData) XCTAssertNotNil(download.resumeData) XCTAssertEqual(response?.resumeData, download.resumeData) } func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() { // Given let expectation = self.expectation(description: "Download should be cancelled") var cancelled = false var response: DownloadResponse<Any>? // When let download = Alamofire.download(urlString) download.downloadProgress { progress in guard !cancelled else { return } if progress.fractionCompleted > 0.1 { download.cancel() cancelled = true } } download.responseJSON { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNil(response?.destinationURL) XCTAssertEqual(response?.result.isFailure, true) XCTAssertNotNil(response?.result.error) XCTAssertNotNil(response?.resumeData) XCTAssertNotNil(download.resumeData) XCTAssertEqual(response?.resumeData, download.resumeData) } }
mit
c82c1087cef6485556bef0d0d8995e69
35.089325
131
0.638394
5.564327
false
true
false
false
antonio081014/LeeCode-CodeBase
Swift/find-median-from-data-stream.swift
2
986
/** * https://leetcode.com/problems/find-median-from-data-stream/ * * */ // Date: Sun Jul 11 08:41:21 PDT 2021 class MedianFinder { var list: [Int] /** initialize your data structure here. */ init() { list = [] } func addNum(_ num: Int) { var left = 0 var right = list.count while left < right { let mid = left + (right - left) / 2 if list[mid] < num { left = mid + 1 } else { right = mid } } list.insert(num, at: left) } func findMedian() -> Double { let n = self.list.count if n % 2 == 0 { return (Double(self.list[n / 2]) + Double(self.list[n / 2 - 1])) / 2 } return Double(self.list[n / 2]) } } /** * Your MedianFinder object will be instantiated and called as such: * let obj = MedianFinder() * obj.addNum(num) * let ret_2: Double = obj.findMedian() */
mit
d42a820113d3303570c7682f78612ff4
21.431818
80
0.486815
3.572464
false
false
false
false
Ge3kXm/MXWB
MXWB/Classes/Home/PicBrowser/MXPicBrowserPC.swift
1
3652
// // MXBrowserPC.swift // MXWB // // Created by maRk on 2017/5/17. // Copyright © 2017年 maRk. All rights reserved. // import UIKit protocol MXPicBrowserDelegate: NSObjectProtocol { // 被点击图片原大小的图片 func browserPresentionShowImageView(presentationController: MXPicBrowserPC, indexPath: IndexPath) -> UIImageView // 被点击图片相对于window的frame func browserPresentionFromFrame(presentationController: MXPicBrowserPC, indexPath: IndexPath) -> CGRect // 被点击图片放大后的frame func browserPresentionToFrame(presentationController: MXPicBrowserPC, indexPath: IndexPath) -> CGRect } class MXPicBrowserPC: UIPresentationController { // 记录当前是否显示 var isPresented = false // 代理 weak var browserDelegate: MXPicBrowserDelegate? // 当前点击的indexPath var indexPath: IndexPath? func setDelegateAndIndexPath(browserDelegate: MXPicBrowserDelegate, indexPath: IndexPath) { self.browserDelegate = browserDelegate self.indexPath = indexPath } } extension MXPicBrowserPC: UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { return MXPicBrowserPC(presentedViewController: presented, presenting: presenting) } func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = true return self } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = false return self } } extension MXPicBrowserPC: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if isPresented { willPresentController(transitionContext: transitionContext) }else { willDismissController(transitionContext: transitionContext) } } // 显示动画 private func willPresentController(transitionContext: UIViewControllerContextTransitioning) { guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else { return } let iv = browserDelegate!.browserPresentionShowImageView(presentationController: self, indexPath: indexPath!) let fromeFrame = browserDelegate!.browserPresentionFromFrame(presentationController: self, indexPath: indexPath!) iv.frame = fromeFrame let toFrame = browserDelegate!.browserPresentionToFrame(presentationController: self, indexPath: indexPath!) let containerView = transitionContext.containerView containerView.addSubview(iv) UIView.animate(withDuration: 2, animations: { iv.frame = toFrame }) { (_) in iv.removeFromSuperview() containerView.addSubview(toView) transitionContext.completeTransition(true) } } // 消失动画 private func willDismissController(transitionContext: UIViewControllerContextTransitioning) { // guard let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) else { // return // } } }
apache-2.0
fda6dda3f43adcbf8b3cf81dd0b47912
34.09901
170
0.710578
5.626984
false
false
false
false
benlangmuir/swift
test/Runtime/superclass_constraint_metadata_resilient_superclass.swift
22
1210
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-library -enable-library-evolution -module-name Framework -module-link-name Framework %S/Inputs/public_struct_with_generic_arg_swift_class_constrained.swift -o %t/%target-library-name(Framework) -emit-module-path %t/Framework.swiftmodule // RUN: %target-codesign %t/libFramework.dylib // RUN: %target-build-swift %s %S/Inputs/print_subclass/main.swift -module-name main -o %t/main -I %t -L %t // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %S/Inputs/print_subclass/main.swift // REQUIRES: executable_test // REQUIRES: OS=macosx // UNSUPPORTED: use_os_stdlib import Swift import Framework // Swift subclass of a Swift class // subclass isSwiftClassMetadataSubclass metadata completeness : Complete // superclass metadata path: loop // iteration 1: subclass->Superclass == Superclass // subclass <= Superclass // superclass == Superclass; done typealias Gen = Framework.Gen<Subclass> public class Subclass : Superclass { override init() { self.gen = Gen() super.init() } var gen: Gen? } @inline(never) public func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } }
apache-2.0
4e082764d69bc923c5401b206bee3a18
30.025641
270
0.708264
3.467049
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Home/HomepageViewController.swift
1
33709
// 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 Shared import UIKit import Storage import SyncTelemetry import MozillaAppServices class HomepageViewController: UIViewController, HomePanel, FeatureFlaggable, Themeable { // MARK: - Typealiases private typealias a11y = AccessibilityIdentifiers.FirefoxHomepage // MARK: - Operational Variables weak var homePanelDelegate: HomePanelDelegate? weak var libraryPanelDelegate: LibraryPanelDelegate? weak var browserBarViewDelegate: BrowserBarViewDelegate? { didSet { viewModel.jumpBackInViewModel.browserBarViewDelegate = browserBarViewDelegate } } private var viewModel: HomepageViewModel private var contextMenuHelper: HomepageContextMenuHelper private var tabManager: TabManagerProtocol private var urlBar: URLBarViewProtocol private var userDefaults: UserDefaultsInterface private lazy var wallpaperView: WallpaperBackgroundView = .build { _ in } private var jumpBackInContextualHintViewController: ContextualHintViewController private var syncTabContextualHintViewController: ContextualHintViewController private var collectionView: UICollectionView! = nil var themeManager: ThemeManager var notificationCenter: NotificationProtocol var themeObserver: NSObjectProtocol? // Background for status bar private lazy var statusBarView: UIView = { let statusBarFrame = statusBarFrame ?? CGRect.zero let statusBarView = UIView(frame: statusBarFrame) view.addSubview(statusBarView) return statusBarView }() // Content stack views contains collection view. lazy var contentStackView: UIStackView = .build { stackView in stackView.backgroundColor = .clear stackView.axis = .vertical } var currentTab: Tab? { return tabManager.selectedTab } // MARK: - Initializers init(profile: Profile, tabManager: TabManagerProtocol, urlBar: URLBarViewProtocol, userDefaults: UserDefaultsInterface = UserDefaults.standard, themeManager: ThemeManager = AppContainer.shared.resolve(), notificationCenter: NotificationProtocol = NotificationCenter.default ) { self.urlBar = urlBar self.tabManager = tabManager self.userDefaults = userDefaults let isPrivate = tabManager.selectedTab?.isPrivate ?? true self.viewModel = HomepageViewModel(profile: profile, isPrivate: isPrivate, tabManager: tabManager, urlBar: urlBar, theme: themeManager.currentTheme) let jumpBackInContextualViewModel = ContextualHintViewModel(forHintType: .jumpBackIn, with: viewModel.profile) self.jumpBackInContextualHintViewController = ContextualHintViewController(with: jumpBackInContextualViewModel) let syncTabContextualViewModel = ContextualHintViewModel(forHintType: .jumpBackInSyncedTab, with: viewModel.profile) self.syncTabContextualHintViewController = ContextualHintViewController(with: syncTabContextualViewModel) self.contextMenuHelper = HomepageContextMenuHelper(viewModel: viewModel) self.themeManager = themeManager self.notificationCenter = notificationCenter super.init(nibName: nil, bundle: nil) contextMenuHelper.delegate = self contextMenuHelper.getPopoverSourceRect = { [weak self] popoverView in guard let self = self else { return CGRect() } return self.getPopoverSourceRect(sourceView: popoverView) } setupNotifications(forObserver: self, observing: [.HomePanelPrefsChanged, .TabsPrivacyModeChanged, .WallpaperDidChange]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { jumpBackInContextualHintViewController.stopTimer() syncTabContextualHintViewController.stopTimer() notificationCenter.removeObserver(self) } // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() configureWallpaperView() configureContentStackView() configureCollectionView() // Delay setting up the view model delegate to ensure the views have been configured first viewModel.delegate = self let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) setupSectionsAction() reloadView() listenForThemeChange() applyTheme() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) jumpBackInContextualHintViewController.stopTimer() syncTabContextualHintViewController.stopTimer() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) wallpaperView.updateImageForOrientationChange() if UIDevice.current.userInterfaceIdiom == .pad { reloadOnRotation() } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) applyTheme() if previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass || previousTraitCollection?.verticalSizeClass != traitCollection.verticalSizeClass { reloadOnRotation() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // make sure the keyboard is dismissed when wallpaper onboarding is shown // or is StartAtHome case // Can be removed once underlying problem is solved (FXIOS-4904) if let presentedViewController = presentedViewController, presentedViewController.isKind(of: BottomSheetViewController.self) || tabManager.isStartingAtHome { self.dismissKeyboard() } } // MARK: - Layout func configureCollectionView() { collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout()) HomepageSectionType.cellTypes.forEach { collectionView.register($0, forCellWithReuseIdentifier: $0.cellIdentifier) } collectionView.register(LabelButtonHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: LabelButtonHeaderView.cellIdentifier) collectionView.keyboardDismissMode = .onDrag collectionView.addGestureRecognizer(longPressRecognizer) collectionView.delegate = self collectionView.dataSource = self collectionView.showsVerticalScrollIndicator = false collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.backgroundColor = .clear collectionView.accessibilityIdentifier = a11y.collectionView contentStackView.addArrangedSubview(collectionView) } func configureContentStackView() { view.addSubview(contentStackView) NSLayoutConstraint.activate([ contentStackView.topAnchor.constraint(equalTo: view.topAnchor), contentStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor), contentStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor), contentStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) } func configureWallpaperView() { view.addSubview(wallpaperView) NSLayoutConstraint.activate([ wallpaperView.topAnchor.constraint(equalTo: view.topAnchor), wallpaperView.leadingAnchor.constraint(equalTo: view.leadingAnchor), wallpaperView.bottomAnchor.constraint(equalTo: view.bottomAnchor), wallpaperView.trailingAnchor.constraint(equalTo: view.trailingAnchor) ]) view.sendSubviewToBack(wallpaperView) } func createLayout() -> UICollectionViewLayout { let layout = UICollectionViewCompositionalLayout { [weak self] (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in guard let self = self, let viewModel = self.viewModel.getSectionViewModel(shownSection: sectionIndex), viewModel.shouldShow else { return nil } return viewModel.section(for: layoutEnvironment.traitCollection) } return layout } // MARK: Long press private lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(longPress)) }() @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == .began else { return } let point = longPressGestureRecognizer.location(in: collectionView) guard let indexPath = collectionView.indexPathForItem(at: point), let viewModel = viewModel.getSectionViewModel(shownSection: indexPath.section) as? HomepageSectionHandler else { return } viewModel.handleLongPress(with: collectionView, indexPath: indexPath) } // MARK: - Homepage view cycle /// Normal viewcontroller view cycles cannot be relied on the homepage since the current way of showing and hiding the homepage is through alpha. /// This is a problem that need to be fixed but until then we have to rely on the methods here. func homepageWillAppear(isZeroSearch: Bool) { viewModel.isZeroSearch = isZeroSearch viewModel.recordViewAppeared() } func homepageDidAppear() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in self?.displayWallpaperSelector() if self?.tabManager.isStartingAtHome ?? false { self?.dismissKeyboard() self?.tabManager.isStartingAtHome = false } } } func homepageWillDisappear() { jumpBackInContextualHintViewController.stopTimer() syncTabContextualHintViewController.stopTimer() viewModel.recordViewDisappeared() } // MARK: - Helpers /// On iPhone, we call reloadOnRotation when the trait collection has changed, to ensure calculation /// is done with the new trait. On iPad, trait collection doesn't change from portrait to landscape (and vice-versa) /// since it's `.regular` on both. We reloadOnRotation from viewWillTransition in that case. private func reloadOnRotation() { if presentedViewController as? PhotonActionSheet != nil { presentedViewController?.dismiss(animated: false, completion: nil) } // Force the entire collectionview to re-layout viewModel.refreshData(for: traitCollection) collectionView.reloadData() collectionView.collectionViewLayout.invalidateLayout() // This pushes a reload to the end of the main queue after all the work associated with // rotating has been completed. This is important because some of the cells layout are // based on the screen state DispatchQueue.main.async { self.collectionView.reloadData() } } private func adjustPrivacySensitiveSections(notification: Notification) { guard let dict = notification.object as? NSDictionary, let isPrivate = dict[Tab.privateModeKey] as? Bool else { return } viewModel.isPrivate = isPrivate reloadView() } func applyTheme() { let theme = themeManager.currentTheme viewModel.theme = theme view.backgroundColor = theme.colors.layer1 updateStatusBar(theme: theme) } func scrollToTop(animated: Bool = false) { collectionView?.setContentOffset(.zero, animated: animated) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { dismissKeyboard() } @objc private func dismissKeyboard() { if currentTab?.lastKnownUrl?.absoluteString.hasPrefix("internal://") ?? false { urlBar.leaveOverlayMode() } } func updatePocketCellsWithVisibleRatio(cells: [UICollectionViewCell], relativeRect: CGRect) { guard let window = UIWindow.keyWindow else { return } for cell in cells { // For every story cell get it's frame relative to the window let targetRect = cell.superview.map { window.convert(cell.frame, from: $0) } ?? .zero // TODO: If visibility ratio is over 50% sponsored content can be marked as seen by the user _ = targetRect.visibilityRatio(relativeTo: relativeRect) } } func scrollViewDidScroll(_ scrollView: UIScrollView) { // Find visible pocket cells that holds pocket stories let cells = self.collectionView.visibleCells.filter { $0.reuseIdentifier == PocketStandardCell.cellIdentifier } // Relative frame is the collectionView frame plus the status bar height let relativeRect = CGRect( x: collectionView.frame.minX, y: collectionView.frame.minY, width: collectionView.frame.width, height: collectionView.frame.height + UIWindow.statusBarHeight ) updatePocketCellsWithVisibleRatio(cells: cells, relativeRect: relativeRect) updateStatusBar(theme: themeManager.currentTheme) } private func showSiteWithURLHandler(_ url: URL, isGoogleTopSite: Bool = false) { let visitType = VisitType.bookmark homePanelDelegate?.homePanel(didSelectURL: url, visitType: visitType, isGoogleTopSite: isGoogleTopSite) } func displayWallpaperSelector() { let wallpaperManager = WallpaperManager(userDefaults: userDefaults) guard wallpaperManager.canOnboardingBeShown(using: viewModel.profile), canModalBePresented else { return } self.dismissKeyboard() let viewModel = WallpaperSelectorViewModel(wallpaperManager: wallpaperManager, openSettingsAction: { self.homePanelDidRequestToOpenSettings(at: .wallpaper) }) let viewController = WallpaperSelectorViewController(viewModel: viewModel) var bottomSheetViewModel = BottomSheetViewModel() bottomSheetViewModel.shouldDismissForTapOutside = false let bottomSheetVC = BottomSheetViewController( viewModel: bottomSheetViewModel, childViewController: viewController ) self.present(bottomSheetVC, animated: false, completion: nil) userDefaults.set(true, forKey: PrefsKeys.Wallpapers.OnboardingSeenKey) } // Check if we already present something on top of the homepage, // if the homepage is actually being shown to the user and if the page is shown from a loaded webpage (zero search). private var canModalBePresented: Bool { return presentedViewController == nil && view.alpha == 1 && !viewModel.isZeroSearch } // MARK: - Contextual hint private func prepareJumpBackInContextualHint(onView headerView: LabelButtonHeaderView) { guard jumpBackInContextualHintViewController.shouldPresentHint(), !viewModel.shouldDisplayHomeTabBanner else { return } jumpBackInContextualHintViewController.configure( anchor: headerView.titleLabel, withArrowDirection: .down, andDelegate: self, presentedUsing: { self.presentContextualHint(contextualHintViewController: self.jumpBackInContextualHintViewController) }, withActionBeforeAppearing: { self.contextualHintPresented(type: .jumpBackIn) }, andActionForButton: { self.openTabsSettings() }) } private func prepareSyncedTabContextualHint(onCell cell: SyncedTabCell) { guard syncTabContextualHintViewController.shouldPresentHint(), featureFlags.isFeatureEnabled(.contextualHintForJumpBackInSyncedTab, checking: .buildOnly) else { syncTabContextualHintViewController.unconfigure() return } syncTabContextualHintViewController.configure( anchor: cell.getContextualHintAnchor(), withArrowDirection: .down, andDelegate: self, presentedUsing: { self.presentContextualHint(contextualHintViewController: self.syncTabContextualHintViewController) }, withActionBeforeAppearing: { self.contextualHintPresented(type: .jumpBackInSyncedTab) }) } @objc private func presentContextualHint(contextualHintViewController: ContextualHintViewController) { guard BrowserViewController.foregroundBVC().searchController == nil, canModalBePresented else { contextualHintViewController.stopTimer() return } present(contextualHintViewController, animated: true, completion: nil) UIAccessibility.post(notification: .layoutChanged, argument: contextualHintViewController) } } // MARK: - CollectionView Data Source extension HomepageViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard kind == UICollectionView.elementKindSectionHeader, let headerView = collectionView.dequeueReusableSupplementaryView( ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: LabelButtonHeaderView.cellIdentifier, for: indexPath) as? LabelButtonHeaderView, let sectionViewModel = viewModel.getSectionViewModel(shownSection: indexPath.section) else { return UICollectionReusableView() } // Jump back in header specific setup if sectionViewModel.sectionType == .jumpBackIn { viewModel.jumpBackInViewModel.sendImpressionTelemetry() prepareJumpBackInContextualHint(onView: headerView) } // Configure header only if section is shown let headerViewModel = sectionViewModel.shouldShow ? sectionViewModel.headerViewModel : LabelButtonHeaderViewModel.emptyHeader headerView.configure(viewModel: headerViewModel, theme: themeManager.currentTheme) return headerView } func numberOfSections(in collectionView: UICollectionView) -> Int { return viewModel.shownSections.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewModel.getSectionViewModel(shownSection: section)?.numberOfItemsInSection() ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let viewModel = viewModel.getSectionViewModel(shownSection: indexPath.section) as? HomepageSectionHandler else { return UICollectionViewCell() } return viewModel.configure(collectionView, at: indexPath) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let viewModel = viewModel.getSectionViewModel(shownSection: indexPath.section) as? HomepageSectionHandler else { return } viewModel.didSelectItem(at: indexPath, homePanelDelegate: homePanelDelegate, libraryPanelDelegate: libraryPanelDelegate) } } // MARK: - Actions Handling private extension HomepageViewController { // Setup all the tap and long press actions on cells in each sections private func setupSectionsAction() { // Header view viewModel.headerViewModel.onTapAction = { _ in // No action currently set if the logo button is tapped. } // Message card viewModel.messageCardViewModel.dismissClosure = { [weak self] in self?.reloadView() } // Top sites viewModel.topSiteViewModel.tilePressedHandler = { [weak self] site, isGoogle in guard let url = site.url.asURL else { return } self?.showSiteWithURLHandler(url, isGoogleTopSite: isGoogle) } viewModel.topSiteViewModel.tileLongPressedHandler = { [weak self] (site, sourceView) in self?.contextMenuHelper.presentContextMenu(for: site, with: sourceView, sectionType: .topSites) } // Recently saved viewModel.recentlySavedViewModel.headerButtonAction = { [weak self] button in self?.openBookmarks(button) } // Jumpback in viewModel.jumpBackInViewModel.onTapGroup = { [weak self] tab in self?.homePanelDelegate?.homePanelDidRequestToOpenTabTray(withFocusedTab: tab) } viewModel.jumpBackInViewModel.headerButtonAction = { [weak self] button in self?.openTabTray(button) } viewModel.jumpBackInViewModel.syncedTabsShowAllAction = { [weak self] in self?.homePanelDelegate?.homePanelDidRequestToOpenTabTray(focusedSegment: .syncedTabs) var extras: [String: String]? if let isZeroSearch = self?.viewModel.isZeroSearch { extras = TelemetryWrapper.getOriginExtras(isZeroSearch: isZeroSearch) } TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .firefoxHomepage, value: .jumpBackInSectionSyncedTabShowAll, extras: extras) } viewModel.jumpBackInViewModel.openSyncedTabAction = { [weak self] tabURL in self?.homePanelDelegate?.homePanelDidRequestToOpenInNewTab(tabURL, isPrivate: false, selectNewTab: true) var extras: [String: String]? if let isZeroSearch = self?.viewModel.isZeroSearch { extras = TelemetryWrapper.getOriginExtras(isZeroSearch: isZeroSearch) } TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .firefoxHomepage, value: .jumpBackInSectionSyncedTabOpened, extras: extras) } viewModel.jumpBackInViewModel.prepareContextualHint = { [weak self] syncedTabCell in self?.prepareSyncedTabContextualHint(onCell: syncedTabCell) } // History highlights viewModel.historyHighlightsViewModel.onTapItem = { [weak self] highlight in guard let url = highlight.siteUrl else { self?.openHistoryHighlightsSearchGroup(item: highlight) return } self?.homePanelDelegate?.homePanel(didSelectURL: url, visitType: .link, isGoogleTopSite: false) } viewModel.historyHighlightsViewModel.historyHighlightLongPressHandler = { [weak self] (highlightItem, sourceView) in self?.contextMenuHelper.presentContextMenu(for: highlightItem, with: sourceView, sectionType: .historyHighlights) } viewModel.historyHighlightsViewModel.headerButtonAction = { [weak self] button in self?.openHistory(button) } // Pocket viewModel.pocketViewModel.onTapTileAction = { [weak self] url in self?.showSiteWithURLHandler(url) } viewModel.pocketViewModel.onLongPressTileAction = { [weak self] (site, sourceView) in self?.contextMenuHelper.presentContextMenu(for: site, with: sourceView, sectionType: .pocket) } viewModel.pocketViewModel.onScroll = { [weak self] cells in guard let window = UIWindow.keyWindow, let self = self else { return } let cells = self.collectionView.visibleCells.filter { $0.reuseIdentifier == PocketStandardCell.cellIdentifier } self.updatePocketCellsWithVisibleRatio(cells: cells, relativeRect: window.bounds) } // Customize home viewModel.customizeButtonViewModel.onTapAction = { [weak self] _ in self?.openCustomizeHomeSettings() } } private func openHistoryHighlightsSearchGroup(item: HighlightItem) { guard let groupItem = item.group else { return } var groupedSites = [Site]() for item in groupItem { groupedSites.append(buildSite(from: item)) } let groupSite = ASGroup<Site>(searchTerm: item.displayTitle, groupedItems: groupedSites, timestamp: Date.now()) let asGroupListViewModel = SearchGroupedItemsViewModel(asGroup: groupSite, presenter: .recentlyVisited) let asGroupListVC = SearchGroupedItemsViewController(viewModel: asGroupListViewModel, profile: viewModel.profile) let dismissableController: DismissableNavigationViewController dismissableController = DismissableNavigationViewController(rootViewController: asGroupListVC) self.present(dismissableController, animated: true, completion: nil) TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .firefoxHomepage, value: .historyHighlightsGroupOpen, extras: nil) asGroupListVC.libraryPanelDelegate = libraryPanelDelegate } private func buildSite(from highlight: HighlightItem) -> Site { let itemURL = highlight.siteUrl?.absoluteString ?? "" return Site(url: itemURL, title: highlight.displayTitle) } func openTabTray(_ sender: UIButton) { homePanelDelegate?.homePanelDidRequestToOpenTabTray(withFocusedTab: nil) if sender.accessibilityIdentifier == a11y.MoreButtons.jumpBackIn { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .firefoxHomepage, value: .jumpBackInSectionShowAll, extras: TelemetryWrapper.getOriginExtras(isZeroSearch: viewModel.isZeroSearch)) } } func openBookmarks(_ sender: UIButton) { homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .bookmarks) if sender.accessibilityIdentifier == a11y.MoreButtons.recentlySaved { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .firefoxHomepage, value: .recentlySavedSectionShowAll, extras: TelemetryWrapper.getOriginExtras(isZeroSearch: viewModel.isZeroSearch)) } } func openHistory(_ sender: UIButton) { homePanelDelegate?.homePanelDidRequestToOpenLibrary(panel: .history) if sender.accessibilityIdentifier == a11y.MoreButtons.historyHighlights { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .firefoxHomepage, value: .historyHighlightsShowAll) } } func openCustomizeHomeSettings() { homePanelDelegate?.homePanelDidRequestToOpenSettings(at: .customizeHomepage) TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .firefoxHomepage, value: .customizeHomepageButton) } func contextualHintPresented(type: ContextualHintType) { homePanelDelegate?.homePanelDidPresentContextualHintOf(type: type) } func openTabsSettings() { homePanelDelegate?.homePanelDidRequestToOpenSettings(at: .customizeTabs) } func getPopoverSourceRect(sourceView: UIView?) -> CGRect { let cellRect = sourceView?.frame ?? .zero let cellFrameInSuperview = self.collectionView?.convert(cellRect, to: self.collectionView) ?? .zero return CGRect(origin: CGPoint(x: cellFrameInSuperview.size.width / 2, y: cellFrameInSuperview.height / 2), size: .zero) } } // MARK: FirefoxHomeContextMenuHelperDelegate extension HomepageViewController: HomepageContextMenuHelperDelegate { func homePanelDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool, selectNewTab: Bool) { homePanelDelegate?.homePanelDidRequestToOpenInNewTab(url, isPrivate: isPrivate, selectNewTab: selectNewTab) } func homePanelDidRequestToOpenSettings(at settingsPage: AppSettingsDeeplinkOption) { homePanelDelegate?.homePanelDidRequestToOpenSettings(at: settingsPage) } } // MARK: - Status Bar Background private extension HomepageViewController { var statusBarFrame: CGRect? { guard let keyWindow = UIWindow.keyWindow else { return nil } return keyWindow.windowScene?.statusBarManager?.statusBarFrame } // Returns a value between 0 and 1 which indicates how far the user has scrolled. // This is used as the alpha of the status bar background. // 0 = no status bar background shown // 1 = status bar background is opaque var scrollOffset: CGFloat { // Status bar height can be 0 on iPhone in landscape mode. guard let scrollView = collectionView, isBottomSearchBar, let statusBarHeight: CGFloat = statusBarFrame?.height, statusBarHeight > 0 else { return 0 } // The scrollview content offset is automatically adjusted to account for the status bar. // We want to start showing the status bar background as soon as the user scrolls. var offset = (scrollView.contentOffset.y + statusBarHeight) / statusBarHeight if offset > 1 { offset = 1 } else if offset < 0 { offset = 0 } return offset } var isBottomSearchBar: Bool { guard SearchBarSettingsViewModel.isEnabled else { return false } return SearchBarSettingsViewModel(prefs: viewModel.profile.prefs).searchBarPosition == .bottom } func updateStatusBar(theme: Theme) { let backgroundColor = theme.colors.layer1 statusBarView.backgroundColor = backgroundColor.withAlphaComponent(scrollOffset) if let statusBarFrame = statusBarFrame { statusBarView.frame = statusBarFrame } } } // MARK: - Popover Presentation Delegate extension HomepageViewController: UIPopoverPresentationControllerDelegate { // Dismiss the popover if the device is being rotated. // This is used by the Share UIActivityViewController action sheet on iPad func popoverPresentationController( _ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView> ) { // Do not dismiss if the popover is a CFR guard !jumpBackInContextualHintViewController.isPresenting && !syncTabContextualHintViewController.isPresenting else { return } popoverPresentationController.presentedViewController.dismiss(animated: false, completion: nil) } func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool { return true } } // MARK: FirefoxHomeViewModelDelegate extension HomepageViewController: HomepageViewModelDelegate { func reloadView() { ensureMainThread { [weak self] in guard let self = self else { return } self.viewModel.refreshData(for: self.traitCollection) self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() } } } // MARK: - Notifiable extension HomepageViewController: Notifiable { func handleNotifications(_ notification: Notification) { ensureMainThread { [weak self] in guard let self = self else { return } switch notification.name { case .TabsPrivacyModeChanged: self.adjustPrivacySensitiveSections(notification: notification) case .HomePanelPrefsChanged, .WallpaperDidChange: self.reloadView() default: break } } } }
mpl-2.0
eed42ef6f3f7d246429d5f7752048f58
41.083645
162
0.66724
5.813901
false
false
false
false
waltflanagan/AdventOfCode
2017/AdventOfCode.playground/Pages/Day 18.xcplaygroundpage/Sources/New File.swift
1
5953
import Foundation public protocol ValueSender { var value: Int { get } } public protocol ValueReceiver { func set(_ value: Int) } public protocol RegisterType: ValueSender, ValueReceiver { } extension Int: ValueSender { public var value: Int { return self } } class Store { var _storage = [String: Int]() subscript(_ string: String) -> Int { get { return _storage[string, default: 0] } set { _storage[string] = newValue } } } struct Register: RegisterType { let name: String let storage: Store var value: Int { get { return storage[name] } set { set(newValue) } } func set(_ value: Int) { storage[name] = value } } class MessageQueue: RegisterType { var storage = [Int]() var hasValue: Bool { return storage.count > 0 } var value: Int { get { return storage.popLast()! } set { set(newValue) } } func set(_ value: Int) { storage.insert(value, at: 0) } } public class Pipe: RegisterType { public let incoming: RegisterType public let outgoing: RegisterType public var sendCount = 0 public init() { self.incoming = MessageQueue() self.outgoing = MessageQueue() } init(incoming: RegisterType, outgoing: RegisterType ) { self.incoming = incoming self.outgoing = outgoing } public var value: Int { get { return outgoing.value } set { set(newValue) } } public func set(_ value: Int) { sendCount += 1 incoming.set(value) } } public class DuetChannel { public let pipe1: Pipe public let pipe2: Pipe public init() { let firstPipe = Pipe() pipe1 = firstPipe pipe2 = Pipe(incoming:firstPipe.outgoing, outgoing: firstPipe.incoming) } } enum Instruction { case set(Register, ValueSender) case add(Register, ValueSender) case mul(Register, ValueSender) case mod(Register, ValueSender) case snd(ValueReceiver, ValueSender) case rcv(ValueSender, ValueReceiver) case jgz(ValueSender, ValueSender) init(string: String, storage: Store, remote: RegisterType) { let components = string.components(separatedBy: " ") let y: ValueSender? = { guard components.count == 3 else { return nil } let y = components[2] if let integer = Int(y) { return integer } else { return Register(name: y, storage: storage) } }() let x: ValueSender = { if let integer = Int(components[1]) { return integer } else { return Register(name: components[1], storage: storage) } }() switch components[0] { case "set": self = .set(x as! Register, y!) case "add": self = .add(x as! Register, y!) case "mul": self = .mul(x as! Register, y!) case "mod": self = .mod(x as! Register, y!) case "snd": self = .snd(remote, x) case "rcv": self = .rcv(remote, x as! ValueReceiver) case "jgz": self = .jgz(x, y!) default: fatalError() } } func execute() -> Int { var jumpValue = 1 switch self { case .set(var x, let y): x.value = y.value case .add(var x, let y): x.value = x.value + y.value case .mul(var x, let y): x.value = x.value * y.value case .mod(var x, let y): x.value = x.value % y.value case .snd(let remote, let x): // print("send - \(x.value)") remote.set(x.value) case .rcv(let remote, let x): // print("rcv") guard let remote = remote as? Pipe, (remote.outgoing as? MessageQueue)?.hasValue == true else { jumpValue = 0 break } x.set(remote.value) case .jgz(let x, let y): guard x.value > 0 else { return 1} jumpValue = y.value break } return jumpValue } } public let input = """ set i 31 set a 1 mul p 17 jgz p p mul a 2 add i -1 jgz i -2 add a -1 set i 127 set p 680 mul p 8505 mod p a mul p 129749 add p 12345 mod p a set b p mod b 10000 snd b add i -1 jgz i -9 jgz a 3 rcv b jgz b -1 set f 0 set i 126 rcv a rcv b set p a mul p -1 add p b jgz p 4 snd a set a b jgz 1 3 snd b set f 1 add i -1 jgz i -11 snd a jgz f -16 jgz a -19 """ public class Program { var sound: Int = 0 var currentStackPointer = 0 // var stop = false let instructionString: String let pipe: Pipe lazy var instructions: [Instruction] = { return instructionString.components(separatedBy: "\n").map { Instruction(string: $0, storage: memory, remote: pipe) } }() var memory = Store() public init(_ string: String, id: Int, pipe: Pipe) { self.pipe = pipe instructionString = string memory["p"] = id } func execute() { while (0..<(instructions.count)).contains(currentStackPointer) { print("\(currentStackPointer)") currentStackPointer += instructions[currentStackPointer].execute() } } public func tick() -> Bool { if (0..<(instructions.count)).contains(currentStackPointer) { currentStackPointer += instructions[currentStackPointer].execute() return true } else { return false } } }
mit
bb9e5067ee523fc4c059fd5cd8f89860
19.961268
126
0.519234
4.030467
false
false
false
false
michaelcordero/CoreDataStructures
Sources/CoreDataStructures/LinkedList.swift
1
6505
// // LinkedList.swift // CoreDataStructures // // Created by Michael Cordero on 1/2/21. // import Foundation open class LinkedList<T: Equatable> : List { // MARK: - Properties private var head: Node<T>? private var tail: Node<T>? private var count: Int // MARK: - Constructors public init() { count = 0 } public init(_ first: T ) { head = LinkedList<T>.Node(item: first) count = 1 } public init(_ first: T, _ last: T) { head = LinkedList<T>.Node(item: first) tail = LinkedList<T>.Node(item: last) head?.next = tail tail?.previous = head count = 2 } // MARK: - Node Inner Class private class Node<T> { var value: T? var previous: Node<T>? var next: Node<T>? // Head Constructor public init(item: T) { previous = nil next = nil value = item } public init(predecessor: Node<T>?, successor: Node<T>?, item: T){ previous = predecessor next = successor value = item } } // MARK: - Private Implementations private func addAll( collection: Array<T> ) { // to be finished later // for i in 0..<ar.count { // if i == 0 { // self.head = Node(item: ar[i]) // } // } } private func linkFirst(_ item: T) -> Void { } private func linkLast(_ item: T) -> Bool { // initialize head if it doesn't exist already let current_last_node: Node<T>? = tail let new_node: Node<T> = Node(predecessor: current_last_node, successor: nil, item: item) tail = new_node if current_last_node == nil { head = new_node } else { current_last_node?.next = new_node } count += 1 return true } private func linkBefore(_ item: T, prev: Node<T> ) -> Void { } // private func unlinkFirst(first: Node<T> ) -> T { // // } // // private func unlinkLast(last: Node<T> ) -> T { // // } // private func unlink(node: Node<T> ) -> T? { if let deleted: Node<T> = find( node.value! ) { // link up previous if let preceding: Node<T> = deleted.previous { preceding.next = deleted.next } // link up tail if let succeeding: Node<T> = deleted.next { succeeding.previous = deleted.previous } // returned detached return deleted.value } else { return nil } } private func getFirst() -> Node<T>? { return head } private func getLast() -> Node<T>? { return tail } /** - Returns: The specified node if present - Complexity: O(n/2) */ private func find(_ index: Int ) -> Node<T> { // start at the beggining if index < ( count >> 1 ) { // dividing number of elements (count) by 2 which yields the middle value var position: Int = 0 var current: Node<T> = head! while(position < index){ current = current.next ?? current position += 1 } return current } else { // start at the end and work way backwards var position: Int = count - 1 var current: Node<T> = tail! while(position > index){ current = current.previous ?? current position -= 1 } return current } } private func find(_ element: T) -> Node<T>? { var current: Node<T> = head! var position: Int = 1 while position <= count { if current.value == element { return current } else { guard current.next != nil else { return nil // not found } current = current.next! position += 1 } } return nil } private func isValidIndex(_ index: Int ) -> Bool { return index >= 0 && index <= count } // MARK: - API public func size() -> Int { var count: Int = 0 guard var current: Node<T> = head else { return count } while current.next != nil { count += 1 current = current.next! } return count } public func add(_ element: T) -> Bool { return linkLast( element ) } public func remove(_ element: T) -> T? { if let node: Node<T> = find( element ) { return unlink(node: node) } return nil } public func get(_ index: Int) -> T? { return isValidIndex( index ) ? find( index ).value : nil } public func set(_ index: Int, value: T) -> T? { if isValidIndex( index ) { let node: Node<T> = find( index ) let old_value = node.value node.value = value return old_value } else { return nil } } public func all() -> [T?] { var allValues: [T?] = [T?]() var current: Node<T>? = head ?? nil if current == nil { return allValues } repeat { allValues.append(current!.value) current = current!.next ?? nil } while current != nil return allValues } public func contains(_ element: T) -> Bool { return find( element ) != nil } public func indexOf(_ element: T) -> Int? { return Int(0) } public func clear() { head = nil tail = nil } public func sort(comparator: (T, T) throws -> Bool) { // add to array var ar: Array<T> = Array() guard var current: Node<T> = head else { return } repeat { if let item: T = current.value { ar.append( item ) } if let next: Node<T> = current.next { current = next } } while current.next != nil // sort the array try! ar.sort(by: comparator) // wipe old data clear() // create a new LinkedList addAll(collection: ar) } }
mit
1472b912540fdcc18e01b316a53a685a
25.124498
113
0.469024
4.356999
false
false
false
false
frootloops/swift
benchmark/single-source/DictionarySwap.swift
4
2548
//===--- DictionarySwap.swift ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Dictionary element swapping benchmark // rdar://problem/19804127 import TestsUtils public let DictionarySwap = [ BenchmarkInfo(name: "DictionarySwap", runFunction: run_DictionarySwap, tags: [.validation, .api, .Dictionary]), BenchmarkInfo(name: "DictionarySwapOfObjects", runFunction: run_DictionarySwapOfObjects, tags: [.validation, .api, .Dictionary]), ] @inline(never) public func run_DictionarySwap(_ N: Int) { let size = 100 var dict = [Int: Int](minimumCapacity: size) // Fill dictionary for i in 1...size { dict[i] = i } CheckResults(dict.count == size) var swapped = false for _ in 1...10000*N { (dict[25], dict[75]) = (dict[75]!, dict[25]!) swapped = !swapped if !swappedCorrectly(swapped, dict[25]!, dict[75]!) { break } } CheckResults(swappedCorrectly(swapped, dict[25]!, dict[75]!)) } // Return true if correctly swapped, false otherwise func swappedCorrectly(_ swapped: Bool, _ p25: Int, _ p75: Int) -> Bool { return swapped && (p25 == 75 && p75 == 25) || !swapped && (p25 == 25 && p75 == 75) } class Box<T : Hashable> : Hashable { var value: T init(_ v: T) { value = v } var hashValue: Int { return value.hashValue } static func ==(lhs: Box, rhs: Box) -> Bool { return lhs.value == rhs.value } } @inline(never) public func run_DictionarySwapOfObjects(_ N: Int) { let size = 100 var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size) // Fill dictionary for i in 1...size { dict[Box(i)] = Box(i) } CheckResults(dict.count == size) var swapped = false for _ in 1...10000*N { let b1 = Box(25) let b2 = Box(75) (dict[b1], dict[b2]) = (dict[b2]!, dict[b1]!) swapped = !swapped if !swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value) { break } } CheckResults(swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value)) }
apache-2.0
cd4855c5d1ec036f7d18a702b30d621d
27.311111
131
0.587127
3.843137
false
false
false
false
adrfer/swift
test/Constraints/dictionary_literal.swift
4
2924
// RUN: %target-parse-verify-swift final class DictStringInt : DictionaryLiteralConvertible { typealias Key = String typealias Value = Int init(dictionaryLiteral elements: (String, Int)...) { } } final class Dictionary<K, V> : DictionaryLiteralConvertible { typealias Key = K typealias Value = V init(dictionaryLiteral elements: (K, V)...) { } } func useDictStringInt(d: DictStringInt) {} func useDict<K, V>(d: Dictionary<K,V>) {} // Concrete dictionary literals. useDictStringInt([ "Hello" : 1 ]) useDictStringInt([ "Hello" : 1, "World" : 2]) useDictStringInt([ "Hello" : 1, "World" : 2.5]) // expected-error{{cannot convert value of type 'Double' to expected dictionary value type 'Int'}} useDictStringInt([ 4.5 : 2]) // expected-error{{cannot convert value of type 'Double' to expected dictionary key type 'String'}} useDictStringInt([ nil : 2]) // expected-error{{nil is not compatible with expected dictionary key type 'String'}} useDictStringInt([ 7 : 1, "World" : 2]) // expected-error{{cannot convert value of type 'Int' to expected dictionary key type 'String'}} // Generic dictionary literals. useDict(["Hello" : 1]) useDict(["Hello" : 1, "World" : 2]) useDict(["Hello" : 1.5, "World" : 2]) useDict([1 : 1.5, 3 : 2.5]) // Fall back to Dictionary<K, V> if no context is otherwise available. var a = ["Hello" : 1, "World" : 2] var a2 : Dictionary<String, Int> = a var a3 = ["Hello" : 1] var b = [ 1 : 2, 1.5 : 2.5 ] var b2 : Dictionary<Double, Double> = b var b3 = [1 : 2.5] // <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error // expected-note @+1 {{did you mean to use a dictionary literal instead?}} var _: Dictionary<String, (Int) -> Int>? = [ // expected-error {{contextual type 'Dictionary<String, (Int) -> Int>' (aka 'Dictionary<String, Int -> Int>') cannot be used with array literal}} "closure_1" as String, {(Int) -> Int in 0}, "closure_2", {(Int) -> Int in 0}] var _: Dictionary<String, Int>? = ["foo", 1] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} {{51-52=:}} var _: Dictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}} var _: Dictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}} // <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}}
apache-2.0
cf5404cb1dec4ccc426c229d2e58b000
44.6875
191
0.669973
3.539952
false
false
false
false
johndpope/Cerberus
Cerberus/Classes/Models/User.swift
1
416
import Foundation final class User { let name: String let email: String private let avatarSize = 128 private let gravatarUri = "http://www.gravatar.com/avatar/%@?s=%d" init(name: String, email: String) { self.name = name self.email = email } func avatarUrl() -> NSURL? { return NSURL(string: String(format: gravatarUri, self.email.md5(), avatarSize)) } }
mit
58617994ea26f3c46e2ce452bd317501
22.166667
87
0.620192
3.851852
false
false
false
false
FengDeng/RxGitHubAPI
RxGitHubAPI/RxGitHubAPI/YYContent.swift
1
771
// // YYContent.swift // RxGitHub // // Created by 邓锋 on 16/1/26. // Copyright © 2016年 fengdeng. All rights reserved. // import Foundation public class YYContent : NSObject{ public private(set) var type = "" public private(set) var encoding = "" public private(set) var size = 0 public private(set) var name = "" public private(set) var path = "" public private(set) var content = "" public private(set) var sha = "" public private(set) var html_url = "" public private(set) var download_url = "" public private(set) var _links = YYLink() //api var url = "" var git_url = "" } public class YYLink : NSObject{ public private(set) var html = "" //api var _self = "" var git = "" }
apache-2.0
7c0211d3c8bf506b5e7a626f5b58af8f
21.5
52
0.600785
3.553488
false
false
false
false
strike65/SwiftyStats
SwiftyStats/CommonSource/HypothesisTesting/SSHypothesisTesting-Outliers.swift
1
13233
// // SSHypothesisTesting-Outliers.swift // SwiftyStats // // Created by strike65 on 20.07.17. // /* Copyright (2017-2019) strike65 GNU GPL 3+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation #if os(macOS) || os(iOS) import os.log #endif extension SSHypothesisTesting { /// Performs the Grubbs outlier test /// - Parameter data: An Array<Double> containing the data /// - Parameter alpha: Alpha /// - Returns: SSGrubbsTestResult public static func grubbsTest<T, FPT>(array: Array<T>, alpha: FPT) throws -> SSGrubbsTestResult<T, FPT> where T: Codable & Comparable & Hashable, FPT: SSFloatingPoint & Codable { if array.count == 3 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("sample size is expected to be >= 3", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } if alpha <= 0 || alpha >= 1 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Alpha must be > 0.0 and < 1.0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } if !Helpers.isNumber(array[0]) { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("expected numerical type", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } do { let examine = SSExamine<T, FPT>.init(withArray: array, name: nil, characterSet: nil) return try SSHypothesisTesting.grubbsTest(data: examine, alpha: alpha) } catch { throw error } } /************************************************************************************************/ /// Performs the Grubbs outlier test /// - Parameter data: An Array<Double> containing the data /// - Parameter alpha: Alpha /// - Returns: SSGrubbsTestResult public static func grubbsTest<T, FPT>(data: SSExamine<T, FPT>, alpha: FPT) throws -> SSGrubbsTestResult<T, FPT> where T: Codable & Comparable & Hashable, FPT: SSFloatingPoint & Codable { if data.sampleSize <= 3 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("sample size is expected to be >= 3", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } if alpha <= 0 || alpha >= 1 { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("Alpha must be > 0.0 and < 1.0", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } if !data.isNumeric { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("expected numerical type", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } var g: FPT var maxDiff:FPT = 0 let mean = data.arithmeticMean! let quantile: FPT var mi: FPT, ma: FPT if let s = data.standardDeviation(type: .unbiased) { ma = Helpers.makeFP(data.maximum!) mi = Helpers.makeFP(data.minimum!) maxDiff = max(abs(ma - mean), abs(mi - mean)) g = maxDiff / s do { let pp: FPT = alpha / (2 * Helpers.makeFP(data.sampleSize)) quantile = try SSProbDist.StudentT.quantile(p: pp, degreesOfFreedom: Helpers.makeFP(data.sampleSize - 2)) } catch { throw error } let t2 = SSMath.pow1(quantile, 2) let e1: FPT = Helpers.makeFP(data.sampleSize) - 1 let e2: FPT = ( Helpers.makeFP(data.sampleSize) - 2 + t2) let e3: FPT = sqrt( Helpers.makeFP(data.sampleSize)) let t: FPT = e1 * sqrt(t2 / e2) / e3 var res:SSGrubbsTestResult<T, FPT> = SSGrubbsTestResult<T, FPT>() res.sampleSize = data.sampleSize res.maxDiff = maxDiff res.largest = data.maximum! res.smallest = data.minimum! res.criticalValue = t res.mean = mean res.G = g res.stdDev = s res.hasOutliers = g > t return res } else { return SSGrubbsTestResult() } } /************************************************************************************************/ /// Returns p for run i fileprivate static func rosnerP<FPT: SSFloatingPoint & Codable>(alpha: FPT, sampleSize: Int, run i: Int) -> FPT { let n: FPT = Helpers.makeFP(sampleSize) let ii: FPT = Helpers.makeFP(i) var ex1: FPT var ex2: FPT var ex3: FPT var ex4: FPT ex1 = n - ii ex2 = ex1 + FPT.one ex3 = 2 * ex2 ex4 = alpha / ex3 return FPT.one - ex4 } fileprivate static func rosnerLambdaRun<FPT: SSFloatingPoint & Codable>(alpha: FPT, sampleSize: Int, run i: Int!) -> FPT { let p: FPT = rosnerP(alpha: alpha, sampleSize: sampleSize, run: i) let df: FPT = Helpers.makeFP(sampleSize - i - 1) var ex1: FPT var ex2: FPT var ex3: FPT var ex4: FPT let cdfStudentT: FPT do { cdfStudentT = try SSProbDist.StudentT.quantile(p: p, degreesOfFreedom: df) } catch { return FPT.nan } let num: FPT = Helpers.makeFP(sampleSize - i) * cdfStudentT let ni: FPT = Helpers.makeFP(sampleSize - i) ex1 = ni - FPT.one ex2 = ex1 + SSMath.pow1(cdfStudentT, 2) ex3 = df + 2 ex4 = ex2 * ex3 let denom: FPT = sqrt(ex4) return num / denom } /// Uses the Rosner test (generalized extreme Studentized deviate = ESD test) to detect up to maxOutliers outliers. This test is more accurate than the Grubbs test (for Grubbs test the suspected number of outliers must be specified exactly.) /// <img src="../img/esd.png" alt=""> /// - Parameter data: Array<Double> /// - Parameter alpha: Alpha /// - Parameter maxOutliers: Upper bound for the number of outliers to detect /// - Parameter testType: SSESDTestType.lowerTail or SSESDTestType.upperTail or SSESDTestType.bothTailes (This should be default.) public static func esdOutlierTest<T: Codable & Comparable & Hashable, FPT: SSFloatingPoint & Codable>(array: Array<T>, alpha: FPT, maxOutliers: Int!, testType: SSESDTestType) throws -> SSESDTestResult<T, FPT>? { if array.count == 0 { return nil } if maxOutliers >= array.count { return nil } let examine: SSExamine<T, FPT> = SSExamine<T, FPT>.init(withArray: array, name: nil, characterSet: nil) do { return try SSHypothesisTesting.esdOutlierTest(data: examine, alpha: alpha, maxOutliers: maxOutliers, testType: testType) } catch { throw error } } /// Uses the Rosner test (generalized extreme Studentized deviate = ESD test) to detect up to maxOutliers outliers. This test is more accurate than the Grubbs test (for Grubbs test the suspected number of outliers must be specified exactly.) /// - Parameter data: Array<Double> /// - Parameter alpha: Alpha /// - Parameter maxOutliers: Upper bound for the number of outliers to detect /// - Parameter testType: SSESDTestType.lowerTail or SSESDTestType.upperTail or SSESDTestType.bothTailes (This should be default.) public static func esdOutlierTest<T: Codable & Comparable & Hashable, FPT: SSFloatingPoint & Codable>(data: SSExamine<T, FPT>, alpha: FPT, maxOutliers: Int!, testType: SSESDTestType) throws -> SSESDTestResult<T, FPT>? { if data.sampleSize == 0 { return nil } if !data.isNumeric { #if os(macOS) || os(iOS) if #available(macOS 10.12, iOS 13, *) { os_log("expected numerical type", log: .log_stat, type: .error) } #endif throw SSSwiftyStatsError.init(type: .invalidArgument, file: #file, line: #line, function: #function) } if maxOutliers >= data.sampleSize { return nil } let examine = data var sortedData = examine.elementsAsArray(sortOrder: .ascending)! let orgMean: FPT = examine.arithmeticMean! let sd: FPT = examine.standardDeviation(type: .unbiased)! var maxDiff: FPT = 0 var difference: FPT = 0 var currentMean: FPT = orgMean var currentSd = sd var currentTestStat: FPT = 0 var currentLambda: FPT var itemToRemove: T var itemsRemoved: Array<T> = Array<T>() var means: Array<FPT> = Array<FPT>() var stdDevs: Array<FPT> = Array<FPT>() let currentData: SSExamine<T, FPT> = SSExamine<T, FPT>() var currentIndex: Int = 0 var testStats: Array<FPT> = Array<FPT>() var lambdas: Array<FPT> = Array<FPT>() currentData.append(contentOf: sortedData) var i: Int = 0 var k: Int = 1 var t: FPT while k <= maxOutliers { i = 0 while i <= (sortedData.count - 1) { t = Helpers.makeFP(sortedData[i]) currentMean = currentData.arithmeticMean! difference = abs(t - currentMean) if difference > maxDiff { switch testType { case .bothTails: maxDiff = difference currentIndex = i case .lowerTail: if t < currentMean { maxDiff = difference currentIndex = i } case .upperTail: if t > currentMean { maxDiff = difference currentIndex = i } } } i = i + 1 } itemToRemove = sortedData[currentIndex] currentSd = currentData.standardDeviation(type: .unbiased)! currentMean = currentData.arithmeticMean! currentTestStat = maxDiff / currentSd currentLambda = rosnerLambdaRun(alpha: alpha, sampleSize: examine.sampleSize, run: k) sortedData.remove(at: currentIndex) currentData.removeAll() currentData.append(contentOf: sortedData) testStats.append(currentTestStat) lambdas.append(currentLambda) itemsRemoved.append(itemToRemove) means.append(currentMean) stdDevs.append(currentSd) maxDiff = 0 difference = 0 k = k + 1 } var countOfOL = 0 var outliers: Array<T> = Array<T>() i = maxOutliers for i in stride(from: maxOutliers - 1, to: 0, by: -1) { if testStats[i] > lambdas[i] { countOfOL = i + 1 break } } i = 0 while i < countOfOL { outliers.append(itemsRemoved[i]) i = i + 1 } var res: SSESDTestResult<T, FPT> = SSESDTestResult<T, FPT>() res.alpha = alpha res.countOfOutliers = countOfOL res.itemsRemoved = itemsRemoved res.lambdas = lambdas res.maxOutliers = maxOutliers res.means = means res.outliers = outliers res.stdDeviations = stdDevs res.testStatistics = testStats res.testType = testType return res } }
gpl-3.0
4398d9dc76593247710fd01738630800
38.383929
245
0.541752
4.222399
false
true
false
false
krevis/MIDIApps
Applications/SysExLibrarian/ExportController.swift
1
2521
/* Copyright (c) 2002-2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Cocoa import SnoizeMIDI class ExportController { init(windowController: MainWindowController) { self.mainWindowController = windowController } // Main window controller sends this to export messages // asSMF == YES for standard MIDI file, NO for sysex (.syx) func exportMessages(_ messages: [SystemExclusiveMessage], fromFileName: String?, asSMF: Bool) { guard let window = mainWindowController?.window else { return } // Pick a file name to export to. let ext = asSMF ? "mid" : "syx" let savePanel = NSSavePanel() savePanel.allowedFileTypes = [ext] savePanel.allowsOtherFileTypes = true savePanel.canSelectHiddenExtension = true let defaultFileName: String if let fileName = fromFileName { defaultFileName = NSString(string: fileName).deletingPathExtension } else { defaultFileName = NSLocalizedString("SysEx", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "default file name for exported standard MIDI file (w/o extension)") } savePanel.nameFieldStringValue = NSString(string: defaultFileName).appendingPathExtension(ext) ?? defaultFileName savePanel.beginSheetModal(for: window) { response in guard response == .OK else { return } if let fileData = asSMF ? SystemExclusiveMessage.standardMIDIFileData(forMessages: messages) : SystemExclusiveMessage.data(forMessages: messages), let url = savePanel.url { do { try fileData.write(to: url) } catch { let alert = NSAlert(error: error) _ = alert.runModal() } } else { let alert = NSAlert() alert.messageText = NSLocalizedString("Error", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "title of error alert") alert.informativeText = NSLocalizedString("The file could not be saved.", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "message if sysex can't be exported") _ = alert.runModal() } } } // MARK: Private private weak var mainWindowController: MainWindowController? }
bsd-3-clause
848bb178cf7e21295d4b715b4707b7d6
37.784615
186
0.633479
5.001984
false
false
false
false
Alienson/Bc
source-code/Parketovanie/Cell.swift
1
1736
// // Cell.swift // Parketovanie // // Created by Adam Turna on 2.4.2016. // Copyright © 2016 Adam Turna. All rights reserved. // import Foundation import SpriteKit class Cell: FrameController { var row: Int = Int() var collumn: Int = Int() var reserved: Bool = Bool() var barPosition: CGPoint? init() { // Testovacia Cell super.init(textureName: "stvorec-50x50") } init(position: CGPoint, parent: SKSpriteNode) { let texture = SKTexture(imageNamed: "stvorec-50x50") super.init(size: texture.size(), name: "cell", parent: parent) super.position = position addLastPosition(self.position) } init(row: Int, collumn: Int, isEmpty: Bool = true, parent: SKSpriteNode) { let imageNamed = "stvorec-50x50" super.init(textureName: imageNamed, name: "cell", parent: parent) if isEmpty { reserved = true } else { reserved = false } self.row = row self.collumn = collumn self.zPosition = CGFloat(2.0) addLastPosition(self.position) } init(row: Int, collumn: Int, parent: SKSpriteNode) { let texture = SKTexture(imageNamed: "stvorec-50x50") super.init(size: texture.size(), name: "cell", parent: parent) reserved = true self.row = row self.collumn = collumn self.zPosition = CGFloat(2.0) addLastPosition(self.position) } func reserve(reserved: Bool) { self.reserved = reserved } func isReserved() -> Bool { return reserved } required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } }
apache-2.0
d413b1c66d7f537ec203379ac8782d87
25.287879
78
0.588473
3.855556
false
false
false
false
master-nevi/UPnAtom
Source/UPnP Objects/UPnPArchivable.swift
1
3240
// // UPnPArchivable.swift // // Copyright (c) 2015 David Robles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation public class UPnPArchivable: NSObject, NSCoding { public let usn: String public let descriptionURL: NSURL init(usn: String, descriptionURL: NSURL) { self.usn = usn self.descriptionURL = descriptionURL } required public init?(coder decoder: NSCoder) { self.usn = decoder.decodeObjectForKey("usn") as! String self.descriptionURL = decoder.decodeObjectForKey("descriptionURL") as! NSURL } public func encodeWithCoder(coder: NSCoder) { coder.encodeObject(usn, forKey: "usn") coder.encodeObject(descriptionURL, forKey: "descriptionURL") } } extension AbstractUPnP { public func archivable() -> UPnPArchivable { return UPnPArchivable(usn: usn.rawValue, descriptionURL: descriptionURL) } } public class UPnPArchivableAnnex: UPnPArchivable { /// Use the custom metadata dictionary to re-populate any missing data fields from a custom device or service subclass. While it's not enforced by the compiler, the contents of the meta data must conform to the NSCoding protocol in order to be archivable. Avoided using Swift generics in order to allow compatability with Obj-C. public let customMetadata: [String: AnyObject] init(usn: String, descriptionURL: NSURL, customMetadata: [String: AnyObject]) { self.customMetadata = customMetadata super.init(usn: usn, descriptionURL: descriptionURL) } required public init?(coder decoder: NSCoder) { self.customMetadata = decoder.decodeObjectForKey("customMetadata") as! [String: AnyObject] super.init(coder: decoder) } public override func encodeWithCoder(coder: NSCoder) { super.encodeWithCoder(coder) coder.encodeObject(customMetadata, forKey: "customMetadata") } } extension AbstractUPnP { public func archivable(customMetadata customMetadata: [String: AnyObject]) -> UPnPArchivableAnnex { return UPnPArchivableAnnex(usn: usn.rawValue, descriptionURL: descriptionURL, customMetadata: customMetadata) } }
mit
031647a1aba51d6edbfb28a7b38aae3c
41.631579
332
0.728086
4.308511
false
false
false
false
naoyashiga/LegendTV
LegendTV/ContainerViewController.swift
1
3403
// // ContainerViewController.swift // Gaki // // Created by naoyashiga on 2015/07/25. // Copyright (c) 2015年 naoyashiga. All rights reserved. // import UIKit class ContainerViewController: UIViewController, KikakuCollectionViewControllerDelegate { var pageMenu : CAPSPageMenu? var controllerArray : [BaseCollectionViewController] = [] private struct NibNameSet { static let homeVC = "HomeCollectionViewController" static let kikakuVC = "KikakuCollectionViewController" static let favVC = "FavoriteCollectionViewController" static let historyVC = "HistoryCollectionViewController" static let settingVC = "SettingCollectionViewController" } override func viewDidLoad() { super.viewDidLoad() let homeVC = HomeCollectionViewController(nibName: NibNameSet.homeVC, bundle: nil) let kikakuVC = KikakuCollectionViewController(nibName: NibNameSet.kikakuVC, bundle: nil) let favVC = FavoriteCollectionViewController(nibName: NibNameSet.favVC, bundle: nil) let historyVC = HistoryCollectionViewController(nibName: NibNameSet.historyVC, bundle: nil) let settingVC = SettingCollectionViewController(nibName: NibNameSet.settingVC, bundle: nil) homeVC.title = "ピックアップ" kikakuVC.title = "企画" favVC.title = "お気に入り" historyVC.title = "履歴" settingVC.title = "その他" kikakuVC.kikakuDelegate = self controllerArray.append(homeVC) controllerArray.append(kikakuVC) controllerArray.append(favVC) controllerArray.append(historyVC) controllerArray.append(settingVC) let parameters: [CAPSPageMenuOption] = [ .ScrollMenuBackgroundColor(UIColor.scrollMenuBackgroundColor()), .ViewBackgroundColor(UIColor.viewBackgroundColor()), .SelectionIndicatorColor(UIColor.selectionIndicatorColor()), // .BottomMenuHairlineColor(UIColor.bottomMenuHairlineColor()), .SelectedMenuItemLabelColor(UIColor.selectedMenuItemLabelColor()), .UnselectedMenuItemLabelColor(UIColor.unselectedMenuItemLabelColor()), .SelectionIndicatorHeight(2.0), .MenuItemFont(UIFont(name: FontSet.bold, size: 12.0)!), .MenuHeight(30.0), .MenuItemWidth(80.0), .MenuMargin(0.0), // "useMenuLikeSegmentedControl": true, .MenuItemSeparatorRoundEdges(true), // "enableHorizontalBounce": true, // "scrollAnimationDurationOnMenuItemTap": 300, .CenterMenuItems(true)] pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 0.0, view.frame.width, view.frame.height), pageMenuOptions: parameters) if let pageMenu = pageMenu { view.addSubview(pageMenu.view) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: true) } //MARK: KikakuCollectionViewControllerDelegate func transitionViewController(ToVC ToVC: BaseTableViewController) { navigationController?.pushViewController(ToVC, animated: true) } }
mit
dcc64f18e8e8bcf7da495598cb057a5b
39.059524
160
0.676969
5.121766
false
false
false
false
ericwastaken/Xcode_Playgrounds
Playgrounds/Binary Tree IsBinaryTree (CCI).playground/Contents.swift
1
4057
/** https://www.hackerrank.com/challenges/ctci-is-binary-search-tree For the purposes of this challenge, we define a binary search tree to be a binary tree with the following ordering properties: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a binary search tree? Note: A binary tree is not a binary search if there are duplicate values. */ import Foundation class BinarySearchTree: CustomStringConvertible { var nodeValue: Int var leftTree: BinarySearchTree? var rightTree: BinarySearchTree? public var description: String { let leftTree = self.leftTree == nil ? "nil" : "\(self.leftTree!)" let rightTree = self.rightTree == nil ? "nil" : "\(self.rightTree!)" return "\(self.nodeValue): [\(leftTree), \(rightTree)]" } // initializers init(_ nodeValue:Int) { self.nodeValue = nodeValue } init(_ nodeValue:Int, leftTree:BinarySearchTree?, rightTree:BinarySearchTree) { self.nodeValue = nodeValue self.leftTree = leftTree self.rightTree = rightTree } public func getLeftChildNodeValue() -> Int? { return self.leftTree?.nodeValue } public func getRightChildNodeValue() -> Int? { return self.rightTree?.nodeValue } // Is it a BST? public func isBst() -> Bool { // Check that current node is leftNodeValue < currentNodeValue < rightNodeValue //print("checking: \(self.nodeValue)") // Left Node first if let leftNodeValue = getLeftChildNodeValue() { if leftNodeValue >= self.nodeValue { // problem, so we can already return false return false } } // Right node next if let rightNodeValue = getRightChildNodeValue() { if rightNodeValue <= self.nodeValue { // problem, so we can already return false return false } } // else, either the nodes followed the right order OR were nil (which we accept) // Recurse into left first, then right, but only if not nil let leftTreeIsBst:Bool if self.leftTree == nil { // is empty, so we call that "true" leftTreeIsBst = true } else { // not empty, so we recurse leftTreeIsBst = leftTree!.isBst() } let rightTreeIsBst:Bool if self.rightTree == nil { // is empty, so we call that "true" rightTreeIsBst = true } else { // not empty, so we recurse rightTreeIsBst = rightTree!.isBst() } return leftTreeIsBst && rightTreeIsBst } } /** Represent the following tree, which is a BST: 5 3 7 2 4 6 8 */ let e1_node2 = BinarySearchTree(2) let e1_node4 = BinarySearchTree(4) let e1_node3 = BinarySearchTree(3,leftTree:e1_node2,rightTree:e1_node4) let e1_node6 = BinarySearchTree(6) let e1_node8 = BinarySearchTree(8) let e1_node7 = BinarySearchTree(7,leftTree:e1_node6,rightTree:e1_node8) let e1_node5_root = BinarySearchTree(5,leftTree:e1_node3,rightTree:e1_node7) print("e1: \(e1_node5_root)") print("e1 isBst: \(e1_node5_root.isBst())") print() /** Represent the following tree, which is NOT a BST: 5 4 7 2 4 6 8 */ let e2_node2 = BinarySearchTree(2) let e2_node4 = BinarySearchTree(4) let e2_node4b = BinarySearchTree(4,leftTree:e2_node2,rightTree:e2_node4) let e2_node6 = BinarySearchTree(6) let e2_node8 = BinarySearchTree(8) let e2_node7 = BinarySearchTree(7,leftTree:e2_node6,rightTree:e2_node8) let e2_node5_root = BinarySearchTree(5,leftTree:e2_node4b,rightTree:e2_node7) print("e2: \(e2_node5_root)") print("e2 isBst: \(e2_node5_root.isBst())")
unlicense
a07e107669afdc9ad82b9b4a67fc0958
29.276119
127
0.625585
3.897214
false
false
false
false
Eonil/HomeworkApp1
Driver/HomeworkApp1/Client.GooglePhotoSearch.swift
1
3165
// // Networking.swift // HomeworkApp1 // // Created by Hoon H. on 2015/02/26. // // import Foundation import Standards /// Google Photo search API service. /// https://developers.google.com/image-search/v1/jsondevguide#basic /// /// Almost the only sane API documentation I could ever found. extension Client { struct ImageItem { var title:String var URL:NSURL } /// Fetches a few of arbitrary image list. /// /// /// :param: completion /// Called at transmission completion regardless success or failure. /// /// :param: imageURLs /// Fetched image URL list. /// `nil` on any error. /// /// If you `cancel` the returning `Transmission`, `completion` will not be called. static func fetchImageURLs(keyword:String, completion:(imageItems:[ImageItem]?)->()) -> Transmission { return fetchImageURL(keyword, continuation: nil, completion: completion) } static func fetchImageURL(keyword:String, continuation:Continuation?, completion:(imageItems:[ImageItem]?)->()) -> Transmission { var f = [ "v" : "1.0", "q" : keyword, "rsz" : "8", "imgtype" : "photo", ] if let c = continuation { f["start"] = c.start } let qs = HTML.Form.URLEncoded.encode(f) let u = NSURL(string: REQ_URL.stringByAppendingString(qs))! let t = NSURLSession.sharedSession().dataTaskWithURL(u, completionHandler: { (d:NSData!, r:NSURLResponse!, e:NSError!) -> Void in if d == nil { Debug.log("Client.fetchImageURL download failed with no error and no data for URL `\(u)`.") completion(imageItems: nil) return } if e != nil { if e!.domain == NSURLErrorDomain { if e!.code == NSURLErrorCancelled { // Cancelled intentionally. Debug.log("Client.fetchImageURL download from URL `\(u)` cancelled intentionally.") return } } Debug.log("Client.fetchImageURL download error while downloading URL `\(u)`: \(e)") completion(imageItems: nil) return } let j = JSON.deserialise(d!) if j == nil { Debug.log("Client.fetchImageURL downloaded `\(d.length) bytes` from URL `\(u)`, but the data is not a decodable image.") completion(imageItems: nil) return } let v = API.Response(json: j!, errorTrap: { (err:String) -> () in assert(false, err) }) if v == nil { completion(imageItems: nil) return } func toItem(m:API.Response.ResponseData.ResultItem) -> ImageItem? { if let u = NSURL(string: m.url) { return ImageItem(title: m.titleNoFormatting, URL: u) } return nil } let ms = v!.responseData.results.map(toItem) for m in ms { if m == nil { completion(imageItems: nil) return } } let ms1 = ms.map({ u in u! }) //// Debug.log(ms1) completion(imageItems: ms1) }) t.resume() return Transmission { t.cancel() } } struct Continuation { private var start:String } } /// Hardcoded for quick implementation. /// Usage: /// /// "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=moe" /// private let REQ_URL = "https://ajax.googleapis.com/ajax/services/search/images?"
mit
44ed4e6541a6a759a11852397e61a7f7
20.241611
131
0.630332
3.155533
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/Cinthyajuarez/Ejercicio1.swift
1
648
/* Instituto Nacional de México Instituto Tecnológico de Tijuana Patrones de diseño Profesor Rene Solis Ejercicio 1 Fecha: 3/2/2017 Juarez Medina Yesifer Cinthya - 13211442 @CinthyaJuarez Descripción del problema: Imprimir si las siguientes ecuaciones tienen la misma recta 3y-21x=12 y-7x=9 */ var Ecuacion1:[Int] = [3,-21,12] var Ecuacion2:[Int] = [1,-7,9] var x=0, y=0, z=0 x = Ecuacion1[0] / Ecuacion2[0] y = Ecuacion1[1] / Ecuacion2[1] z = Ecuacion1[2] / Ecuacion2[2] if x==y && y==z{ print ("La ecuacion 3y-21x=12 y y-7x=9 tienen la misma recta") } else{ print("La ecuacion 3y-21x=12 y y-7x=9 tienen diferente recta") }
gpl-3.0
0fcfc7a4300170f5e53e2e61741a4fb8
18.515152
63
0.700311
2.050955
false
false
false
false
DanielStormApps/Fanny
Fanny/fanny-widget/Widget/FNYWidgetViewController.swift
1
4520
// // FNYWidgetViewController.swift // FannyWidget // // Created by Daniel Storm on 9/15/19. // Copyright © 2019 Daniel Storm. All rights reserved. // import Cocoa import NotificationCenter class FNYWidgetViewController: NSViewController, NCWidgetProviding { @IBOutlet private weak var containerView: NSView! @IBOutlet private weak var headerTextField: FNYTextField! @IBOutlet private weak var radioButtonStackView: NSStackView! { didSet { radioButtonStackView.translatesAutoresizingMaskIntoConstraints = false radioButtonStackView.alphaValue = 0.0 radioButtonStackView.spacing = 8.0 } } @IBOutlet private weak var currentRPMTextField: FNYTextField! @IBOutlet private weak var minimumRPMTextField: FNYTextField! @IBOutlet private weak var maximumRPMTextField: FNYTextField! @IBOutlet private weak var targetRPMTextField: FNYTextField! @IBOutlet private weak var cpuTemperatureTextField: FNYTextField! @IBOutlet private weak var gpuTemperatureTextField: FNYTextField! private static let widgetNibName: String = "FNYWidgetViewController" private static let unavailableDisplayValue: String = "--" private var selectedRadioButtonTag: Int = 0 override var nibName: NSNib.Name? { return NSNib.Name(FNYWidgetViewController.widgetNibName) } // MARK: - View Cycle override func viewDidLoad() { super.viewDidLoad() updateWidget() FNYMonitor.shared.start() FNYMonitor.shared.delegate.add(self) } override func viewDidAppear() { super.viewDidAppear() FNYLauncher.shared.launchParentApplicationIfNeeded() } // MARK: - Widget Cycle func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) { updateWidget() completionHandler(.newData) } // MARK: - Update Widget private func updateWidget() { updateStackViewIfNeeded() let fans: [Fan] = FNYLocalStorage.fans() guard fans.indices.contains(selectedRadioButtonTag) else { return } let selectedFan: Fan = fans[selectedRadioButtonTag] currentRPMTextField.stringValue = selectedFan.currentRPM != nil ? "\(selectedFan.currentRPM ?? 0) RPM" : FNYWidgetViewController.unavailableDisplayValue minimumRPMTextField.stringValue = selectedFan.minimumRPM != nil ? "\(selectedFan.minimumRPM ?? 0) RPM" : FNYWidgetViewController.unavailableDisplayValue maximumRPMTextField.stringValue = selectedFan.maximumRPM != nil ? "\(selectedFan.maximumRPM ?? 0) RPM" : FNYWidgetViewController.unavailableDisplayValue targetRPMTextField.stringValue = selectedFan.targetRPM != nil ? "\(selectedFan.targetRPM ?? 0) RPM" : FNYWidgetViewController.unavailableDisplayValue cpuTemperatureTextField.stringValue = FNYLocalStorage.cpuTemperature()?.formattedTemperature() ?? FNYWidgetViewController.unavailableDisplayValue gpuTemperatureTextField.stringValue = FNYLocalStorage.gpuTemperature()?.formattedTemperature() ?? FNYWidgetViewController.unavailableDisplayValue } // MARK: - Radio Button Action @objc private func radioButtonClicked(sender: FNYRadioButton) { selectedRadioButtonTag = sender.tag updateWidget() } // MARK: - Helpers private func updateStackViewIfNeeded() { guard let numberOfFans: Int = FNYLocalStorage.numberOfFans(), numberOfFans > 1, radioButtonStackView.subviews.count != numberOfFans else { return } for subview in radioButtonStackView.subviews { radioButtonStackView.removeArrangedSubview(subview) } for i in 0..<numberOfFans { let radioButton: FNYRadioButton = FNYRadioButton(tag: i, state: i == 0 ? .on : .off, target: self, action: #selector(radioButtonClicked(sender:))) radioButtonStackView.addArrangedSubview(radioButton) } radioButtonStackView.alphaValue = 1.0 } } extension FNYWidgetViewController: FNYMonitorDelegate { // MARK: - FNYMonitorDelegate func monitorDidRefreshSystemStats(_ monitor: FNYMonitor) { updateWidget() } }
mit
5886684ce6cb575166a381f6c7bff942
37.29661
160
0.6632
5.242459
false
false
false
false
nerdishbynature/octokit.swift
Tests/OctoKitTests/ReviewTests.swift
1
3589
// // ReviewTests.swift // OctoKitTests // // Created by Franco Meloni on 08/02/2020. // Copyright © 2020 nerdish by nature. All rights reserved. // import OctoKit import XCTest class ReviewTests: XCTestCase { func testReviews() { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/repos/octocat/Hello-World/pulls/1/reviews", expectedHTTPMethod: "GET", jsonFile: "reviews", statusCode: 201) let task = Octokit().listReviews(session, owner: "octocat", repository: "Hello-World", pullRequestNumber: 1) { response in switch response { case let .success(reviews): let review = reviews.first XCTAssertEqual(review?.body, "Here is the body for the review.") XCTAssertEqual(review?.commitID, "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091") XCTAssertEqual(review?.id, 80) XCTAssertEqual(review?.state, .approved) XCTAssertEqual(review?.submittedAt, Date(timeIntervalSince1970: 1_574_012_623.0)) XCTAssertEqual(review?.user.avatarURL, "https://github.com/images/error/octocat_happy.gif") XCTAssertNil(review?.user.blog) XCTAssertNil(review?.user.company) XCTAssertNil(review?.user.email) XCTAssertEqual(review?.user.gravatarID, "") XCTAssertEqual(review?.user.id, 1) XCTAssertNil(review?.user.location) XCTAssertEqual(review?.user.login, "octocat") XCTAssertNil(review?.user.name) XCTAssertNil(review?.user.numberOfPublicGists) XCTAssertNil(review?.user.numberOfPublicRepos) XCTAssertNil(review?.user.numberOfPrivateRepos) XCTAssertEqual(review?.user.type, "User") case .failure: XCTFail("should not get an error") } } XCTAssertNotNil(task) XCTAssertTrue(session.wasCalled) } #if compiler(>=5.5.2) && canImport(_Concurrency) @available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) func testReviewsAsync() async throws { let session = OctoKitURLTestSession(expectedURL: "https://api.github.com/repos/octocat/Hello-World/pulls/1/reviews", expectedHTTPMethod: "GET", jsonFile: "reviews", statusCode: 201) let reviews = try await Octokit().reviews(session, owner: "octocat", repository: "Hello-World", pullRequestNumber: 1) let review = reviews.first XCTAssertEqual(review?.body, "Here is the body for the review.") XCTAssertEqual(review?.commitID, "ecdd80bb57125d7ba9641ffaa4d7d2c19d3f3091") XCTAssertEqual(review?.id, 80) XCTAssertEqual(review?.state, .approved) XCTAssertEqual(review?.submittedAt, Date(timeIntervalSince1970: 1_574_012_623.0)) XCTAssertEqual(review?.user.avatarURL, "https://github.com/images/error/octocat_happy.gif") XCTAssertNil(review?.user.blog) XCTAssertNil(review?.user.company) XCTAssertNil(review?.user.email) XCTAssertEqual(review?.user.gravatarID, "") XCTAssertEqual(review?.user.id, 1) XCTAssertNil(review?.user.location) XCTAssertEqual(review?.user.login, "octocat") XCTAssertNil(review?.user.name) XCTAssertNil(review?.user.numberOfPublicGists) XCTAssertNil(review?.user.numberOfPublicRepos) XCTAssertNil(review?.user.numberOfPrivateRepos) XCTAssertEqual(review?.user.type, "User") XCTAssertTrue(session.wasCalled) } #endif }
mit
e5fc228b7b01e2652aa2e5cfa897cf68
48.833333
189
0.653846
4.343826
false
true
false
false
seanmcneil/CodeHunter
Example/CodeHunter/ViewController.swift
1
4710
// // ViewController.swift // CodeHunter // // Created by seanmcneil on 10/18/2016. // Copyright (c) 2016 seanmcneil. All rights reserved. // import UIKit import CodeHunter class ViewController: CodeHunterViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // This is the default option, which sets it up with just a QR code setupCaptureSession() // This will setup the session to scan Typ128 barcodes, but it will not start until you run startSession //setupCaptureSession(autoStart: false, Barcode.type128) // This sets it up with only a PDF417 or 128 code //setupCaptureSession(Barcode.typePDF417, Barcode.type128) // You need to comply with this delegate to get the result of barcode scans, or error messages self.delegate = self // If you are using the cancel button, then you will want to enable the transitionDelegate //self.transitionDelegate = self // If you choose not to specify a match code, than any character is valid // This accepts any amount of numbers //matchCode(lettersAllowed: false, allowCapitalLetters: false, numbersAllowed: true) // This accepts 0-20 lower case letters, but no capital letters or numbers //matchCode(lettersAllowed: true, allowCapitalLetters: false, numbersAllowed: false, minLength: 0, maxLength: 20) // This uses an expression you define. For this example, it will only accept www.google.com //matchCodeWithExpression(regularExpression: "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+") // This one will fail because the max length is 0, which triggers the scanner:error: delegate method //matchCode(lettersAllowed: true, allowCapitalLetters: false, numbersAllowed: false, minLength: 0, maxLength: 0) // This one will fail because the max length is length than the min length, which triggers the scanner:error: delegate method //matchCode(lettersAllowed: true, allowCapitalLetters: false, numbersAllowed: false, minLength: 10, maxLength: 0) // The session can start automatically, but you can choose to start it at a time of your choosing with this command //startSession() // Provides a border around the scanner window with default values of 20.0 width, black color and 0.5 opacity //setupBorder() // Provides a border around the scanner window using provided values for width, color and opacity //setupBorder(width: 60.0, color: .gray, opacity: 0.25) // You can add a cancel button using the default command below. It will stop the scan & dismiss the view controller when pressed //setupCancelButton() // You can modify the cancel button with a custom message, title color and border values with the commands below. When pressed, it will terminate scan & close view //let cancelBorderProperties = CancelBorderProperties(borderColor: .black, borderWidth: 1.0, cornerRadius: 5.0) //setupCancelButton(title: "Stahp", titleColor: .white, cancelBorderProperties: cancelBorderProperties) // For taking screenshots, you can provide an image that will be placed behind any border or button you have enabled //setupScreenshot(with: UIImage(named: "blank.png")!) } } extension ViewController: CodeHunterDelegate { func scanner(_ scanner: CodeHunterViewController, barcode: String) { showAlert(controller: self, message: barcode) } func scanner(_ scanner: CodeHunterViewController, error: Error) { showAlert(controller: self, message: error.localizedDescription) } private func showAlert(controller: UIViewController, message: String) { let actionSheetController = UIAlertController(title: "CodeHunter", message: message, preferredStyle: .alert) let repeatAction = UIAlertAction(title: "Try Again", style: .default) { [weak self] action -> Void in actionSheetController.dismiss(animated: false, completion: nil) self?.startSession() } actionSheetController.addAction(repeatAction) controller.present(actionSheetController, animated: true, completion: nil) } } extension ViewController: CodeHunterTransitionDelegate { func scanner(_ scanner: CodeHunterViewController, transitionToParentController parentController: UIViewController?) { showAlert(controller: self, message: "This is where you transition your view. The scanner is now stopped.") } }
mit
2aa6dd4df3d68c4f84a61df6d2e59cee
49.645161
171
0.687473
4.860681
false
false
false
false
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/library/controls/TabBar.swift
1
3941
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit class TabBar: ItemBar { var underscore = UIView() override var selectedIndex: Int { didSet { self.moveUnderscore(self.selectedIndex) } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override var itemWidth : CGFloat { return self.frame.width / CGFloat(self.items.count) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func draw(_ rect: CGRect) { let aPath = UIBezierPath() aPath.move(to: CGPoint(x:0, y:self.frame.height)) aPath.addLine(to: CGPoint(x:self.frame.width, y:self.frame.height)) aPath.close() aPath.lineWidth = 2.0 UIColor.sldsTextColor(.colorTextLinkActive).set() aPath.stroke() } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func loadView() { super.loadView() self.accessibilityTraits = UIAccessibilityTraitTabBar self.underscore.backgroundColor = UIColor.sldsBorderColor(.colorBorderSelection) self.addSubview(self.underscore) self.constrainChild(self.underscore, xAlignment: .left, yAlignment: .bottom, height: 3) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func layoutSubviews() { super.layoutSubviews() if self.underscore.widthConstraint.constant != self.itemWidth { self.underscore.widthConstraint.constant = self.itemWidth self.moveUnderscore(self.selectedIndex, animated: false) } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func addTab(withLabelString labelString :String) { let tab = UIButton() tab.setTitle(labelString.uppercased(), for: .normal) tab.titleLabel?.font = UIFont.sldsFont(.regular, with: .small) tab.setTitleColor(UIColor.sldsTextColor(.colorTextDefault), for: .normal) super.addItem(item: tab) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func moveUnderscore(_ index : Int, animated:Bool = true) { for c in self.constraints { if c.firstItem as! NSObject == underscore, c.firstAttribute == .left { c.constant = CGFloat(index) * self.itemWidth } } if animated { UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: { self.layoutIfNeeded() }) } else { self.layoutIfNeeded() } } }
bsd-3-clause
3d98047facdf1f50f994c129d51e17f7
32.388889
93
0.477205
5.606343
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Settings/HomepageSettings/WallpaperSettings/v1/WallpaperSettingsViewModel.swift
2
9180
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import Shared public enum WallpaperSettingsError: Error { case itemNotFound } class WallpaperSettingsViewModel { typealias a11yIds = AccessibilityIdentifiers.Settings.Homepage.CustomizeFirefox.Wallpaper typealias stringIds = String.Settings.Homepage.Wallpaper enum WallpaperSettingsLayout: Equatable { case compact case regular // The maximum number of items to display per row var itemsPerRow: Int { switch self { case .compact: return 3 case .regular: return 4 } } } struct Constants { struct Strings { struct Toast { static let label: String = stringIds.WallpaperUpdatedToastLabel static let button: String = stringIds.WallpaperUpdatedToastButton } } } private var theme: Theme private var wallpaperManager: WallpaperManagerInterface private var wallpaperCollections = [WallpaperCollection]() var tabManager: TabManagerProtocol var sectionLayout: WallpaperSettingsLayout = .compact // We use the compact layout as default var selectedIndexPath: IndexPath? var numberOfSections: Int { return wallpaperCollections.count } init(wallpaperManager: WallpaperManagerInterface = WallpaperManager(), tabManager: TabManagerProtocol, theme: Theme) { self.wallpaperManager = wallpaperManager self.tabManager = tabManager self.theme = theme setupWallpapers() } func numberOfWallpapers(in section: Int) -> Int { return wallpaperCollections[safe: section]?.wallpapers.count ?? 0 } func sectionHeaderViewModel(for sectionIndex: Int, dismissView: @escaping (() -> Void) ) -> WallpaperSettingsHeaderViewModel? { guard let collection = wallpaperCollections[safe: sectionIndex] else { return nil } let isClassic = collection.type == .classic let classicString = String(format: stringIds.ClassicWallpaper, AppName.shortName.rawValue) let title: String = isClassic ? classicString : stringIds.LimitedEditionWallpaper var description: String? = isClassic ? nil : stringIds.IndependentVoicesDescription let buttonTitle: String? = isClassic ? nil : stringIds.LearnMoreButton // the first limited edition collection has a different description, any other collection uses the default if sectionIndex > 1 { description = stringIds.LimitedEditionDefaultDescription } let buttonAction = { [weak self] in guard let strongSelf = self, let learnMoreUrl = collection.learnMoreUrl else { return } dismissView() let tab = strongSelf.tabManager.addTab(URLRequest(url: learnMoreUrl), afterTab: strongSelf.tabManager.selectedTab, isPrivate: false) strongSelf.tabManager.selectTab(tab, previous: nil) } return WallpaperSettingsHeaderViewModel( theme: theme, title: title, titleA11yIdentifier: "\(a11yIds.collectionTitle)_\(sectionIndex)", description: description, descriptionA11yIdentifier: "\(a11yIds.collectionDescription)_\(sectionIndex)", buttonTitle: buttonTitle, buttonA11yIdentifier: "\(a11yIds.collectionButton)_\(sectionIndex)", buttonAction: collection.learnMoreUrl != nil ? buttonAction : nil) } func updateSectionLayout(for traitCollection: UITraitCollection) { if traitCollection.horizontalSizeClass == .compact { sectionLayout = .compact } else { sectionLayout = .regular } } func cellViewModel(for indexPath: IndexPath) -> WallpaperCellViewModel? { guard let collection = wallpaperCollections[safe: indexPath.section], let wallpaper = collection.wallpapers[safe: indexPath.row] else { return nil } return cellViewModel(for: wallpaper, collectionType: collection.type, indexPath: indexPath) } func downloadAndSetWallpaper(at indexPath: IndexPath, completion: @escaping (Result<Void, Error>) -> Void) { guard let collection = wallpaperCollections[safe: indexPath.section], let wallpaper = collection.wallpapers[safe: indexPath.row] else { completion(.failure(WallpaperSelectorError.itemNotFound)) return } let setWallpaperBlock = { [weak self] in self?.updateCurrentWallpaper(for: wallpaper, in: collection) { result in if case .success = result { self?.selectedIndexPath = indexPath } completion(result) } } if wallpaper.needsToFetchResources { wallpaperManager.fetchAssetsFor(wallpaper) { result in switch result { case .success: setWallpaperBlock() case .failure: completion(result) } } } else { setWallpaperBlock() } } func removeAssetsOnDismiss() { wallpaperManager.removeUnusedAssets() } func selectHomepageTab() { let homepageTab = getHomepageTab(isPrivate: tabManager.selectedTab?.isPrivate ?? false) tabManager.selectTab(homepageTab, previous: nil) } /// Get mostRecentHomePage used if none is available we add and select a new homepage Tab /// - Parameter isPrivate: If private mode is selected private func getHomepageTab(isPrivate: Bool) -> Tab { guard let homepageTab = tabManager.getMostRecentHomepageTab() else { return tabManager.addTab(nil, afterTab: nil, isPrivate: isPrivate) } return homepageTab } } private extension WallpaperSettingsViewModel { var initialSelectedIndexPath: IndexPath? { for (sectionIndex, collection) in wallpaperCollections.enumerated() { if let rowIndex = collection.wallpapers.firstIndex(where: {$0 == wallpaperManager.currentWallpaper}) { return IndexPath(row: rowIndex, section: sectionIndex) } } return nil } func setupWallpapers() { wallpaperCollections = wallpaperManager.availableCollections selectedIndexPath = initialSelectedIndexPath } func cellViewModel(for wallpaper: Wallpaper, collectionType: WallpaperCollectionType, indexPath: IndexPath ) -> WallpaperCellViewModel { let a11yId = "\(a11yIds.card)_\(indexPath.section)_\(indexPath.row)" var a11yLabel: String switch collectionType { case .classic: a11yLabel = "\(String(format: stringIds.ClassicWallpaper, AppName.shortName.rawValue)) \(indexPath.row + 1)" case .limitedEdition: a11yLabel = "\(stringIds.LimitedEditionWallpaper) \(indexPath.row + 1)" } let cellViewModel = WallpaperCellViewModel(image: wallpaper.thumbnail, a11yId: a11yId, a11yLabel: a11yLabel) return cellViewModel } func updateCurrentWallpaper(for wallpaper: Wallpaper, in collection: WallpaperCollection, completion: @escaping (Result<Void, Error>) -> Void) { wallpaperManager.setCurrentWallpaper(to: wallpaper) { [weak self] result in guard let extra = self?.telemetryMetadata(for: wallpaper, in: collection) else { completion(result) return } TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .wallpaperSettings, value: .wallpaperSelected, extras: extra) completion(result) } } func telemetryMetadata(for wallpaper: Wallpaper, in collection: WallpaperCollection) -> [String: String] { var metadata = [String: String]() metadata[TelemetryWrapper.EventExtraKey.wallpaperName.rawValue] = wallpaper.id let wallpaperTypeKey = TelemetryWrapper.EventExtraKey.wallpaperType.rawValue switch (wallpaper.type, collection.type) { case (.defaultWallpaper, _): metadata[wallpaperTypeKey] = "default" case (.other, .classic): metadata[wallpaperTypeKey] = collection.type.rawValue case (.other, .limitedEdition): metadata[wallpaperTypeKey] = collection.id } return metadata } }
mpl-2.0
95775ad04c3b8a8624dfabe3eede70bf
37.410042
120
0.615468
5.550181
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/Extensions/NSString+Digits.swift
1
715
// // NSString+Digits.swift // AviasalesSDKTemplate // // Created by Dim on 31.05.2018. // Copyright © 2018 Go Travel Un Limited. All rights reserved. // extension NSString { private static let digits: [String : String] = { let formatter = NumberFormatter() formatter.locale = Locale(identifier: "ar") var digits = [String : String]() Array(0...9).forEach { value in if let key = formatter.string(from: NSNumber(value: value)) { digits[key] = "\(value)" } } return digits }() @objc func arabicDigits() -> String { return (self as String).map { NSString.digits["\($0)"] ?? "\($0)" }.joined() } }
mit
f2fe947fea6b297bf5e5c12fdd49e5bb
26.461538
84
0.561625
3.966667
false
false
false
false
yagiz/Bagel
mac/Bagel/Workers/BagelController/Publisher/BagelPublisher.swift
1
3648
// // BagelPublisher.swift // Bagel // // Created by Yagiz Gurgul on 26.09.2018. // Copyright © 2018 Yagiz Lab. All rights reserved. // import Cocoa import CocoaAsyncSocket protocol BagelPublisherDelegate { func didGetPacket(publisher: BagelPublisher, packet: BagelPacket) } class BagelPublisher: NSObject { var delegate: BagelPublisherDelegate? var mainSocket: GCDAsyncSocket! var sockets: [GCDAsyncSocket] = [] var netService: NetService! func startPublishing() { self.sockets = [] self.mainSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.global(qos: .background)) do { try self.mainSocket.accept(onPort: UInt16(BagelConfiguration.netServicePort)) self.sockets.append(self.mainSocket) self.netService = NetService(domain: BagelConfiguration.netServiceDomain, type: BagelConfiguration.netServiceType, name: BagelConfiguration.netServiceName, port: BagelConfiguration.netServicePort) self.netService.delegate = self self.netService.publish() } catch { self.tryPublishAgain() } } func lengthOf(data: Data) -> Int { var length = 0 memcpy(&length, ([UInt8](data)), MemoryLayout<UInt64>.stride) return length } func parseBody(data: Data) { let jsonDecoder = JSONDecoder() jsonDecoder.dateDecodingStrategy = .secondsSince1970 do { let bagelPacket = try jsonDecoder.decode(BagelPacket.self, from: data) DispatchQueue.main.async { self.delegate?.didGetPacket(publisher: self, packet: bagelPacket) } } catch { print(error) } } } extension BagelPublisher: NetServiceDelegate { func netServiceDidPublish(_ sender: NetService) { print("publish", sender) } func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]) { print("error", errorDict) } } extension BagelPublisher: GCDAsyncSocketDelegate { func socket(_ sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) { self.sockets.append(newSocket) newSocket.delegate = self newSocket.readData(toLength: UInt(MemoryLayout<UInt64>.stride), withTimeout: -1.0, tag: 0) } func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { if tag == 0 { let length = self.lengthOf(data: data) sock.readData(toLength: UInt(length), withTimeout: -1.0, tag: 1) } else if tag == 1 { self.parseBody(data: data) sock.readData(toLength: UInt(MemoryLayout<UInt64>.stride), withTimeout: -1.0, tag: 0) } } func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { if self.sockets.contains(sock) { sock.delegate = nil self.sockets = Array(self.sockets.filter { $0 !== sock }) if self.sockets.count == 0 { self.tryPublishAgain() } } } func tryPublishAgain() { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { self.startPublishing() } } }
apache-2.0
6728917d0aa446e368db25347b1c41df
24.865248
208
0.558541
4.989056
false
false
false
false
nakau1/Formations
Formations/Sources/Extensions/String+Common.swift
1
2774
// ============================================================================= // Formations // Copyright 2017 yuichi.nakayasu All rights reserved. // ============================================================================= import Foundation // MARK: - String拡張: subscript - extension String { subscript(i: Int) -> String { return String(self[index(startIndex, offsetBy: i)]) } subscript(start: Int, end: Int) -> String { let si = start < startIndex.encodedOffset ? startIndex.encodedOffset : start let ei = end > endIndex.encodedOffset ? endIndex.encodedOffset : end if si > ei { return "" } let s = index(startIndex, offsetBy: si) let e = index(startIndex, offsetBy: ei) return String(self[s..<e]) } } // MARK: - String拡張: 構成チェック - extension String { /// 半角数字の構成 static let structureOfNumber = "0123456789" /// 半角小文字アルファベットの構成 static let structureOfLowercaseAlphabet = "abcdefghijklmnopqrstuvwxyz" /// 半角大文字アルファベットの構成 static let structureOfUppercaseAlphabet = structureOfLowercaseAlphabet.uppercased() /// 半角アルファベットの構成 static let structureOfAlphabet = structureOfLowercaseAlphabet + structureOfUppercaseAlphabet /// 半角英数字の構成 static let structureOfAlphabetNumber = structureOfAlphabet + structureOfNumber /// 半角数字のみで構成されているかどうか public var isOnlyNumber: Bool { return isOnly(structuredBy: String.structureOfNumber) } /// 半角アルファベットのみで構成されているかどうか public var isOnlyAlphabet: Bool { return isOnly(structuredBy: String.structureOfAlphabet) } /// 半角英数字のみで構成されているかどうか public var isOnlyAlphabetNumber: Bool { return isOnly(structuredBy: String.structureOfAlphabetNumber) } /// 半角英数字とハイフン、半角スペースのみで構成されているかどうか public var isOnlyAlphabetNumberHyphenWhitespace: Bool { return isOnly(structuredBy: String.structureOfAlphabetNumber + " -") } /// 指定した文字のみで構成されているかどうかを返す /// - parameter chars: 指定の文字 /// - returns: 渡した文字のみで構成されているかどうか public func isOnly(structuredBy chars: String) -> Bool { let characterSet = NSMutableCharacterSet() characterSet.addCharacters(in: chars) return trimmingCharacters(in: characterSet as CharacterSet).count <= 0 } }
apache-2.0
50c493756ce163fdeb5c127de4990a2d
31.833333
96
0.626481
3.979798
false
false
false
false
visenze/visearch-widget-swift
ViSearchWidgets/ViSearchWidgets/Models/ViProduct.swift
2
1546
// // ViProduct.swift // ViSearchWidgets // // Created by Hung on 25/10/16. // Copyright © 2016 Visenze. All rights reserved. // import UIKit /// Model to hold data for product card /// Based on the provided schema mapping and ViSenze API response, data will be populated in this class /// Represent a single product open class ViProduct: NSObject { // MARK: properties /// im_name for image, identify this image in ViSenze API public var im_name: String /// underlying image. This take precendence over image url. If set, image url will be ignored public var image: UIImage? = nil /// image url to load public var imageUrl : URL? = nil /// label e.g. for product brand public var label : String? = nil /// heading e.g. for product title public var heading: String? = nil /// price public var price: Float? = nil /// discounted price public var discountPrice : Float? = nil /// meta data dictionary retrieved from visenze API public var metadataDict: [String : Any]? = nil // MARK: constructors public init(im_name: String, url: URL, price: Float?){ self.imageUrl = url self.price = price self.im_name = im_name } public convenience init?(im_name: String, urlString: String, price: Float? = nil){ if let url = URL(string: urlString) { self.init (im_name: im_name, url: url, price: price) } else { return nil } } }
mit
b1eaf9a4851cf9996d55fd6b97a7ff5d
25.186441
103
0.611003
4.175676
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Foundation/Pluralize.swift
1
8965
// // Pluralize.swift // ZeeQL3 // // Created by Helge Hess on 04.06.17. // Copyright © 2017-2019 ZeeZide GmbH. All rights reserved. // public extension String { // Inspired by: // https://github.com/rails/rails/blob/master/activesupport/lib/active_support/inflections.rb var singularized : String { // FIXME: case switch self { // case compare // irregular case "people": return "person" case "men": return "man" case "children": return "child" case "sexes": return "sex" case "moves": return "move" case "zombies": return "zombie" case "staff": return "staff" // regular case "mice": return "mouse" case "lice": return "louse" case "mouse": return "mouse" case "louse": return "louse" // other case "axis", "axes": return "axis" case "analysis", "analyses": return "analysis" default: break } let len = self.count if len > 2 { if self.hasCISuffix("octopi") { return self.cutoffTrailer(1) + "us" } if self.hasCISuffix("viri") { return self.cutoffTrailer(1) + "us" } if self.hasCISuffix("aliases") { return self.cutoffTrailer(2) } if self.hasCISuffix("statuses") { return self.cutoffTrailer(2) } if self.hasCISuffix("oxen") { return self.cutoffTrailer(2) } if self.hasCISuffix("vertices") { return self.cutoffTrailer(4) + "ex" } if self.hasCISuffix("indices") { return self.cutoffTrailer(4) + "ex" } if self.hasCISuffix("matrices") { return self.cutoffTrailer(3) + "x" } if self.hasCISuffix("quizzes") { return self.cutoffTrailer(3) } if self.hasCISuffix("databases") { return self.cutoffTrailer(1) } if self.hasCISuffix("crises") { return self.cutoffTrailer(2) + "is" } if self.hasCISuffix("crises") { return self } if self.hasCISuffix("testes") { return self.cutoffTrailer(2) + "is" } if self.hasCISuffix("testis") { return self } if self.hasCISuffix("shoes") { return self.cutoffTrailer(1) } if self.hasCISuffix("oes") { return self.cutoffTrailer(2) } if self.hasCISuffix("buses") { return self.cutoffTrailer(2) } if self.hasCISuffix("bus") { return self } if self.hasCISuffix("mice") { return self.cutoffTrailer(3) + "ouse" } if self.hasCISuffix("lice") { return self.cutoffTrailer(3) + "ouse" } if self.hasCISuffix("xes") { return self.cutoffTrailer(2) } if self.hasCISuffix("ches") { return self.cutoffTrailer(2) } if self.hasCISuffix("sses") { return self.cutoffTrailer(2) } if self.hasCISuffix("shes") { return self.cutoffTrailer(2) } if self.hasCISuffix("ies") && len > 3 { if self.hasCISuffix("movies") { return self.cutoffTrailer(1) } if self.hasCISuffix("series") { return self } if self.hasCISuffix("quies") { return self.cutoffTrailer(3) + "y" } let cidx = self.index(endIndex, offsetBy: -4) let c = self[cidx] if c != "a" && c != "e" && c != "i" && c != "o" && c != "u" && c != "y" { return self.cutoffTrailer(3) + "y" } } if self.hasCISuffix("lves") { return self.cutoffTrailer(3) + "f" } if self.hasCISuffix("rves") { return self.cutoffTrailer(3) + "f" } if self.hasCISuffix("tives") { return self.cutoffTrailer(1) } if self.hasCISuffix("hives") { return self.cutoffTrailer(1) } if self.hasCISuffix("ves") && len > 3 { let cidx = self.index(endIndex, offsetBy: -4) if self[cidx] != "f" { return self.cutoffTrailer(3) + "fe" } } if self.hasCISuffix("sis") { if self.hasCISuffix("analysis") { return self } if self.hasCISuffix("basis") { return self } if self.hasCISuffix("diagnosis") { return self } if self.hasCISuffix("parenthesis") { return self } if self.hasCISuffix("prognosis") { return self } if self.hasCISuffix("synopsis") { return self } if self.hasCISuffix("thesis") { return self } } else if self.hasCISuffix("ses") { if self.hasCISuffix("analyses") { return self.cutoffTrailer(3) + "sis" } if self.hasCISuffix("bases") { return self.cutoffTrailer(3) + "sis" } if self.hasCISuffix("diagnoses") { return self.cutoffTrailer(3) + "sis" } if self.hasCISuffix("parentheses") { return self.cutoffTrailer(3) + "sis" } if self.hasCISuffix("prognoses") { return self.cutoffTrailer(3) + "sis" } if self.hasCISuffix("synopses") { return self.cutoffTrailer(3) + "sis" } if self.hasCISuffix("theses") { return self.cutoffTrailer(3) + "sis" } } if self.hasCISuffix("ta") { return self.cutoffTrailer(2) + "um" } if self.hasCISuffix("ia") { return self.cutoffTrailer(2) + "um" } if self.hasCISuffix("news") { return self } } if self.hasCISuffix("ss") { return self.cutoffTrailer(2) } if self.hasCISuffix("s") { return self.cutoffTrailer(1) } return self } var pluralized : String { // FIXME: case switch self { // irregular case "person": return "people" case "man": return "men" case "child": return "children" case "sex": return "sexes" case "move": return "moves" case "zombie": return "zombies" case "staff": return "staff" // regular case "mice": return "mice" case "lice": return "lice" case "mouse": return "mice" case "louse": return "lice" default: break } if self.hasCISuffix("quiz") { return self + "zes" } if self.hasCISuffix("oxen") { return self } if self.hasCISuffix("ox") { return self + "en" } if self.hasCISuffix("matrix") { return self.replaceSuffix("matrix", "matrices") } if self.hasCISuffix("vertex") { return self.replaceSuffix("vertex", "vertices") } if self.hasCISuffix("index") { return self.replaceSuffix("index", "indices") } if self.hasCISuffix("ch") { return self + "es" } if self.hasCISuffix("ss") { return self + "es" } if self.hasCISuffix("sh") { return self + "es" } if self.hasCISuffix("quy") { return self.replaceSuffix("quy", "quies") } if self.hasCISuffix("y") { if self.count > 2 { let idx = self.index(self.endIndex, offsetBy: -2) let cbY = self[idx] switch cbY { // https://www.youtube.com/watch?v=gUrJKN7F_so case "a", "e", "i", "o", "u": break default: return self.replaceSuffix("y", "ies") } if self.hasCISuffix("ry") { return self.replaceSuffix("ry", "ries") } } } if self.hasCISuffix("hive") { return self + "hives" } // TODO: (?:([^f])fe|([lr])f) => '\1\2ves' if self.hasCISuffix("sis") { return self + "ses" } // TODO: replace? if self.hasCISuffix("ta") { return self } if self.hasCISuffix("ia") { return self } if self.hasCISuffix("tum") { return self.replaceSuffix("tum", "ta") } if self.hasCISuffix("ium") { return self.replaceSuffix("ium", "ia") } if self.hasCISuffix("buffalo") { return self.replaceSuffix("buffalo", "buffaloes") } if self.hasCISuffix("tomato") { return self.replaceSuffix("tomato", "tomatoes") } if self.hasCISuffix("bus") { return self.replaceSuffix("bus", "buses") } if self.hasCISuffix("alias") { return self + "es" } if self.hasCISuffix("status") { return self + "es" } if self.hasCISuffix("octopi") { return self } if self.hasCISuffix("viri") { return self } if self.hasCISuffix("octopus") { return self.replaceSuffix("octopus", "octopi") } if self.hasCISuffix("virus") { return self.replaceSuffix("virus", "viri") } if self == "axis" { return "axes" } if self == "testis" { return "testes" } if self.hasCISuffix("s") { return self } return self + "s" } } fileprivate extension String { func hasCIPrefix(_ s: String) -> Bool { // urks return lowercased().hasPrefix(s.lowercased()) } func hasCISuffix(_ s: String) -> Bool { // urks return lowercased().hasSuffix(s.lowercased()) } func cutoffTrailer(_ count: Int) -> String { guard self.count >= count else { return self } let endIdx = self.index(endIndex, offsetBy: -count) return String(self[startIndex..<endIdx]) } func replaceSuffix(_ suffix: String, _ with: String) -> String { guard hasSuffix(suffix) else { return self } let endIdx = self.index(endIndex, offsetBy: -(suffix.count)) return self[startIndex..<endIdx] + with } }
apache-2.0
e5139da7c42769d3b1480155d376b530
36.041322
97
0.576751
3.413557
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKitMock/MockAnnouncement.swift
1
1324
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxSwift import XCTest @testable import AnalyticsKit @testable import BlockchainNamespace #if canImport(AnalyticsKitMock) @testable import AnalyticsKitMock #endif @testable import PlatformKit @testable import PlatformUIKit @testable import ToolKit #if canImport(ToolKitMock) @testable import ToolKitMock #endif struct MockOneTimeAnnouncement: OneTimeAnnouncement { var viewModel: AnnouncementCardViewModel { fatalError("\(#function) was not implemented") } var associatedAppModes: [AppMode] = [.legacy, .trading] var shouldShow: Bool { !isDismissed } let dismiss: CardAnnouncementAction let recorder: AnnouncementRecorder let type: AnnouncementType let analyticsRecorder: AnalyticsEventRecorderAPI init( type: AnnouncementType, cacheSuite: CacheSuite, analyticsRecorder: AnalyticsEventRecorderAPI = AnalyticsEventRecorder( analyticsServiceProviders: [MockAnalyticsService()] ), dismiss: @escaping CardAnnouncementAction ) { self.type = type recorder = AnnouncementRecorder(cache: cacheSuite, errorRecorder: MockErrorRecorder()) self.analyticsRecorder = analyticsRecorder self.dismiss = dismiss } }
lgpl-3.0
65028d6851a55373793a200873784660
26.5625
94
0.733182
5.334677
false
true
false
false
fitpay/fitpay-ios-sdk
FitpaySDK/Rest/RestSession.swift
1
8191
import Foundation import Alamofire @objcMembers open class RestSession: NSObject { open var userId: String? open var accessToken: String? open var isAuthorized: Bool { return accessToken != nil } let defaultHeaders = [ "Accept": "application/json", "X-FitPay-SDK": "iOS-\(FitpayConfig.sdkVersion)" ] private var restRequest: RestRequestable = RestRequest() private typealias AcquireAccessTokenHandler = (AuthorizationDetails?, NSError?) -> Void // MARK: - Lifecycle public init(sessionData: SessionData? = nil, restRequest: RestRequestable? = nil) { if let sessionData = sessionData { self.accessToken = sessionData.token self.userId = sessionData.userId } if let restRequest = restRequest { self.restRequest = restRequest } } // MARK: - Public Functions @objc open func setWebViewAuthorization(_ webViewSessionData: SessionData) { accessToken = webViewSessionData.token userId = webViewSessionData.userId } @objc open func login(username: String, password: String, completion: @escaping (_ error: NSError?) -> Void) { acquireAccessToken(username: username, password: password) { (details, error) in if let error = error { completion(error) } else { self.setIdAndToken(details: details, completion: completion) } } } @objc open func login(firebaseToken: String, completion: @escaping (_ error: NSError?) -> Void) { acquireAccessToken(firebaseToken: firebaseToken) { (details, error) in if let error = error { completion(error) } else { self.setIdAndToken(details: details, completion: completion) } } } // MARK: - Private Functions private func acquireAccessToken(username: String, password: String, completion: @escaping AcquireAccessTokenHandler) { let parameters: [String: String] = [ "response_type": "token", "client_id": FitpayConfig.clientId, "redirect_uri": FitpayConfig.redirectURL, "credentials": ["username": username, "password": password].JSONString! ] makeAuthorizeRequest(url: FitpayConfig.authURL + "/oauth/authorize", parameters: parameters, completion: completion) } private func acquireAccessToken(firebaseToken: String, completion: @escaping AcquireAccessTokenHandler) { let parameters: [String: String] = [ "response_type": "token", "client_id": FitpayConfig.clientId, "redirect_uri": FitpayConfig.redirectURL, "firebase_token": firebaseToken ] makeAuthorizeRequest(url: FitpayConfig.authURL + "/oauth/token", parameters: parameters, completion: completion) } private func setIdAndToken(details: AuthorizationDetails?, completion: @escaping (_ error: NSError?) -> Void) { guard let accessToken = details?.accessToken else { completion(NSError.error(code: ErrorEnum.accessTokenFailure, domain: RestSession.self, message: "Failed to retrieve access token")) return } guard let jwt = try? JWS(token: accessToken) else { completion(NSError.error(code: ErrorEnum.decodeFailure, domain: RestSession.self, message: "Failed to decode access token")) return } guard let userId = jwt.body["user_id"] as? String else { completion(NSError.error(code: ErrorEnum.parsingFailure, domain: RestSession.self, message: "Failed to parse user id")) return } log.verbose("REST_SESSION: successfully acquired token for user: \(userId)") self.userId = userId self.accessToken = accessToken completion(nil) } private func makeAuthorizeRequest(url: String, parameters: [String: String], completion: @escaping AcquireAccessTokenHandler) { restRequest.makeRequest(url: url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: defaultHeaders) { (resultValue, error) in if let error = error { completion(nil, error) return } let authorizationDetails = try? AuthorizationDetails(resultValue) completion(authorizationDetails, nil) } } } extension RestSession { typealias GetUserAndDeviceCompletion = (User?, Device?, ErrorResponse?) -> Void // TODO: Refactor into instance for testability class func GetUserAndDeviceWith(sessionData: SessionData, completion: @escaping GetUserAndDeviceCompletion) -> RestClient? { guard let userId = sessionData.userId, let deviceId = sessionData.deviceId else { completion(nil, nil, ErrorResponse(domain: RestSession.self, errorCode: ErrorCode.userOrDeviceEmpty.rawValue, errorMessage: "")) return nil } let session = RestSession(sessionData: sessionData) let client = RestClient(session: session) client.user(id: userId) { (user, error) in guard user != nil && error == nil else { completion(nil, nil, error) return } user?.getDevices(limit: 20, offset: 0) { (devicesCollection, error) in guard user != nil && error == nil else { completion(nil, nil, error) return } if let device = devicesCollection?.results?.first(where: { $0.deviceIdentifier == deviceId }) { completion(user!, device, nil) return } devicesCollection?.collectAllAvailable { (devices, error) in guard error == nil, let devices = devices else { completion(nil, nil, error) return } if let device = devices.first(where: { $0.deviceIdentifier == deviceId }) { completion(user!, device, nil) return } completion(nil, nil, ErrorResponse(domain: RestSession.self, errorCode: ErrorCode.deviceNotFound.rawValue, errorMessage: "")) } } } return client } class func GetUserAndDeviceWith(token: String, userId: String, deviceId: String, completion: @escaping GetUserAndDeviceCompletion) -> RestClient? { return RestSession.GetUserAndDeviceWith(sessionData: SessionData(token: token, userId: userId, deviceId: deviceId), completion: completion) } } // MARK: - Nested Objects extension RestSession { public enum ErrorEnum: Int, Error, RawIntValue { case decodeFailure = 1000 case parsingFailure case accessTokenFailure } public enum ErrorCode: Int, Error, RawIntValue, CustomStringConvertible { case unknownError = 0 case deviceNotFound = 10001 case userOrDeviceEmpty = 10002 public var description: String { switch self { case .unknownError: return "Unknown error" case .deviceNotFound: return "Can't find device provided by wv." case .userOrDeviceEmpty: return "User or device empty." } } } struct AuthorizationDetails: Serializable { var tokenType: String? var accessToken: String? var expiresIn: String? var scope: String? var jti: String? private enum CodingKeys: String, CodingKey { case tokenType = "token_type" case accessToken = "access_token" case expiresIn = "expires_in" case scope case jti } } }
mit
8386d01730d21a4db9e0dc7905a8f743
36.401826
162
0.586986
5.213877
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Tool/Sources/ToolKit/General/Extensions/UInt256.swift
1
6513
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import Foundation extension BigInt.Sign { static func from(string: String) -> BigInt.Sign { string.contains(Character("-")) ? .minus : .plus } } extension BigInt { public init?(_ string: String, decimals: Int) { let sign = Sign.from(string: string) let trimmedString = string.replacingOccurrences(of: "-", with: "") guard let maginitude = BigUInt(trimmedString, decimals: decimals) else { return nil } self.init(sign: sign, magnitude: maginitude) } } extension BigUInt { /// - Parameter string: String number. can be: "0.023", "123123123.12312312312" /// - Parameter decimals: Number of decimals that string should be multiplyed by public init?(_ string: String, decimals: Int) { let separators = CharacterSet(charactersIn: ".,") let components = string.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: separators) guard components.count == 1 || components.count == 2 else { return nil } let unitDecimals = decimals guard var mainPart = BigUInt(components[0], radix: 10) else { return nil } mainPart *= BigUInt(10).power(unitDecimals) if components.count == 2 { let numDigits = components[1].count guard numDigits <= unitDecimals else { return nil } guard let afterDecPoint = BigUInt(components[1], radix: 10) else { return nil } let extraPart = afterDecPoint * BigUInt(10).power(unitDecimals - numDigits) mainPart += extraPart } self = mainPart } /// Number to string convertion options public struct StringOptions: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// Fallback to scientific number. (like `1.0e-16`) public static let fallbackToScientific = StringOptions(rawValue: 0b1) /// Removes last zeroes (will print `1.123` instead of `1.12300000000000`) public static let stripZeroes = StringOptions(rawValue: 0b10) /// Default options: [.stripZeroes] public static let `default`: StringOptions = [.stripZeroes] } /// Formats a BigUInt object to String. The supplied number is first divided into integer and decimal part based on "toUnits", /// then limit the decimal part to "decimals" symbols and uses a "decimalSeparator" as a separator. /// Fallbacks to scientific format if higher precision is required. /// default: decimals: 18, decimalSeparator: ".", options: .stripZeroes public func string(unitDecimals: Int, decimals: Int = 18, decimalSeparator: String = ".", options: StringOptions = .default) -> String { guard self != 0 else { return "0" } var toDecimals = decimals if unitDecimals < toDecimals { toDecimals = unitDecimals } let divisor = BigUInt(10).power(unitDecimals) let (quotient, remainder) = quotientAndRemainder(dividingBy: divisor) var fullRemainder = String(remainder) let fullPaddedRemainder = fullRemainder.leftPadding(toLength: unitDecimals, withPad: "0") let remainderPadded = fullPaddedRemainder[0..<toDecimals] let offset = remainderPadded.reversed().firstIndex(where: { $0 != "0" })?.base if let offset = offset { if toDecimals == 0 { return String(quotient) } else if options.contains(.stripZeroes) { return String(quotient) + decimalSeparator + remainderPadded[..<offset] } else { return String(quotient) + decimalSeparator + remainderPadded } } else if quotient != 0 || !options.contains(.fallbackToScientific) { return String(quotient) } else { var firstDigit = 0 for char in fullPaddedRemainder { if char == "0" { firstDigit += 1 } else { let firstDecimalUnit = String(fullPaddedRemainder[firstDigit..<firstDigit + 1]) var remainingDigits = "" let numOfRemainingDecimals = fullPaddedRemainder.count - firstDigit - 1 if numOfRemainingDecimals <= 0 { remainingDigits = "" } else if numOfRemainingDecimals > decimals { let end = firstDigit + 1 + decimals > fullPaddedRemainder.count ? fullPaddedRemainder.count : firstDigit + 1 + decimals remainingDigits = String(fullPaddedRemainder[firstDigit + 1..<end]) } else { remainingDigits = String(fullPaddedRemainder[firstDigit + 1..<fullPaddedRemainder.count]) } fullRemainder = firstDecimalUnit if !remainingDigits.isEmpty { fullRemainder += decimalSeparator + remainingDigits } firstDigit += 1 break } } return fullRemainder + "e-" + String(firstDigit) } } } extension BigInt { /// Typealias public typealias StringOptions = BigUInt.StringOptions /// Formats a BigInt object to String. The supplied number is first divided into integer and decimal part based on "units", /// then limit the decimal part to "decimals" symbols and uses a "decimalSeparator" as a separator. /// Fallbacks to scientific format if higher precision is required. /// default: decimals: 18, decimalSeparator: ".", options: .stripZeroes public func string(unitDecimals: Int, decimals: Int = 18, decimalSeparator: String = ".", options: StringOptions = .default) -> String { let formatted = magnitude.string(unitDecimals: unitDecimals, decimals: decimals, decimalSeparator: decimalSeparator, options: options) switch sign { case .plus: return formatted case .minus: return "-" + formatted } } } extension String { fileprivate func leftPadding(toLength: Int, withPad character: Character) -> String { let stringLength = count if stringLength < toLength { return String(repeatElement(character, count: toLength - stringLength)) + self } else { return String(suffix(toLength)) } } }
lgpl-3.0
ad1f595b78f4a8d0616e3fa0ef91d388
43.60274
143
0.614558
4.899925
false
false
false
false
Brightify/Reactant
Source/CollectionView/Identifier/CollectionViewCellIdentifier.swift
2
1743
// // CollectionViewCellIdentifier.swift // Reactant // // Created by Filip Dolnik on 15.11.16. // Copyright © 2016 Brightify. All rights reserved. // import RxSwift public struct CollectionViewCellIdentifier<T: UIView> { internal let name: String public init(name: String = NSStringFromClass(T.self)) { self.name = name } } extension UICollectionView { public func register<T>(identifier: CollectionViewCellIdentifier<T>) { register(CollectionViewCellWrapper<T>.self, forCellWithReuseIdentifier: identifier.name) } public func unregister<T>(identifier: CollectionViewCellIdentifier<T>) { register(nil as AnyClass?, forCellWithReuseIdentifier: identifier.name) } } extension UICollectionView { public func dequeue<T>(identifier: CollectionViewCellIdentifier<T>, for indexPath: IndexPath) -> CollectionViewCellWrapper<T> { guard let cell = dequeueReusableCell(withReuseIdentifier: identifier.name, for: indexPath) as? CollectionViewCellWrapper<T> else { fatalError("\(identifier) is not registered.") } return cell } public func dequeue<T>(identifier: CollectionViewCellIdentifier<T>, forRow row: Int, inSection section: Int = 0) -> CollectionViewCellWrapper<T> { return dequeue(identifier: identifier, for: IndexPath(row: row, section: section)) } public func items<S: Sequence, Cell, O: ObservableType>(with identifier: CollectionViewCellIdentifier<Cell>) -> (_ source: O) -> (_ configureCell: @escaping (Int, S.Iterator.Element, CollectionViewCellWrapper<Cell>) -> Void) -> Disposable where O.Element == S { return rx.items(cellIdentifier: identifier.name) } }
mit
cefbf0c16ab8310c7828ed31f31e69a6
35.291667
157
0.700918
4.759563
false
false
false
false
aiwalle/LiveProject
LiveProject/Test/TestSwiftController.swift
1
2053
// // TestSwiftController.swift // LiveProject // // Created by liang on 2017/7/25. // Copyright © 2017年 liang. All rights reserved. // import UIKit import Kingfisher class TestSwiftController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } func testGif() { let imageView = UIImageView(frame: CGRect(x: 0, y: 100, width: 300, height: 200)) // 这个很卡 // LJGifImageManager.loadLocalGifWithImageName(imageView: imageView, imageName: "timg") // 这个非常流畅 let filePath = Bundle.main.url(forResource: "timg", withExtension: "gif") imageView.kf.setImage(with: filePath) view.addSubview(imageView) } func test1() { // 可选类型 // var arr : Array<String> = Array() // var name : Optional<String> = nil // name = "string" // // // Optional("string") // // print(name) // // 对可选类型进行解包 // // 强制解包 // // print(name!) // if let name = name { // print(name) // } // // // // let url : URL? = URL(string: "http://www.baidu.com") // if let url = URL(string: "http://www.baidu.com") { // var request : URLRequest? = URLRequest(url: url) // } // // view.backgroundColor = .white let emoView = EmoticonView.loadFromNib() view.addSubview(emoView) let gift = GiftView.loadFromNib() view.addSubview(gift) // 协议规定了遵守的类型,因此这里报错 // let person = Person.loadFromNib() } }
mit
c30a41196ac223caefc86673800a3b63
22.357143
102
0.438838
4.594848
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/QMUIKit/UICommon/QMUICommonDefines.swift
1
21952
// // QMUICommonDefines.swift // QMUI.swift // // Created by 伯驹 黄 on 2017/1/17. // Copyright © 2017年 伯驹 黄. All rights reserved. // // MARK: - 变量-编译相关 /// 判断当前是否debug编译模式 #if DEBUG let IS_DEBUG = true #else let IS_DEBUG = false #endif // 设备类型 let IS_IPAD = QMUIHelper.isIPad let IS_IPAD_PRO = QMUIHelper.isIPadPro let IS_IPOD = QMUIHelper.isIPod let IS_IPHONE = QMUIHelper.isIPhone let IS_SIMULATOR = QMUIHelper.isSimulator /// 操作系统版本号 let IOS_VERSION = (UIDevice.current.systemVersion as NSString).floatValue /// 数字形式的操作系统版本号,可直接用于大小比较;如 110205 代表 11.2.5 版本;根据 iOS 规范,版本号最多可能有3位 let IOS_VERSION_NUMBER = QMUIHelper.numbericOSVersion /// 是否横竖屏,用户界面横屏了才会返回true let IS_LANDSCAPE = UIApplication.shared.statusBarOrientation.isLandscape /// 无论支不支持横屏,只要设备横屏了,就会返回YES let IS_DEVICE_LANDSCAPE = UIDevice.current.orientation.isLandscape /// 屏幕宽度,会根据横竖屏的变化而变化 let SCREEN_WIDTH = UIScreen.main.bounds.width /// 屏幕高度,会根据横竖屏的变化而变化 let SCREEN_HEIGHT = UIScreen.main.bounds.height /// 屏幕宽度,跟横竖屏无关 let DEVICE_WIDTH = IS_LANDSCAPE ? UIScreen.main.bounds.height : UIScreen.main.bounds.width /// 屏幕高度,跟横竖屏无关 let DEVICE_HEIGHT = IS_LANDSCAPE ? UIScreen.main.bounds.width : UIScreen.main.bounds.height /// 设备屏幕尺寸 /// iPhoneX let IS_58INCH_SCREEN = QMUIHelper.is58InchScreen /// iPhone6/7/8 Plus let IS_55INCH_SCREEN = QMUIHelper.is55InchScreen /// iPhone6/7/8 let IS_47INCH_SCREEN = QMUIHelper.is47InchScreen /// iPhone5/5s/SE let IS_40INCH_SCREEN = QMUIHelper.is40InchScreen /// iPhone4/4s let IS_35INCH_SCREEN = QMUIHelper.is35InchScreen // iPhone4/4s/5/5s/SE let IS_320WIDTH_SCREEN = (IS_35INCH_SCREEN || IS_40INCH_SCREEN) /// 是否Retina let IS_RETINASCREEN = UIScreen.main.scale >= 2.0 // 是否放大模式(iPhone 6及以上的设备支持放大模式) let IS_ZOOMEDMODE = ScreenNativeScale > ScreenScale /// MARK: - 变量-布局相关 /// bounds && nativeBounds / scale && nativeScale let ScreenBoundsSize = UIScreen.main.bounds.size let ScreenNativeBoundsSize = UIScreen.main.nativeBounds.size let ScreenScale = UIScreen.main.scale let ScreenNativeScale = UIScreen.main.nativeScale /// 状态栏高度(来电等情况下,状态栏高度会发生变化,所以应该实时计算) let StatusBarHeight = UIApplication.shared.statusBarFrame.height /// navigationBar相关frame let NavigationBarHeight: CGFloat = (IS_LANDSCAPE ? PreferredVarForDevices(44, 32, 32, 32) : 44) /// toolBar的相关frame let ToolBarHeight: CGFloat = (IS_LANDSCAPE ? PreferredVarForUniversalDevicesIncludingIPhoneX(44, 44, 53, 32, 32, 32) : PreferredVarForUniversalDevicesIncludingIPhoneX(44, 44, 83, 44, 44, 44)) /// tabBar相关frame let TabBarHeight: CGFloat = (IS_LANDSCAPE ? PreferredVarForUniversalDevicesIncludingIPhoneX(49, 49, 53, 32, 32, 32) : PreferredVarForUniversalDevicesIncludingIPhoneX(49, 49, 83, 49, 49, 49)) /// 保护 iPhoneX 安全区域的 insets let IPhoneXSafeAreaInsets: UIEdgeInsets = QMUIHelper.safeAreaInsetsForIPhoneX // 获取顶部导航栏占位高度,从而在布局 subviews 时可以当成 minY 参考 // 注意,以下两个宏已废弃,请尽量使用 UIViewController (QMUI) qmui_navigationBarMaxYInViewCoordinator 代替 let NavigationContentTop = StatusBarHeight + NavigationBarHeight let NavigationContentStaticTop = NavigationContentTop /// 获取一个像素 let PixelOne = QMUIHelper.pixelOne /// 获取最合适的适配值,默认以varFor55Inch为准,也即偏向大屏 func PreferredVarForDevices<T>(_ varFor55Inch: T, _ varFor47or58Inch: T, _ varFor40Inch: T, _ varFor35Inch: T) -> T { return PreferredVarForUniversalDevices(varFor55Inch, varFor55Inch, varFor47or58Inch, varFor40Inch, varFor35Inch) } /// 同上,加多一个iPad的参数 func PreferredVarForUniversalDevices<T>(_ varForPad: T, _ varFor55Inch: T, _ varFor47or58Inch: T, _ varFor40Inch: T, _ varFor35Inch: T) -> T { return PreferredVarForUniversalDevicesIncludingIPhoneX(varForPad, varFor55Inch, varFor47or58Inch, varFor47or58Inch, varFor40Inch, varFor35Inch) } // 同上,包含 iPhoneX func PreferredVarForUniversalDevicesIncludingIPhoneX<T>(_ varForPad: T, _ varFor55Inch: T, _ varFor58Inch: T, _ varFor47Inch: T, _ varFor40Inch: T, _ varFor35Inch: T) -> T { let result = (IS_IPAD ? varForPad : (IS_35INCH_SCREEN ? varFor35Inch : (IS_40INCH_SCREEN ? varFor40Inch : (IS_47INCH_SCREEN ? varFor47Inch : (IS_55INCH_SCREEN ? varFor55Inch : varFor58Inch))))) return result } /// MARK: - 方法-创建器 /// 使用文件名(不带后缀名)创建一个UIImage对象,会被系统缓存,适用于大量复用的小资源图 /// 使用这个 API 而不是 imageNamed: 是因为后者在 iOS 8 下反而存在性能问题(by molice 不确定 iOS 9 及以后的版本是否还有这个问题) let UIImageMake: (String) -> UIImage? = { UIImage(named: $0, in: nil, compatibleWith: nil) } /// 使用文件名(不带后缀名,仅限png)创建一个UIImage对象,不会被系统缓存,用于不被复用的图片,特别是大图 let UIImageMakeWithFile: (String) -> UIImage? = { UIImageMakeWithFileAndSuffix($0, "png") } let UIImageMakeWithFileAndSuffix: (String, String) -> UIImage? = { UIImage(contentsOfFile: "\(Bundle.main.resourcePath ?? "")/\($0).\($1)") } // 字体相关的宏,用于快速创建一个字体对象,更多创建宏可查看 UIFont+QMUI.swift let UIFontMake: (CGFloat) -> UIFont = { UIFont.systemFont(ofSize: $0) } /// 斜体只对数字和字母有效,中文无效 let UIFontItalicMake: (CGFloat) -> UIFont = { UIFont.italicSystemFont(ofSize: $0) } let UIFontBoldMake: (CGFloat) -> UIFont = { UIFont.boldSystemFont(ofSize: $0) } let UIFontBoldWithFont: (UIFont) -> UIFont = { UIFont.boldSystemFont(ofSize: $0.pointSize) } let UIFontLightMake: (CGFloat) -> UIFont = { UIFont.qmui_lightSystemFont(ofSize: $0) } let UIFontLightWithFont: (UIFont) -> UIFont = { UIFont.qmui_lightSystemFont(ofSize: $0.pointSize) } let UIDynamicFontMake: (CGFloat) -> UIFont = { UIFont.qmui_dynamicFont(ofSize: $0, weight: .normal, italic: false) } let UIDynamicFontMakeWithLimit: (CGFloat, CGFloat, CGFloat) -> UIFont = { pointSize, upperLimitSize, lowerLimitSize in UIFont.qmui_dynamicFont(ofSize: pointSize, upperLimitSize: upperLimitSize, lowerLimitSize: lowerLimitSize, weight: .normal, italic: false) } let UIDynamicFontBoldMake: (CGFloat) -> UIFont = { UIFont.qmui_dynamicFont(ofSize: $0, weight: .bold, italic: false) } let UIDynamicFontBoldMakeWithLimit: (CGFloat, CGFloat, CGFloat) -> UIFont = { pointSize, upperLimitSize, lowerLimitSize in UIFont.qmui_dynamicFont(ofSize: pointSize, upperLimitSize: upperLimitSize, lowerLimitSize: lowerLimitSize, weight: .bold, italic: true) } let UIDynamicFontLightMake: (CGFloat) -> UIFont = { UIFont.qmui_dynamicFont(ofSize: $0, weight: .light, italic: false) } /// MARK: - 数学计算 let AngleWithDegrees: (CGFloat) -> CGFloat = { .pi * $0 / 180.0 } /// MARK: - 动画 extension UIView.AnimationOptions { static var curveOut: UIView.AnimationOptions { return UIView.AnimationOptions(rawValue: 7 << 16) } static var curveIn: UIView.AnimationOptions { return UIView.AnimationOptions(rawValue: 8 << 16) } } /// MARK: - 其他 func StringFromBool(_flag: Bool) -> String { if _flag { return "true" } return "false" } /// MARK: - 方法-C对象、结构操作 func ReplaceMethod(_ _class: AnyClass, _ _originSelector: Selector, _ _newSelector: Selector) { let oriMethod = class_getInstanceMethod(_class, _originSelector) let newMethod = class_getInstanceMethod(_class, _newSelector) let isAddedMethod = class_addMethod(_class, _originSelector, method_getImplementation(newMethod!), method_getTypeEncoding(newMethod!)) if isAddedMethod { class_replaceMethod(_class, _newSelector, method_getImplementation(oriMethod!), method_getTypeEncoding(oriMethod!)) } else { method_exchangeImplementations(oriMethod!, newMethod!) } } /// MARK: - CGFloat /** * 基于指定的倍数,对传进来的 floatValue 进行像素取整。若指定倍数为0,则表示以当前设备的屏幕倍数为准。 * * 例如传进来 “2.1”,在 2x 倍数下会返回 2.5(0.5pt 对应 1px),在 3x 倍数下会返回 2.333(0.333pt 对应 1px)。 */ func flatSpecificScale(_ value: CGFloat, _ scale: CGFloat) -> CGFloat { let s = scale == 0 ? ScreenScale : scale return ceil(value * s) / s } /** * 基于当前设备的屏幕倍数,对传进来的 floatValue 进行像素取整。 * * 注意如果在 Core Graphic 绘图里使用时,要注意当前画布的倍数是否和设备屏幕倍数一致,若不一致,不可使用 flat() 函数,而应该用 flatSpecificScale */ func flat(_ value: CGFloat) -> CGFloat { return flatSpecificScale(value, 0) } /** * 类似flat(),只不过 flat 是向上取整,而 floorInPixel 是向下取整 */ func floorInPixel(_ value: CGFloat) -> CGFloat { let resultValue = floor(value * ScreenScale) / ScreenScale return resultValue } func between(_ minimumValue: CGFloat, _ value: CGFloat, _ maximumValue: CGFloat) -> Bool { return minimumValue < value && value < maximumValue } func betweenOrEqual(_ minimumValue: CGFloat, _ value: CGFloat, _ maximumValue: CGFloat) -> Bool { return minimumValue <= value && value <= maximumValue } extension CGFloat { /** * 某些地方可能会将 CGFLOAT_MIN 作为一个数值参与计算(但其实 CGFLOAT_MIN 更应该被视为一个标志位而不是数值),可能导致一些精度问题,所以提供这个方法快速将 CGFLOAT_MIN 转换为 0 * issue: https://github.com/QMUI/QMUI_iOS/issues/203 */ func removeFloatMin() -> CGFloat { return self == CGFloat.leastNormalMagnitude ? 0 : self } /** * 调整给定的某个 CGFloat 值的小数点精度,超过精度的部分按四舍五入处理。 * * 例如 0.3333.fixed(2) 会返回 0.33,而 0.6666.fixed(2) 会返回 0.67 * * @warning 参数类型为 CGFloat,也即意味着不管传进来的是 float 还是 double 最终都会被强制转换成 CGFloat 再做计算 * @warning 该方法无法解决浮点数精度运算的问题 */ func fixed(_ precision: Int) -> CGFloat { let nf = NumberFormatter() nf.numberStyle = .decimal nf.maximumFractionDigits = precision var cgFloat:CGFloat = 0 if let result = nf.string(from: NSNumber(value: Double(self))), let doubleValue = Double(result) { cgFloat = CGFloat(doubleValue) } return cgFloat } /// 用于居中运算 func center(_ child: CGFloat) -> CGFloat { return flat((self - child) / 2.0) } } // MARK: - CGPoint extension CGPoint { /// 两个point相加 func union(_ point: CGPoint) -> CGPoint { return CGPoint(x: flat(x + point.x), y: flat(y + point.y)) } func fixed(_ precision: Int) -> CGPoint { let x = self.x.fixed(precision) let y = self.y.fixed(precision) let result = CGPoint(x: x, y: y) return result } func removeFloatMin() -> CGPoint { let x = self.x.removeFloatMin() let y = self.y.removeFloatMin() let result = CGPoint(x: x, y: y) return result } } // MARK: - CGRect /// 创建一个像素对齐的CGRect let CGRectFlat: (CGFloat, CGFloat, CGFloat, CGFloat) -> CGRect = { x, y, w, h in CGRect(x: flat(x), y: flat(y), width: flat(w), height: flat(h)) } extension CGRect { /// 通过 size 获取一个 x/y 为 0 的 CGRect static func rect(size: CGSize) -> CGRect { return CGRect(x: 0, y: 0, width: size.width, height: size.height) } /// 获取rect的center,包括rect本身的x/y偏移 var center: CGPoint { return CGPoint(x: flat(midX), y: flat(midY)) } /// 对CGRect的x/y、width/height都调用一次flat,以保证像素对齐 var flatted: CGRect { return CGRect(x: flat(minX), y: flat(minY), width: flat(width), height: flat(height)) } /// 判断一个 CGRect 是否存在NaN var isNaN: Bool { return self.origin.x.isNaN || self.origin.y.isNaN || self.size.width.isNaN || self.size.height.isNaN } /// 系统提供的 CGRectIsInfinite 接口只能判断 CGRectInfinite 的情况,而该接口可以用于判断 INFINITY 的值 var isInf: Bool { return self.origin.x.isInfinite || self.origin.y.isInfinite || self.size.width.isInfinite || self.size.height.isInfinite } /// 判断一个 CGRect 是否合法(例如不带无穷大的值、不带非法数字) var isValidated: Bool { return !self.isNull && !self.isInfinite && !self.isNaN && !self.isInf } /// 为一个CGRect叠加scale计算 func apply(scale: CGFloat) -> CGRect { return CGRect(x: minX * scale, y: minY * scale, width: width * scale, height: height * scale).flatted } /// 计算view的水平居中,传入父view和子view的frame,返回子view在水平居中时的x值 func minXHorizontallyCenter(in parentRect: CGRect) -> CGFloat { return flat((parentRect.width - width) / 2.0) } /// 计算view的垂直居中,传入父view和子view的frame,返回子view在垂直居中时的y值 func minYVerticallyCenter(in parentRect: CGRect) -> CGFloat { return flat((parentRect.height - height) / 2.0) } /// 返回值:同一个坐标系内,想要layoutingRect和已布局完成的referenceRect(self)保持垂直居中时,layoutingRect的originY func minYVerticallyCenter(_ layoutingRect: CGRect) -> CGFloat { return minY + layoutingRect.minYVerticallyCenter(in: self) } /// 返回值:同一个坐标系内,想要layoutingRect和已布局完成的referenceRect保持水平居中时,layoutingRect的originX func minXHorizontallyCenter(_ layoutingRect: CGRect) -> CGFloat { return minX + layoutingRect.minXHorizontallyCenter(in: self) } /// 为给定的rect往内部缩小insets的大小 func insetEdges(_ insets: UIEdgeInsets) -> CGRect { let newX = minX + insets.left let newY = minY + insets.top let newWidth = width - insets.horizontalValue let newHeight = height - insets.verticalValue return CGRect(x: newX, y: newY, width: newWidth, height: newHeight) } func float(top: CGFloat) -> CGRect { var result = self result.origin.y = top return result } func float(bottom: CGFloat) -> CGRect { var result = self result.origin.y = bottom - height return result } func float(right: CGFloat) -> CGRect { var result = self result.origin.x = right - width return result } func float(left: CGFloat) -> CGRect { var result = self result.origin.x = left return result } /// 保持rect的左边缘不变,改变其宽度,使右边缘靠在right上 func limit(right: CGFloat) -> CGRect { var result = self result.size.width = right - minX return result } /// 保持rect右边缘不变,改变其宽度和origin.x,使其左边缘靠在left上。只适合那种右边缘不动的view /// 先改变origin.x,让其靠在offset上 /// 再改变size.width,减少同样的宽度,以抵消改变origin.x带来的view移动,从而保证view的右边缘是不动的 func limit(left: CGFloat) -> CGRect { var result = self let subOffset = left - minX result.origin.x = left result.size.width -= subOffset return result } /// 限制rect的宽度,超过最大宽度则截断,否则保持rect的宽度不变 func limit(maxWidth: CGFloat) -> CGRect { var result = self result.size.width = width > maxWidth ? maxWidth : width return result } func setX(_ x: CGFloat) -> CGRect { var result = self result.origin.x = flat(x) return result } func setY(_ y: CGFloat) -> CGRect { var result = self result.origin.y = flat(y) return result } func setXY(_ x: CGFloat, _ y: CGFloat) -> CGRect { var result = self result.origin.x = flat(x) result.origin.y = flat(y) return result } func setWidth(_ width: CGFloat) -> CGRect { var result = self result.size.width = flat(width) return result } func setHeight(_ height: CGFloat) -> CGRect { var result = self result.size.height = flat(height) return result } func setSize(size: CGSize) -> CGRect { var result = self result.size = size.flatted return result } func fixed(_ precision: Int) -> CGRect { let x = self.origin.x.fixed(precision) let y = self.origin.y.fixed(precision) let width = self.width.fixed(precision) let height = self.height.fixed(precision) let result = CGRect(x: x, y: y, width: width, height: height) return result } func removeFloatMin() -> CGRect { let x = self.origin.x.removeFloatMin() let y = self.origin.y.removeFloatMin() let width = self.width.removeFloatMin() let height = self.height.removeFloatMin() let result = CGRect(x: x, y: y, width: width, height: height) return result } } // MARK: - CGSize extension CGSize { // static var max: CGSize { // return CGSize(width: CGFloat.infinity, height: CGFloat.infinity) // } /// 返回一个x/y为0的CGRect var rect: CGRect { return CGRect(origin: .zero, size: self) } var center: CGPoint { return CGPoint(x: flat(width / 2.0), y: flat(height / 2.0)) } /// 判断一个size是否为空(宽或高为0) var isEmpty: Bool { return width <= 0 || height <= 0 } /// 将一个CGSize像素对齐 var flatted: CGSize { return CGSize(width: flat(width), height: flat(height)) } /// 将一个 CGSize 以 pt 为单位向上取整 var sizeCeil: CGSize { return CGSize(width: ceil(width), height: ceil(height)) } /// 将一个 CGSize 以 pt 为单位向下取整 var sizeFloor: CGSize { return CGSize(width: floor(width), height: floor(height)) } static var max: CGSize { return CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) } func fixed(_ precision: Int) -> CGSize { let width = self.width.fixed(precision) let height = self.height.fixed(precision) let result = CGSize(width: width, height: height) return result } func removeFloatMin() -> CGSize { let width = self.width.removeFloatMin() let height = self.height.removeFloatMin() let result = CGSize(width: width, height: height) return result } } // MARK: - UIEdgeInsets extension UIEdgeInsets { /// 获取UIEdgeInsets在水平方向上的值 var horizontalValue: CGFloat { return left + right } /// 获取UIEdgeInsets在垂直方向上的值 var verticalValue: CGFloat { return top + bottom } /// 将两个UIEdgeInsets合并为一个 func concat(insets: UIEdgeInsets) -> UIEdgeInsets { let top = self.top + insets.top let left = self.left + insets.left let bottom = self.bottom + insets.bottom let right = self.right + insets.right return UIEdgeInsets(top: top, left: left, bottom: bottom, right: right) } func fixed(_ precision: Int) -> UIEdgeInsets { let top = self.top.fixed(precision) let left = self.left.fixed(precision) let bottom = self.bottom.fixed(precision) let right = self.right.fixed(precision) let result = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right) return result } func removeFloatMin() -> UIEdgeInsets { let top = self.top.removeFloatMin() let left = self.left.removeFloatMin() let bottom = self.bottom.removeFloatMin() let right = self.right.removeFloatMin() let result = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right) return result } } // MARK: - NSRange extension NSRange { func containing(innerRange: NSRange) -> Bool { if innerRange.location >= self.location && self.location + self.length >= innerRange.location + innerRange.length { return true } return false } }
mit
8a03e6af778abbabc79005bf7a5310c0
32.5
197
0.636523
3.58375
false
false
false
false
lorentey/swift
test/stdlib/Accelerate_vImage.swift
8
28795
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: rdar50244151 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import Accelerate var Accelerate_vImageTests = TestSuite("Accelerate_vImage") if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { let width = UInt(64) let height = UInt(32) let widthi = 64 let heighti = 32 //===----------------------------------------------------------------------===// // // MARK: Converter // //===----------------------------------------------------------------------===// Accelerate_vImageTests.test("vImage/CVConverters") { let colorSpace = CGColorSpaceCreateDeviceRGB() let cgFormat = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: colorSpace, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.first.rawValue), renderingIntent: .defaultIntent)! let cvFormat = vImageCVImageFormat.make(format: .format32ABGR, matrix: kvImage_ARGBToYpCbCrMatrix_ITU_R_601_4.pointee, chromaSiting: .center, colorSpace: colorSpace, alphaIsOpaqueHint: false)! let coreVideoToCoreGraphics = try! vImageConverter.make(sourceFormat: cvFormat, destinationFormat: cgFormat, flags: .printDiagnosticsToConsole) let coreGraphicsToCoreVideo = try! vImageConverter.make(sourceFormat: cgFormat, destinationFormat: cvFormat, flags: .printDiagnosticsToConsole) let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in return UInt8.random(in: 0 ..< 255) } let image = makeRGBA8888Image(from: pixels, width: width, height: height)! let sourceCGBuffer = try! vImage_Buffer(cgImage: image) var intermediateCVBuffer = try! vImage_Buffer(width: widthi, height: heighti, bitsPerPixel: 32) var destinationCGBuffer = try! vImage_Buffer(width: widthi, height: heighti, bitsPerPixel: 32) try! coreGraphicsToCoreVideo.convert(source: sourceCGBuffer, destination: &intermediateCVBuffer) try! coreVideoToCoreGraphics.convert(source: intermediateCVBuffer, destination: &destinationCGBuffer) let destinationPixels: [UInt8] = arrayFromBuffer(buffer: destinationCGBuffer, channelCount: 4, count: pixels.count) expectEqual(destinationPixels, pixels) expectEqual(coreVideoToCoreGraphics.destinationBuffers(colorSpace: colorSpace), coreGraphicsToCoreVideo.sourceBuffers(colorSpace: colorSpace)) expectEqual(coreVideoToCoreGraphics.sourceBuffers(colorSpace: colorSpace), coreGraphicsToCoreVideo.destinationBuffers(colorSpace: colorSpace)) } /* Disabled due to <rdar://problem/50209312> Accelerate_vImageTests.test("vImage/BufferOrder") { let sourceFormat = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: CGColorSpaceCreateDeviceCMYK(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), renderingIntent: .defaultIntent)! let destinationFormat = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 24, colorSpace: CGColorSpace(name: CGColorSpace.genericLab)!, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), renderingIntent: .defaultIntent)! let converter = try! vImageConverter.make(sourceFormat: sourceFormat, destinationFormat: destinationFormat) let sBuffers = converter.sourceBuffers(colorSpace: sourceFormat.colorSpace.takeRetainedValue()) let dBuffers = converter.destinationBuffers(colorSpace: destinationFormat.colorSpace.takeRetainedValue()) expectEqual(sBuffers, [.coreGraphics]) expectEqual(dBuffers, [.coreGraphics]) } */ Accelerate_vImageTests.test("vImage/AnyToAnyError") { var error = kvImageNoError let format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: CGColorSpaceCreateDeviceCMYK(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), renderingIntent: .defaultIntent)! expectCrashLater() _ = try! vImageConverter.make(sourceFormat: format, destinationFormat: format, flags: .imageExtend) } Accelerate_vImageTests.test("vImage/AnyToAny") { let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in return UInt8.random(in: 0 ..< 255) } let image = makeRGBA8888Image(from: pixels, width: width, height: height)! let sourceFormat = vImage_CGImageFormat(cgImage: image)! let destinationFormat = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: CGColorSpaceCreateDeviceCMYK(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), renderingIntent: .defaultIntent)! let sourceBuffer = try! vImage_Buffer(cgImage: image) var destinationBuffer = try! vImage_Buffer(width: widthi, height: heighti, bitsPerPixel: 32) // New API let converter = try! vImageConverter.make(sourceFormat: sourceFormat, destinationFormat: destinationFormat) try! converter.convert(source: sourceBuffer, destination: &destinationBuffer) let mustOperateOutOfPlace = try! converter.mustOperateOutOfPlace(source: sourceBuffer, destination: destinationBuffer) // Legacy API var legacyDestinationBuffer = try! vImage_Buffer(width: widthi, height: heighti, bitsPerPixel: 32) var legacyConverter: vImageConverter? withUnsafePointer(to: destinationFormat) { dest in withUnsafePointer(to: sourceFormat) { src in legacyConverter = vImageConverter_CreateWithCGImageFormat( src, dest, nil, vImage_Flags(kvImageNoFlags), nil)?.takeRetainedValue() } } _ = withUnsafePointer(to: sourceBuffer) { src in vImageConvert_AnyToAny(legacyConverter!, src, &legacyDestinationBuffer, nil, vImage_Flags(kvImageNoFlags)) } var e = kvImageNoError withUnsafePointer(to: sourceBuffer) { src in withUnsafePointer(to: destinationBuffer) { dest in e = vImageConverter_MustOperateOutOfPlace(legacyConverter!, src, dest, vImage_Flags(kvImageNoFlags)) } } let legacyMustOperateOutOfPlace = e == kvImageOutOfPlaceOperationRequired // Compare results let destinationPixels: [UInt8] = arrayFromBuffer(buffer: destinationBuffer, channelCount: 4, count: pixels.count) let legacyDestinationPixels: [UInt8] = arrayFromBuffer(buffer: legacyDestinationBuffer, channelCount: 4, count: pixels.count) expectTrue(legacyDestinationPixels.elementsEqual(destinationPixels)) expectEqual(converter.sourceBufferCount, 1) expectEqual(converter.destinationBufferCount, 1) expectEqual(legacyMustOperateOutOfPlace, mustOperateOutOfPlace) sourceBuffer.free() destinationBuffer.free() legacyDestinationBuffer.free() } //===----------------------------------------------------------------------===// // // MARK: Buffer // //===----------------------------------------------------------------------===// Accelerate_vImageTests.test("vImage/IllegalSize") { expectCrashLater() let buffer = try! vImage_Buffer(width: -1, height: -1, bitsPerPixel: 32) } Accelerate_vImageTests.test("vImage/IllegalSize") { expectCrashLater() let buffer = try! vImage_Buffer(width: 99999999, height: 99999999, bitsPerPixel: 99999999) } Accelerate_vImageTests.test("vImage/InitWithInvalidImageFormat") { let pixels: [UInt8] = (0 ..< width * height).map { _ in return UInt8.random(in: 0 ..< 255) } let image = makePlanar8Image(from: pixels, width: width, height: height)! let format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGBitmapInfo(rawValue: 0))! var error = kvImageNoError expectCrashLater() let buffer = try! vImage_Buffer(cgImage: image, format: format) } Accelerate_vImageTests.test("vImage/CreateCGImage") { let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in return UInt8.random(in: 0 ..< 255) } let image = makeRGBA8888Image(from: pixels, width: width, height: height)! let buffer = try! vImage_Buffer(cgImage: image) let format = vImage_CGImageFormat(cgImage: image)! let bufferImage = try! buffer.createCGImage(format: format) let imagePixels = imageToPixels(image: image) let bufferImagePixels = imageToPixels(image: bufferImage) expectTrue(imagePixels.elementsEqual(bufferImagePixels)) buffer.free() } Accelerate_vImageTests.test("vImage/CopyBadWidth") { var source = try! vImage_Buffer(width: 10, height: 100, bitsPerPixel: 32) var destination = try! vImage_Buffer(width: 20, height: 20, bitsPerPixel: 32) expectCrashLater() try! source.copy(destinationBuffer: &destination, pixelSize: 4) } Accelerate_vImageTests.test("vImage/CopyBadHeight") { var source = try! vImage_Buffer(width: 100, height: 10, bitsPerPixel: 32) var destination = try! vImage_Buffer(width: 20, height: 20, bitsPerPixel: 32) expectCrashLater() try! source.copy(destinationBuffer: &destination, pixelSize: 4) } Accelerate_vImageTests.test("vImage/Copy") { let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in return UInt8.random(in: 0 ..< 255) } let image = makeRGBA8888Image(from: pixels, width: width, height: height)! let source = try! vImage_Buffer(cgImage: image) var destination = try! vImage_Buffer(width: widthi, height: heighti, bitsPerPixel: 32) try! source.copy(destinationBuffer: &destination, pixelSize: 4) let sourcePixels: [UInt8] = arrayFromBuffer(buffer: source, channelCount: 4, count: pixels.count) let destinationPixels: [UInt8] = arrayFromBuffer(buffer: destination, channelCount: 4, count: pixels.count) expectTrue(sourcePixels.elementsEqual(destinationPixels)) source.free() destination.free() } Accelerate_vImageTests.test("vImage/InitializeWithFormat") { let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in return UInt8.random(in: 0 ..< 255) } let image = makeRGBA8888Image(from: pixels, width: width, height: height)! let format = vImage_CGImageFormat(cgImage: image)! let buffer = try! vImage_Buffer(cgImage: image, format: format) let bufferPixels: [UInt8] = arrayFromBuffer(buffer: buffer, channelCount: 4, count: pixels.count) expectTrue(bufferPixels.elementsEqual(pixels)) expectEqual(buffer.rowBytes, Int(width) * 4) expectEqual(buffer.width, width) expectEqual(buffer.height, height) buffer.free() } Accelerate_vImageTests.test("vImage/Alignment") { // New API var alignment = try! vImage_Buffer.preferredAlignmentAndRowBytes(width: widthi, height: heighti, bitsPerPixel: 32) // Legacy API var legacyBuffer = vImage_Buffer() let legacyAlignment = vImageBuffer_Init(&legacyBuffer, height, width, 32, vImage_Flags(kvImageNoAllocate)) expectEqual(alignment.alignment, legacyAlignment) expectEqual(alignment.rowBytes, legacyBuffer.rowBytes) legacyBuffer.free() } Accelerate_vImageTests.test("vImage/CreateBufferFromCGImage") { let pixels: [UInt8] = (0 ..< width * height * 4).map { _ in return UInt8.random(in: 0 ..< 255) } let image = makeRGBA8888Image(from: pixels, width: width, height: height)! // New API let buffer = try! vImage_Buffer(cgImage: image) // Legacy API let legacyBuffer: vImage_Buffer = { var format = vImage_CGImageFormat(cgImage: image)! var buffer = vImage_Buffer() vImageBuffer_InitWithCGImage(&buffer, &format, nil, image, vImage_Flags(kvImageNoFlags)) return buffer }() let bufferPixels: [UInt8] = arrayFromBuffer(buffer: buffer, channelCount: 4, count: pixels.count) let legacyBufferPixels: [UInt8] = arrayFromBuffer(buffer: legacyBuffer, channelCount: 4, count: pixels.count) expectTrue(bufferPixels.elementsEqual(legacyBufferPixels)) expectEqual(buffer.width, legacyBuffer.width) expectEqual(buffer.height, legacyBuffer.height) expectEqual(buffer.rowBytes, legacyBuffer.rowBytes) expectEqual(buffer.size, CGSize(width: Int(width), height: Int(height))) buffer.free() free(legacyBuffer.data) } //===----------------------------------------------------------------------===// // // MARK: CVImageFormat // //===----------------------------------------------------------------------===// Accelerate_vImageTests.test("vImage/MakeFromPixelBuffer") { let pixelBuffer = makePixelBuffer(pixelFormat: kCVPixelFormatType_420YpCbCr8Planar)! let format = vImageCVImageFormat.make(buffer: pixelBuffer)! expectEqual(format.channels, [vImage.BufferType.luminance, vImage.BufferType.Cb, vImage.BufferType.Cr]) } Accelerate_vImageTests.test("vImage/MakeFormat4444YpCbCrA8") { let format = vImageCVImageFormat.make(format: .format4444YpCbCrA8, matrix: kvImage_ARGBToYpCbCrMatrix_ITU_R_709_2.pointee, chromaSiting: .center, colorSpace: CGColorSpaceCreateDeviceRGB(), alphaIsOpaqueHint: false)! // test alphaIsOpaqueHint expectEqual(format.alphaIsOpaqueHint, false) format.alphaIsOpaqueHint = true expectEqual(format.alphaIsOpaqueHint, true) // test colorSpace expectEqual(String(format.colorSpace!.name!), "kCGColorSpaceDeviceRGB") format.colorSpace = CGColorSpace(name: CGColorSpace.extendedLinearSRGB)! expectEqual(String(format.colorSpace!.name!), "kCGColorSpaceExtendedLinearSRGB") // test channel names let channels = format.channels expectEqual(channels, [vImage.BufferType.Cb, vImage.BufferType.luminance, vImage.BufferType.Cr, vImage.BufferType.alpha]) let description = format.channelDescription(bufferType: channels.first!) expectEqual(description?.min, 0) expectEqual(description?.max, 255) expectEqual(description?.full, 240) expectEqual(description?.zero, 128) } Accelerate_vImageTests.test("vImage/MakeFormat420YpCbCr8Planar") { let format = vImageCVImageFormat.make(format: .format420YpCbCr8Planar, matrix: kvImage_ARGBToYpCbCrMatrix_ITU_R_709_2.pointee, chromaSiting: .center, colorSpace: CGColorSpaceCreateDeviceRGB(), alphaIsOpaqueHint: false)! // test chromaSiting expectEqual(format.chromaSiting, vImageCVImageFormat.ChromaSiting.center) format.chromaSiting = .dv420 expectEqual(format.chromaSiting, vImageCVImageFormat.ChromaSiting.dv420) // test formatCode expectEqual(format.formatCode, kCVPixelFormatType_420YpCbCr8Planar) // test channelCount expectEqual(format.channelCount, 3) } //===----------------------------------------------------------------------===// // // MARK: CGImageFormat // //===----------------------------------------------------------------------===// Accelerate_vImageTests.test("vImage/CGImageFormatIllegalValues") { let formatOne = vImage_CGImageFormat(bitsPerComponent: -1, bitsPerPixel: 32, colorSpace: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)) let formatTwo = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: -1, colorSpace: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)) expectTrue(formatOne == nil) expectTrue(formatTwo == nil) } Accelerate_vImageTests.test("vImage/CGImageFormatFromCGImage") { let pixels: [UInt8] = (0 ..< width * height).map { _ in return UInt8.random(in: 0 ..< 255) } let image = makePlanar8Image(from: pixels, width: width, height: height)! var format = vImage_CGImageFormat(cgImage: image)! var legacyFormat = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 8, colorSpace: Unmanaged.passRetained(CGColorSpaceCreateDeviceGray()), bitmapInfo: CGBitmapInfo(rawValue: 0), version: 0, decode: nil, renderingIntent: .defaultIntent) expectTrue(vImageCGImageFormat_IsEqual(&format, &legacyFormat)) } Accelerate_vImageTests.test("vImage/CGImageFormatLightweightInit") { let colorspace = CGColorSpaceCreateDeviceRGB() let renderingIntent = CGColorRenderingIntent.defaultIntent let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue) var format = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: colorspace, bitmapInfo: bitmapInfo)! var legacyFormat = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: Unmanaged.passRetained(colorspace), bitmapInfo: bitmapInfo, version: 0, decode: nil, renderingIntent: renderingIntent) expectTrue(vImageCGImageFormat_IsEqual(&format, &legacyFormat)) expectTrue(format.componentCount == 4) } //===----------------------------------------------------------------------===// // // MARK: Helper Functions // //===----------------------------------------------------------------------===// func makePixelBuffer(pixelFormat: OSType) -> CVPixelBuffer? { var pixelBuffer: CVPixelBuffer? = nil CVPixelBufferCreate(kCFAllocatorDefault, 1, 1, pixelFormat, [:] as CFDictionary?, &pixelBuffer) return pixelBuffer } func arrayFromBuffer<T>(buffer: vImage_Buffer, channelCount: Int, count: Int) -> Array<T> { if (buffer.rowBytes == Int(buffer.width) * MemoryLayout<T>.stride * channelCount) { let ptr = buffer.data.bindMemory(to: T.self, capacity: count) let buf = UnsafeBufferPointer(start: ptr, count: count) return Array(buf) } else { var returnArray = [T]() let perRowCount = Int(buffer.width) * MemoryLayout<T>.stride * channelCount var ptr = buffer.data.bindMemory(to: T.self, capacity: perRowCount) for _ in 0 ..< buffer.height { let buf = UnsafeBufferPointer(start: ptr, count: perRowCount) returnArray.append(contentsOf: Array(buf)) ptr = ptr.advanced(by: buffer.rowBytes) } return returnArray } } func imageToPixels(image: CGImage) -> [UInt8] { let pixelCount = image.width * image.height let pixelData = image.dataProvider?.data let pixels: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) let buf = UnsafeBufferPointer(start: pixels, count: pixelCount) return Array(buf) } func makePlanar8Image(from pixels: [UInt8], width: UInt, height: UInt) -> CGImage? { if let outputData = CFDataCreate(nil, pixels, pixels.count), let cgDataProvider = CGDataProvider(data: outputData) { return CGImage(width: Int(width), height: Int(height), bitsPerComponent: 8, bitsPerPixel: 8, bytesPerRow: Int(width), space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGBitmapInfo(rawValue: 0), provider: cgDataProvider, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent) } return nil } func makeRGBA8888Image(from pixels: [UInt8], width: UInt, height: UInt) -> CGImage? { if let outputData = CFDataCreate(nil, pixels, pixels.count), let cgDataProvider = CGDataProvider(data: outputData) { return CGImage(width: Int(width), height: Int(height), bitsPerComponent: 8, bitsPerPixel: 8 * 4, bytesPerRow: Int(width) * 4, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue), provider: cgDataProvider, decode: nil, shouldInterpolate: false, intent: CGColorRenderingIntent.defaultIntent) } return nil } } runAllTests()
apache-2.0
0430a34698271af6288c2a75d9c852ca
42.235736
126
0.470498
6.298119
false
true
false
false
apple/swift-corelibs-foundation
Sources/Foundation/JSONEncoder.swift
1
49624
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_implementationOnly import CoreFoundation /// A marker protocol used to determine whether a value is a `String`-keyed `Dictionary` /// containing `Encodable` values (in which case it should be exempt from key conversion strategies). /// fileprivate protocol _JSONStringDictionaryEncodableMarker { } extension Dictionary: _JSONStringDictionaryEncodableMarker where Key == String, Value: Encodable { } //===----------------------------------------------------------------------===// // JSON Encoder //===----------------------------------------------------------------------===// /// `JSONEncoder` facilitates the encoding of `Encodable` values into JSON. open class JSONEncoder { // MARK: Options /// The formatting of the output JSON data. public struct OutputFormatting: OptionSet { /// The format's default value. public let rawValue: UInt /// Creates an OutputFormatting value with the given raw value. public init(rawValue: UInt) { self.rawValue = rawValue } /// Produce human-readable JSON with indented output. public static let prettyPrinted = OutputFormatting(rawValue: 1 << 0) /// Produce JSON with dictionary keys sorted in lexicographic order. @available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) public static let sortedKeys = OutputFormatting(rawValue: 1 << 1) /// By default slashes get escaped ("/" → "\/", "http://apple.com/" → "http:\/\/apple.com\/") /// for security reasons, allowing outputted JSON to be safely embedded within HTML/XML. /// In contexts where this escaping is unnecessary, the JSON is known to not be embedded, /// or is intended only for display, this option avoids this escaping. public static let withoutEscapingSlashes = OutputFormatting(rawValue: 1 << 3) } /// The strategy to use for encoding `Date` values. public enum DateEncodingStrategy { /// Defer to `Date` for choosing an encoding. This is the default strategy. case deferredToDate /// Encode the `Date` as a UNIX timestamp (as a JSON number). case secondsSince1970 /// Encode the `Date` as UNIX millisecond timestamp (as a JSON number). case millisecondsSince1970 /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) case iso8601 /// Encode the `Date` as a string formatted by the given formatter. case formatted(DateFormatter) /// Encode the `Date` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Date, Encoder) throws -> Void) } /// The strategy to use for encoding `Data` values. public enum DataEncodingStrategy { /// Defer to `Data` for choosing an encoding. case deferredToData /// Encoded the `Data` as a Base64-encoded string. This is the default strategy. case base64 /// Encode the `Data` as a custom value encoded by the given closure. /// /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. case custom((Data, Encoder) throws -> Void) } /// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). public enum NonConformingFloatEncodingStrategy { /// Throw upon encountering non-conforming values. This is the default strategy. case `throw` /// Encode the values using the given representation strings. case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String) } /// The strategy to use for automatically changing the value of keys before encoding. public enum KeyEncodingStrategy { /// Use the keys specified by each type. This is the default strategy. case useDefaultKeys /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key to JSON payload. /// /// Capital characters are determined by testing membership in `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters` (Unicode General Categories Lu and Lt). /// The conversion to lower case uses `Locale.system`, also known as the ICU "root" locale. This means the result is consistent regardless of the current user's locale and language preferences. /// /// Converting from camel case to snake case: /// 1. Splits words at the boundary of lower-case to upper-case /// 2. Inserts `_` between words /// 3. Lowercases the entire string /// 4. Preserves starting and ending `_`. /// /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`. /// /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted. case convertToSnakeCase /// Provide a custom conversion to the key in the encoded JSON from the keys specified by the encoded types. /// The full path to the current encoding position is provided for context (in case you need to locate this key within the payload). The returned key is used in place of the last component in the coding path before encoding. /// If the result of the conversion is a duplicate key, then only one value will be present in the result. case custom((_ codingPath: [CodingKey]) -> CodingKey) fileprivate static func _convertToSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } var words: [Range<String.Index>] = [] // The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase // // myProperty -> my_property // myURLProperty -> my_url_property // // We assume, per Swift naming conventions, that the first character of the key is lowercase. var wordStart = stringKey.startIndex var searchRange = stringKey.index(after: wordStart)..<stringKey.endIndex // Find next uppercase character while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) { let untilUpperCase = wordStart..<upperCaseRange.lowerBound words.append(untilUpperCase) // Find next lowercase character searchRange = upperCaseRange.lowerBound..<searchRange.upperBound guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else { // There are no more lower case letters. Just end here. wordStart = searchRange.lowerBound break } // Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound) if lowerCaseRange.lowerBound == nextCharacterAfterCapital { // The next character after capital is a lower case character and therefore not a word boundary. // Continue searching for the next upper case for the boundary. wordStart = upperCaseRange.lowerBound } else { // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before the lower case character. let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) words.append(upperCaseRange.lowerBound..<beforeLowerIndex) // Next word starts at the capital before the lowercase we just found wordStart = beforeLowerIndex } searchRange = lowerCaseRange.upperBound..<searchRange.upperBound } words.append(wordStart..<searchRange.upperBound) let result = words.map({ (range) in return stringKey[range].lowercased() }).joined(separator: "_") return result } } /// The output format to produce. Defaults to `[]`. open var outputFormatting: OutputFormatting = [] /// The strategy to use in encoding dates. Defaults to `.deferredToDate`. open var dateEncodingStrategy: DateEncodingStrategy = .deferredToDate /// The strategy to use in encoding binary data. Defaults to `.base64`. open var dataEncodingStrategy: DataEncodingStrategy = .base64 /// The strategy to use in encoding non-conforming numbers. Defaults to `.throw`. open var nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy = .throw /// The strategy to use for encoding keys. Defaults to `.useDefaultKeys`. open var keyEncodingStrategy: KeyEncodingStrategy = .useDefaultKeys /// Contextual user-provided information for use during encoding. open var userInfo: [CodingUserInfoKey: Any] = [:] /// Options set on the top-level encoder to pass down the encoding hierarchy. fileprivate struct _Options { let dateEncodingStrategy: DateEncodingStrategy let dataEncodingStrategy: DataEncodingStrategy let nonConformingFloatEncodingStrategy: NonConformingFloatEncodingStrategy let keyEncodingStrategy: KeyEncodingStrategy let userInfo: [CodingUserInfoKey: Any] } /// The options set on the top-level encoder. fileprivate var options: _Options { return _Options(dateEncodingStrategy: dateEncodingStrategy, dataEncodingStrategy: dataEncodingStrategy, nonConformingFloatEncodingStrategy: nonConformingFloatEncodingStrategy, keyEncodingStrategy: keyEncodingStrategy, userInfo: userInfo) } // MARK: - Constructing a JSON Encoder /// Initializes `self` with default strategies. public init() {} // MARK: - Encoding Values /// Encodes the given top-level value and returns its JSON representation. /// /// - parameter value: The value to encode. /// - returns: A new `Data` value containing the encoded JSON data. /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`. /// - throws: An error if any value throws an error during encoding. open func encode<T: Encodable>(_ value: T) throws -> Data { let value: JSONValue = try encodeAsJSONValue(value) let writer = JSONValue.Writer(options: self.outputFormatting) let bytes = writer.writeValue(value) return Data(bytes) } func encodeAsJSONValue<T: Encodable>(_ value: T) throws -> JSONValue { let encoder = JSONEncoderImpl(options: self.options, codingPath: []) guard let topLevel = try encoder.wrapEncodable(value, for: nil) else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "Top-level \(T.self) did not encode any values.")) } return topLevel } } // MARK: - _JSONEncoder private enum JSONFuture { case value(JSONValue) case encoder(JSONEncoderImpl) case nestedArray(RefArray) case nestedObject(RefObject) class RefArray { private(set) var array: [JSONFuture] = [] init() { self.array.reserveCapacity(10) } @inline(__always) func append(_ element: JSONValue) { self.array.append(.value(element)) } @inline(__always) func append(_ encoder: JSONEncoderImpl) { self.array.append(.encoder(encoder)) } @inline(__always) func appendArray() -> RefArray { let array = RefArray() self.array.append(.nestedArray(array)) return array } @inline(__always) func appendObject() -> RefObject { let object = RefObject() self.array.append(.nestedObject(object)) return object } var values: [JSONValue] { self.array.map { (future) -> JSONValue in switch future { case .value(let value): return value case .nestedArray(let array): return .array(array.values) case .nestedObject(let object): return .object(object.values) case .encoder(let encoder): return encoder.value ?? .object([:]) } } } } class RefObject { private(set) var dict: [String: JSONFuture] = [:] init() { self.dict.reserveCapacity(20) } @inline(__always) func set(_ value: JSONValue, for key: String) { self.dict[key] = .value(value) } @inline(__always) func setArray(for key: String) -> RefArray { switch self.dict[key] { case .encoder: preconditionFailure("For key \"\(key)\" an encoder has already been created.") case .nestedObject: preconditionFailure("For key \"\(key)\" a keyed container has already been created.") case .nestedArray(let array): return array case .none, .value: let array = RefArray() dict[key] = .nestedArray(array) return array } } @inline(__always) func setObject(for key: String) -> RefObject { switch self.dict[key] { case .encoder: preconditionFailure("For key \"\(key)\" an encoder has already been created.") case .nestedObject(let object): return object case .nestedArray: preconditionFailure("For key \"\(key)\" a unkeyed container has already been created.") case .none, .value: let object = RefObject() dict[key] = .nestedObject(object) return object } } @inline(__always) func set(_ encoder: JSONEncoderImpl, for key: String) { switch self.dict[key] { case .encoder: preconditionFailure("For key \"\(key)\" an encoder has already been created.") case .nestedObject: preconditionFailure("For key \"\(key)\" a keyed container has already been created.") case .nestedArray: preconditionFailure("For key \"\(key)\" a unkeyed container has already been created.") case .none, .value: dict[key] = .encoder(encoder) } } var values: [String: JSONValue] { self.dict.mapValues { (future) -> JSONValue in switch future { case .value(let value): return value case .nestedArray(let array): return .array(array.values) case .nestedObject(let object): return .object(object.values) case .encoder(let encoder): return encoder.value ?? .object([:]) } } } } } private class JSONEncoderImpl { let options: JSONEncoder._Options let codingPath: [CodingKey] var userInfo: [CodingUserInfoKey: Any] { options.userInfo } var singleValue: JSONValue? var array: JSONFuture.RefArray? var object: JSONFuture.RefObject? var value: JSONValue? { if let object = self.object { return .object(object.values) } if let array = self.array { return .array(array.values) } return self.singleValue } init(options: JSONEncoder._Options, codingPath: [CodingKey]) { self.options = options self.codingPath = codingPath } } extension JSONEncoderImpl: Encoder { func container<Key>(keyedBy _: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey { if let _ = object { let container = JSONKeyedEncodingContainer<Key>(impl: self, codingPath: codingPath) return KeyedEncodingContainer(container) } guard self.singleValue == nil, self.array == nil else { preconditionFailure() } self.object = JSONFuture.RefObject() let container = JSONKeyedEncodingContainer<Key>(impl: self, codingPath: codingPath) return KeyedEncodingContainer(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { if let _ = array { return JSONUnkeyedEncodingContainer(impl: self, codingPath: self.codingPath) } guard self.singleValue == nil, self.object == nil else { preconditionFailure() } self.array = JSONFuture.RefArray() return JSONUnkeyedEncodingContainer(impl: self, codingPath: self.codingPath) } func singleValueContainer() -> SingleValueEncodingContainer { guard self.object == nil, self.array == nil else { preconditionFailure() } return JSONSingleValueEncodingContainer(impl: self, codingPath: self.codingPath) } } // this is a private protocol to implement convenience methods directly on the EncodingContainers extension JSONEncoderImpl: _SpecialTreatmentEncoder { var impl: JSONEncoderImpl { return self } // untyped escape hatch. needed for `wrapObject` func wrapUntyped(_ encodable: Encodable) throws -> JSONValue { switch encodable { case let date as Date: return try self.wrapDate(date, for: nil) case let data as Data: return try self.wrapData(data, for: nil) case let url as URL: return .string(url.absoluteString) case let decimal as Decimal: return .number(decimal.description) case let object as [String: Encodable]: // this emits a warning, but it works perfectly return try self.wrapObject(object, for: nil) default: try encodable.encode(to: self) return self.value ?? .object([:]) } } } private protocol _SpecialTreatmentEncoder { var codingPath: [CodingKey] { get } var options: JSONEncoder._Options { get } var impl: JSONEncoderImpl { get } } extension _SpecialTreatmentEncoder { @inline(__always) fileprivate func wrapFloat<F: FloatingPoint & CustomStringConvertible>(_ float: F, for additionalKey: CodingKey?) throws -> JSONValue { guard !float.isNaN, !float.isInfinite else { if case .convertToString(let posInfString, let negInfString, let nanString) = self.options.nonConformingFloatEncodingStrategy { switch float { case F.infinity: return .string(posInfString) case -F.infinity: return .string(negInfString) default: // must be nan in this case return .string(nanString) } } var path = self.codingPath if let additionalKey = additionalKey { path.append(additionalKey) } throw EncodingError.invalidValue(float, .init( codingPath: path, debugDescription: "Unable to encode \(F.self).\(float) directly in JSON." )) } var string = float.description if string.hasSuffix(".0") { string.removeLast(2) } return .number(string) } fileprivate func wrapEncodable<E: Encodable>(_ encodable: E, for additionalKey: CodingKey?) throws -> JSONValue? { switch encodable { case let date as Date: return try self.wrapDate(date, for: additionalKey) case let data as Data: return try self.wrapData(data, for: additionalKey) case let url as URL: return .string(url.absoluteString) case let decimal as Decimal: return .number(decimal.description) case let object as _JSONStringDictionaryEncodableMarker: return try self.wrapObject(object as! [String: Encodable], for: additionalKey) default: let encoder = self.getEncoder(for: additionalKey) try encodable.encode(to: encoder) return encoder.value } } func wrapDate(_ date: Date, for additionalKey: CodingKey?) throws -> JSONValue { switch self.options.dateEncodingStrategy { case .deferredToDate: let encoder = self.getEncoder(for: additionalKey) try date.encode(to: encoder) return encoder.value ?? .null case .secondsSince1970: return .number(date.timeIntervalSince1970.description) case .millisecondsSince1970: return .number((date.timeIntervalSince1970 * 1000).description) case .iso8601: if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { return .string(_iso8601Formatter.string(from: date)) } else { fatalError("ISO8601DateFormatter is unavailable on this platform.") } case .formatted(let formatter): return .string(formatter.string(from: date)) case .custom(let closure): let encoder = self.getEncoder(for: additionalKey) try closure(date, encoder) // The closure didn't encode anything. Return the default keyed container. return encoder.value ?? .object([:]) } } func wrapData(_ data: Data, for additionalKey: CodingKey?) throws -> JSONValue { switch self.options.dataEncodingStrategy { case .deferredToData: let encoder = self.getEncoder(for: additionalKey) try data.encode(to: encoder) return encoder.value ?? .null case .base64: let base64 = data.base64EncodedString() return .string(base64) case .custom(let closure): let encoder = self.getEncoder(for: additionalKey) try closure(data, encoder) // The closure didn't encode anything. Return the default keyed container. return encoder.value ?? .object([:]) } } func wrapObject(_ object: [String: Encodable], for additionalKey: CodingKey?) throws -> JSONValue { var baseCodingPath = self.codingPath if let additionalKey = additionalKey { baseCodingPath.append(additionalKey) } var result = [String: JSONValue]() result.reserveCapacity(object.count) try object.forEach { (key, value) in var elemCodingPath = baseCodingPath elemCodingPath.append(_JSONKey(stringValue: key, intValue: nil)) let encoder = JSONEncoderImpl(options: self.options, codingPath: elemCodingPath) result[key] = try encoder.wrapUntyped(value) } return .object(result) } fileprivate func getEncoder(for additionalKey: CodingKey?) -> JSONEncoderImpl { if let additionalKey = additionalKey { var newCodingPath = self.codingPath newCodingPath.append(additionalKey) return JSONEncoderImpl(options: self.options, codingPath: newCodingPath) } return self.impl } } private struct JSONKeyedEncodingContainer<K: CodingKey>: KeyedEncodingContainerProtocol, _SpecialTreatmentEncoder { typealias Key = K let impl: JSONEncoderImpl let object: JSONFuture.RefObject let codingPath: [CodingKey] private var firstValueWritten: Bool = false fileprivate var options: JSONEncoder._Options { return self.impl.options } init(impl: JSONEncoderImpl, codingPath: [CodingKey]) { self.impl = impl self.object = impl.object! self.codingPath = codingPath } // used for nested containers init(impl: JSONEncoderImpl, object: JSONFuture.RefObject, codingPath: [CodingKey]) { self.impl = impl self.object = object self.codingPath = codingPath } private func _converted(_ key: Key) -> CodingKey { switch self.options.keyEncodingStrategy { case .useDefaultKeys: return key case .convertToSnakeCase: let newKeyString = JSONEncoder.KeyEncodingStrategy._convertToSnakeCase(key.stringValue) return _JSONKey(stringValue: newKeyString, intValue: key.intValue) case .custom(let converter): return converter(codingPath + [key]) } } mutating func encodeNil(forKey key: Self.Key) throws { self.object.set(.null, for: self._converted(key).stringValue) } mutating func encode(_ value: Bool, forKey key: Self.Key) throws { self.object.set(.bool(value), for: self._converted(key).stringValue) } mutating func encode(_ value: String, forKey key: Self.Key) throws { self.object.set(.string(value), for: self._converted(key).stringValue) } mutating func encode(_ value: Double, forKey key: Self.Key) throws { try encodeFloatingPoint(value, key: self._converted(key)) } mutating func encode(_ value: Float, forKey key: Self.Key) throws { try encodeFloatingPoint(value, key: self._converted(key)) } mutating func encode(_ value: Int, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode(_ value: Int8, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode(_ value: Int16, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode(_ value: Int32, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode(_ value: Int64, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode(_ value: UInt, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode(_ value: UInt8, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode(_ value: UInt16, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode(_ value: UInt32, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode(_ value: UInt64, forKey key: Self.Key) throws { try encodeFixedWidthInteger(value, key: self._converted(key)) } mutating func encode<T>(_ value: T, forKey key: Self.Key) throws where T: Encodable { let convertedKey = self._converted(key) let encoded = try self.wrapEncodable(value, for: convertedKey) self.object.set(encoded ?? .object([:]), for: convertedKey.stringValue) } mutating func nestedContainer<NestedKey>(keyedBy _: NestedKey.Type, forKey key: Self.Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { let convertedKey = self._converted(key) let newPath = self.codingPath + [convertedKey] let object = self.object.setObject(for: convertedKey.stringValue) let nestedContainer = JSONKeyedEncodingContainer<NestedKey>(impl: impl, object: object, codingPath: newPath) return KeyedEncodingContainer(nestedContainer) } mutating func nestedUnkeyedContainer(forKey key: Self.Key) -> UnkeyedEncodingContainer { let convertedKey = self._converted(key) let newPath = self.codingPath + [convertedKey] let array = self.object.setArray(for: convertedKey.stringValue) let nestedContainer = JSONUnkeyedEncodingContainer(impl: impl, array: array, codingPath: newPath) return nestedContainer } mutating func superEncoder() -> Encoder { let newEncoder = self.getEncoder(for: _JSONKey.super) self.object.set(newEncoder, for: _JSONKey.super.stringValue) return newEncoder } mutating func superEncoder(forKey key: Self.Key) -> Encoder { let convertedKey = self._converted(key) let newEncoder = self.getEncoder(for: convertedKey) self.object.set(newEncoder, for: convertedKey.stringValue) return newEncoder } } extension JSONKeyedEncodingContainer { @inline(__always) private mutating func encodeFloatingPoint<F: FloatingPoint & CustomStringConvertible>(_ float: F, key: CodingKey) throws { let value = try self.wrapFloat(float, for: key) self.object.set(value, for: key.stringValue) } @inline(__always) private mutating func encodeFixedWidthInteger<N: FixedWidthInteger>(_ value: N, key: CodingKey) throws { self.object.set(.number(value.description), for: key.stringValue) } } private struct JSONUnkeyedEncodingContainer: UnkeyedEncodingContainer, _SpecialTreatmentEncoder { let impl: JSONEncoderImpl let array: JSONFuture.RefArray let codingPath: [CodingKey] var count: Int { self.array.array.count } private var firstValueWritten: Bool = false fileprivate var options: JSONEncoder._Options { return self.impl.options } init(impl: JSONEncoderImpl, codingPath: [CodingKey]) { self.impl = impl self.array = impl.array! self.codingPath = codingPath } // used for nested containers init(impl: JSONEncoderImpl, array: JSONFuture.RefArray, codingPath: [CodingKey]) { self.impl = impl self.array = array self.codingPath = codingPath } mutating func encodeNil() throws { self.array.append(.null) } mutating func encode(_ value: Bool) throws { self.array.append(.bool(value)) } mutating func encode(_ value: String) throws { self.array.append(.string(value)) } mutating func encode(_ value: Double) throws { try encodeFloatingPoint(value) } mutating func encode(_ value: Float) throws { try encodeFloatingPoint(value) } mutating func encode(_ value: Int) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: Int8) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: Int16) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: Int32) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: Int64) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt8) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt16) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt32) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt64) throws { try encodeFixedWidthInteger(value) } mutating func encode<T>(_ value: T) throws where T: Encodable { let key = _JSONKey(stringValue: "Index \(self.count)", intValue: self.count) let encoded = try self.wrapEncodable(value, for: key) self.array.append(encoded ?? .object([:])) } mutating func nestedContainer<NestedKey>(keyedBy _: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { let newPath = self.codingPath + [_JSONKey(index: self.count)] let object = self.array.appendObject() let nestedContainer = JSONKeyedEncodingContainer<NestedKey>(impl: impl, object: object, codingPath: newPath) return KeyedEncodingContainer(nestedContainer) } mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { let newPath = self.codingPath + [_JSONKey(index: self.count)] let array = self.array.appendArray() let nestedContainer = JSONUnkeyedEncodingContainer(impl: impl, array: array, codingPath: newPath) return nestedContainer } mutating func superEncoder() -> Encoder { let encoder = self.getEncoder(for: _JSONKey(index: self.count)) self.array.append(encoder) return encoder } } extension JSONUnkeyedEncodingContainer { @inline(__always) private mutating func encodeFixedWidthInteger<N: FixedWidthInteger>(_ value: N) throws { self.array.append(.number(value.description)) } @inline(__always) private mutating func encodeFloatingPoint<F: FloatingPoint & CustomStringConvertible>(_ float: F) throws { let value = try self.wrapFloat(float, for: _JSONKey(index: self.count)) self.array.append(value) } } private struct JSONSingleValueEncodingContainer: SingleValueEncodingContainer, _SpecialTreatmentEncoder { let impl: JSONEncoderImpl let codingPath: [CodingKey] private var firstValueWritten: Bool = false fileprivate var options: JSONEncoder._Options { return self.impl.options } init(impl: JSONEncoderImpl, codingPath: [CodingKey]) { self.impl = impl self.codingPath = codingPath } mutating func encodeNil() throws { self.preconditionCanEncodeNewValue() self.impl.singleValue = .null } mutating func encode(_ value: Bool) throws { self.preconditionCanEncodeNewValue() self.impl.singleValue = .bool(value) } mutating func encode(_ value: Int) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: Int8) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: Int16) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: Int32) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: Int64) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt8) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt16) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt32) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: UInt64) throws { try encodeFixedWidthInteger(value) } mutating func encode(_ value: Float) throws { try encodeFloatingPoint(value) } mutating func encode(_ value: Double) throws { try encodeFloatingPoint(value) } mutating func encode(_ value: String) throws { self.preconditionCanEncodeNewValue() self.impl.singleValue = .string(value) } mutating func encode<T: Encodable>(_ value: T) throws { self.preconditionCanEncodeNewValue() self.impl.singleValue = try self.wrapEncodable(value, for: nil) } func preconditionCanEncodeNewValue() { precondition(self.impl.singleValue == nil, "Attempt to encode value through single value container when previously value already encoded.") } } extension JSONSingleValueEncodingContainer { @inline(__always) private mutating func encodeFixedWidthInteger<N: FixedWidthInteger>(_ value: N) throws { self.preconditionCanEncodeNewValue() self.impl.singleValue = .number(value.description) } @inline(__always) private mutating func encodeFloatingPoint<F: FloatingPoint & CustomStringConvertible>(_ float: F) throws { self.preconditionCanEncodeNewValue() let value = try self.wrapFloat(float, for: nil) self.impl.singleValue = value } } extension JSONValue { fileprivate struct Writer { let options: JSONEncoder.OutputFormatting init(options: JSONEncoder.OutputFormatting) { self.options = options } func writeValue(_ value: JSONValue) -> [UInt8] { var bytes = [UInt8]() if self.options.contains(.prettyPrinted) { self.writeValuePretty(value, into: &bytes) } else { self.writeValue(value, into: &bytes) } return bytes } private func writeValue(_ value: JSONValue, into bytes: inout [UInt8]) { switch value { case .null: bytes.append(contentsOf: [UInt8]._null) case .bool(true): bytes.append(contentsOf: [UInt8]._true) case .bool(false): bytes.append(contentsOf: [UInt8]._false) case .string(let string): self.encodeString(string, to: &bytes) case .number(let string): bytes.append(contentsOf: string.utf8) case .array(let array): var iterator = array.makeIterator() bytes.append(._openbracket) // we don't like branching, this is why we have this extra if let first = iterator.next() { self.writeValue(first, into: &bytes) } while let item = iterator.next() { bytes.append(._comma) self.writeValue(item, into:&bytes) } bytes.append(._closebracket) case .object(let dict): if #available(OSX 10.13, *), options.contains(.sortedKeys) { let sorted = dict.sorted { $0.key < $1.key } self.writeObject(sorted, into: &bytes) } else { self.writeObject(dict, into: &bytes) } } } private func writeObject<Object: Sequence>(_ object: Object, into bytes: inout [UInt8], depth: Int = 0) where Object.Element == (key: String, value: JSONValue) { var iterator = object.makeIterator() bytes.append(._openbrace) if let (key, value) = iterator.next() { self.encodeString(key, to: &bytes) bytes.append(._colon) self.writeValue(value, into: &bytes) } while let (key, value) = iterator.next() { bytes.append(._comma) // key self.encodeString(key, to: &bytes) bytes.append(._colon) self.writeValue(value, into: &bytes) } bytes.append(._closebrace) } private func addInset(to bytes: inout [UInt8], depth: Int) { bytes.append(contentsOf: [UInt8](repeating: ._space, count: depth * 2)) } private func writeValuePretty(_ value: JSONValue, into bytes: inout [UInt8], depth: Int = 0) { switch value { case .null: bytes.append(contentsOf: [UInt8]._null) case .bool(true): bytes.append(contentsOf: [UInt8]._true) case .bool(false): bytes.append(contentsOf: [UInt8]._false) case .string(let string): self.encodeString(string, to: &bytes) case .number(let string): bytes.append(contentsOf: string.utf8) case .array(let array): var iterator = array.makeIterator() bytes.append(contentsOf: [._openbracket, ._newline]) if let first = iterator.next() { self.addInset(to: &bytes, depth: depth + 1) self.writeValuePretty(first, into: &bytes, depth: depth + 1) } while let item = iterator.next() { bytes.append(contentsOf: [._comma, ._newline]) self.addInset(to: &bytes, depth: depth + 1) self.writeValuePretty(item, into: &bytes, depth: depth + 1) } bytes.append(._newline) self.addInset(to: &bytes, depth: depth) bytes.append(._closebracket) case .object(let dict): if #available(OSX 10.13, *), options.contains(.sortedKeys) { let sorted = dict.sorted { $0.key < $1.key } self.writePrettyObject(sorted, into: &bytes, depth: depth) } else { self.writePrettyObject(dict, into: &bytes, depth: depth) } } } private func writePrettyObject<Object: Sequence>(_ object: Object, into bytes: inout [UInt8], depth: Int = 0) where Object.Element == (key: String, value: JSONValue) { var iterator = object.makeIterator() bytes.append(contentsOf: [._openbrace, ._newline]) if let (key, value) = iterator.next() { self.addInset(to: &bytes, depth: depth + 1) self.encodeString(key, to: &bytes) bytes.append(contentsOf: [._space, ._colon, ._space]) self.writeValuePretty(value, into: &bytes, depth: depth + 1) } while let (key, value) = iterator.next() { bytes.append(contentsOf: [._comma, ._newline]) self.addInset(to: &bytes, depth: depth + 1) // key self.encodeString(key, to: &bytes) bytes.append(contentsOf: [._space, ._colon, ._space]) // value self.writeValuePretty(value, into: &bytes, depth: depth + 1) } bytes.append(._newline) self.addInset(to: &bytes, depth: depth) bytes.append(._closebrace) } private func encodeString(_ string: String, to bytes: inout [UInt8]) { bytes.append(UInt8(ascii: "\"")) let stringBytes = string.utf8 var startCopyIndex = stringBytes.startIndex var nextIndex = startCopyIndex while nextIndex != stringBytes.endIndex { switch stringBytes[nextIndex] { case 0 ..< 32, UInt8(ascii: "\""), UInt8(ascii: "\\"): // All Unicode characters may be placed within the // quotation marks, except for the characters that MUST be escaped: // quotation mark, reverse solidus, and the control characters (U+0000 // through U+001F). // https://tools.ietf.org/html/rfc8259#section-7 // copy the current range over bytes.append(contentsOf: stringBytes[startCopyIndex ..< nextIndex]) switch stringBytes[nextIndex] { case UInt8(ascii: "\""): // quotation mark bytes.append(contentsOf: [._backslash, ._quote]) case UInt8(ascii: "\\"): // reverse solidus bytes.append(contentsOf: [._backslash, ._backslash]) case 0x08: // backspace bytes.append(contentsOf: [._backslash, UInt8(ascii: "b")]) case 0x0C: // form feed bytes.append(contentsOf: [._backslash, UInt8(ascii: "f")]) case 0x0A: // line feed bytes.append(contentsOf: [._backslash, UInt8(ascii: "n")]) case 0x0D: // carriage return bytes.append(contentsOf: [._backslash, UInt8(ascii: "r")]) case 0x09: // tab bytes.append(contentsOf: [._backslash, UInt8(ascii: "t")]) default: func valueToAscii(_ value: UInt8) -> UInt8 { switch value { case 0 ... 9: return value + UInt8(ascii: "0") case 10 ... 15: return value - 10 + UInt8(ascii: "a") default: preconditionFailure() } } bytes.append(UInt8(ascii: "\\")) bytes.append(UInt8(ascii: "u")) bytes.append(UInt8(ascii: "0")) bytes.append(UInt8(ascii: "0")) let first = stringBytes[nextIndex] / 16 let remaining = stringBytes[nextIndex] % 16 bytes.append(valueToAscii(first)) bytes.append(valueToAscii(remaining)) } nextIndex = stringBytes.index(after: nextIndex) startCopyIndex = nextIndex case UInt8(ascii: "/") where options.contains(.withoutEscapingSlashes) == false: bytes.append(contentsOf: stringBytes[startCopyIndex ..< nextIndex]) bytes.append(contentsOf: [._backslash, UInt8(ascii: "/")]) nextIndex = stringBytes.index(after: nextIndex) startCopyIndex = nextIndex default: nextIndex = stringBytes.index(after: nextIndex) } } // copy everything, that hasn't been copied yet bytes.append(contentsOf: stringBytes[startCopyIndex ..< nextIndex]) bytes.append(UInt8(ascii: "\"")) } } } //===----------------------------------------------------------------------===// // Shared Key Types //===----------------------------------------------------------------------===// internal struct _JSONKey: CodingKey { public var stringValue: String public var intValue: Int? public init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } public init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } public init(stringValue: String, intValue: Int?) { self.stringValue = stringValue self.intValue = intValue } internal init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } internal static let `super` = _JSONKey(stringValue: "super")! } //===----------------------------------------------------------------------===// // Shared ISO8601 Date Formatter //===----------------------------------------------------------------------===// // NOTE: This value is implicitly lazy and _must_ be lazy. We're compiled against the latest SDK (w/ ISO8601DateFormatter), but linked against whichever Foundation the user has. ISO8601DateFormatter might not exist, so we better not hit this code path on an older OS. @available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) internal var _iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter }() //===----------------------------------------------------------------------===// // Error Utilities //===----------------------------------------------------------------------===// extension EncodingError { /// Returns a `.invalidValue` error describing the given invalid floating-point value. /// /// /// - parameter value: The value that was invalid to encode. /// - parameter path: The path of `CodingKey`s taken to encode this value. /// - returns: An `EncodingError` with the appropriate path and debug description. fileprivate static func _invalidFloatingPointValue<T: FloatingPoint>(_ value: T, at codingPath: [CodingKey]) -> EncodingError { let valueDescription: String if value == T.infinity { valueDescription = "\(T.self).infinity" } else if value == -T.infinity { valueDescription = "-\(T.self).infinity" } else { valueDescription = "\(T.self).nan" } let debugDescription = "Unable to encode \(valueDescription) directly in JSON. Use JSONEncoder.NonConformingFloatEncodingStrategy.convertToString to specify how the value should be encoded." return .invalidValue(value, EncodingError.Context(codingPath: codingPath, debugDescription: debugDescription)) } }
apache-2.0
3d246c16581d46f2dacaad857b232ac8
38.727782
267
0.601592
4.993459
false
false
false
false
roambotics/swift
test/SILOptimizer/unused_containers.swift
2
1581
// RUN: %target-swift-frontend -primary-file %s -O -emit-sil | grep -v 'builtin "onFastPath"' | %FileCheck %s // REQUIRES: swift_stdlib_no_asserts // FIXME: https://github.com/apple/swift/issues/50345 // REQUIRES: CPU=arm64 || CPU=x86_64 // REQUIRES: rdar45797168 // FIXME: https://github.com/apple/swift/issues/51511 //CHECK-LABEL: @$s17unused_containers16empty_array_testyyF //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func empty_array_test() { let unused : [Int] = [] } //CHECK-LABEL: @$s17unused_containers14empty_dic_testyyF //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func empty_dic_test() { let unused : [Int: Int] = [:] } //CHECK-LABEL: sil hidden @$s17unused_containers0A12_string_testyyF //CHECK-NEXT: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func unused_string_test() { let unused : String = "" } //CHECK-LABEL: array_of_strings_test //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func array_of_strings_test() { let x = [""] } //CHECK-LABEL: string_interpolation //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func string_interpolation() { // Int let x : Int = 2 "\(x)" // String let y : String = "hi" "\(y)" // Float let f : Float = 2.0 "\(f)" // Bool "\(true)" //UInt8 "\(UInt8(2))" //UInt32 "\(UInt32(4))" } //CHECK-LABEL: string_interpolation2 //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func string_interpolation2() { "\(false) \(true)" } //CHECK-LABEL: string_plus //CHECK: bb0: //CHECK-NEXT: tuple //CHECK-NEXT: return func string_plus() { "a" + "b" }
apache-2.0
0d93415a87f285f00366543eb76c6401
17.821429
109
0.644529
2.828265
false
true
false
false
shajrawi/swift
stdlib/public/core/StringInterpolation.swift
1
9907
//===--- StringInterpolation.swift - String Interpolation -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Represents a string literal with interpolations while it is being built up. /// /// Do not create an instance of this type directly. It is used by the compiler /// when you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." /// /// When implementing an `ExpressibleByStringInterpolation` conformance, /// set the `StringInterpolation` associated type to /// `DefaultStringInterpolation` to get the same interpolation behavior as /// Swift's built-in `String` type and construct a `String` with the results. /// If you don't want the default behavior or don't want to construct a /// `String`, use a custom type conforming to `StringInterpolationProtocol` /// instead. /// /// Extending default string interpolation behavior /// =============================================== /// /// Code outside the standard library can extend string interpolation on /// `String` and many other common types by extending /// `DefaultStringInterpolation` and adding an `appendInterpolation(...)` /// method. For example: /// /// extension DefaultStringInterpolation { /// fileprivate mutating func appendInterpolation( /// escaped value: String, asASCII forceASCII: Bool = false) { /// for char in value.unicodeScalars { /// appendInterpolation(char.escaped(asASCII: forceASCII)) /// } /// } /// } /// /// print("Escaped string: \(escaped: string)") /// /// See `StringInterpolationProtocol` for details on `appendInterpolation` /// methods. /// /// `DefaultStringInterpolation` extensions should add only `mutating` members /// and should not copy `self` or capture it in an escaping closure. @_fixed_layout public struct DefaultStringInterpolation: StringInterpolationProtocol { /// The string contents accumulated by this instance. @usableFromInline internal var _storage: String /// Creates a string interpolation with storage pre-sized for a literal /// with the indicated attributes. /// /// Do not call this initializer directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public init(literalCapacity: Int, interpolationCount: Int) { let capacityPerInterpolation = 2 let initialCapacity = literalCapacity + interpolationCount * capacityPerInterpolation _storage = String(_StringGuts(_initialCapacity: initialCapacity)) } /// Appends a literal segment of a string interpolation. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. @inlinable public mutating func appendLiteral(_ literal: String) { literal.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable, T: CustomStringConvertible { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = "If one cookie costs \(price) dollars, " + /// "\(number) cookies cost \(price * number) dollars." /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: TextOutputStreamable { value.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) where T: CustomStringConvertible { value.description.write(to: &self) } /// Interpolates the given value's textual representation into the /// string literal being created. /// /// Do not call this method directly. It is used by the compiler when /// interpreting string interpolations. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable public mutating func appendInterpolation<T>(_ value: T) { _print_unlocked(value, &self) } /// Creates a string from this instance, consuming the instance in the /// process. @inlinable internal __consuming func make() -> String { return _storage } } extension DefaultStringInterpolation: CustomStringConvertible { @inlinable public var description: String { return _storage } } extension DefaultStringInterpolation: TextOutputStream { @inlinable public mutating func write(_ string: String) { _storage.append(string) } public mutating func _writeASCII(_ buffer: UnsafeBufferPointer<UInt8>) { _storage._guts.append(_StringGuts(buffer, isASCII: true)) } } // While not strictly necessary, declaring these is faster than using the // default implementation. extension String { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self = stringInterpolation.make() } } extension Substring { /// Creates a new instance from an interpolated string literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = """ /// If one cookie costs \(price) dollars, \ /// \(number) cookies cost \(price * number) dollars. /// """ /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @inlinable @_effects(readonly) public init(stringInterpolation: DefaultStringInterpolation) { self.init(stringInterpolation.make()) } }
apache-2.0
bb5dc128e3b3e8e251e0ece5b7d10fb2
37.699219
80
0.637226
4.863525
false
false
false
false
dipen30/Qmote
KodiRemote/Pods/UPnAtom/Source/AV Profile/Services/RenderingControl1Service.swift
1
20991
// // RenderingControl1Service.swift // // Copyright (c) 2015 David Robles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation open class RenderingControl1Service: AbstractUPnPService { open func listPresets(instanceID: String, success: @escaping (_ presetNameList: [String]) -> Void, failure: @escaping (_ error: NSError) -> Void) { let arguments = ["InstanceID" : instanceID] let parameters = SOAPRequestSerializer.Parameters(soapAction: "ListPresets", serviceURN: urn, arguments: arguments as! NSDictionary) soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in let responseObject = responseObject as? [String: String] success(responseObject?["CurrentPresetNameList"]?.components(separatedBy: ",") ?? [String]()) }, failure: {(task, error) in } ) } open func selectPreset(instanceID: String, presetName: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { let arguments = [ "InstanceID" : instanceID, "PresetName" : presetName] let parameters = SOAPRequestSerializer.Parameters(soapAction: "SelectPreset", serviceURN: urn, arguments: arguments as! NSDictionary) soapSessionManager.post(controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in success() }, failure: {(task, error) in } ) } open func getBrightness(instanceID: String, success: @escaping (_ brightness: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "Brightness", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setBrightness(instanceID: String, brightness: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "Brightness", stateVariableValue: brightness, success: success, failure: failure) } open func getContrast(instanceID: String, success: @escaping (_ contrast: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "Contrast", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setContrast(instanceID: String, contrast: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "Contrast", stateVariableValue: contrast, success: success, failure: failure) } open func getSharpness(instanceID: String, success: @escaping (_ sharpness: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "Sharpness", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setSharpness(instanceID: String, sharpness: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "Sharpness", stateVariableValue: sharpness, success: success, failure: failure) } open func getRedVideoGain(instanceID: String, success: @escaping (_ redVideoGain: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "RedVideoGain", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setRedVideoGain(instanceID: String, redVideoGain: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "RedVideoGain", stateVariableValue: redVideoGain, success: success, failure: failure) } open func getGreenVideoGain(instanceID: String, success: @escaping (_ greenVideoGain: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "GreenVideoGain", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setGreenVideoGain(instanceID: String, greenVideoGain: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "GreenVideoGain", stateVariableValue: greenVideoGain, success: success, failure: failure) } open func getBlueVideoGain(instanceID: String, success: @escaping (_ blueVideoGain: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "BlueVideoGain", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setBlueVideoGain(instanceID: String, blueVideoGain: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "BlueVideoGain", stateVariableValue: blueVideoGain, success: success, failure: failure) } open func getRedVideoBlackLevel(instanceID: String, success: @escaping (_ redVideoBlackLevel: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "RedVideoBlackLevel", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setRedVideoBlackLevel(instanceID: String, redVideoBlackLevel: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "RedVideoBlackLevel", stateVariableValue: redVideoBlackLevel, success: success, failure: failure) } open func getGreenVideoBlackLevel(instanceID: String, success: @escaping (_ greenVideoBlackLevel: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "GreenVideoBlackLevel", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setGreenVideoBlackLevel(instanceID: String, greenVideoBlackLevel: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "GreenVideoBlackLevel", stateVariableValue: greenVideoBlackLevel, success: success, failure: failure) } open func getBlueVideoBlackLevel(instanceID: String, success: @escaping (_ blueVideoBlackLevel: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "BlueVideoBlackLevel", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setBlueVideoBlackLevel(instanceID: String, blueVideoBlackLevel: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "BlueVideoBlackLevel", stateVariableValue: blueVideoBlackLevel, success: success, failure: failure) } open func getColorTemperature(instanceID: String, success: @escaping (_ colorTemperature: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "ColorTemperature", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setColorTemperature(instanceID: String, colorTemperature: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "ColorTemperature", stateVariableValue: colorTemperature, success: success, failure: failure) } open func getHorizontalKeystone(instanceID: String, success: @escaping (_ horizontalKeystone: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "HorizontalKeystone", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setHorizontalKeystone(instanceID: String, horizontalKeystone: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "HorizontalKeystone", stateVariableValue: horizontalKeystone, success: success, failure: failure) } open func getVerticalKeystone(instanceID: String, success: @escaping (_ verticalKeystone: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "VerticalKeystone", success: { (stateVariableValue: String?) -> Void in success(stateVariableValue) }, failure: failure) } open func setVerticalKeystone(instanceID: String, verticalKeystone: String, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "VerticalKeystone", stateVariableValue: verticalKeystone, success: success, failure: failure) } open func getMute(instanceID: String, channel: String = "Master", success: @escaping (_ mute: Bool) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "Mute", additionalArguments: ["Channel" : channel], isOptional: false, success: { (stateVariableValue: String?) -> Void in success((stateVariableValue ?? "0") == "0" ? false : true) }, failure: failure) } open func setMute(instanceID: String, mute: Bool, channel: String = "Master", success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "Mute", stateVariableValue: mute ? "1" : "0", additionalArguments: ["Channel" : channel], isOptional: false, success: success, failure: failure) } open func getVolume(instanceID: String, channel: String = "Master", success: @escaping (_ volume: Int) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "Volume", additionalArguments: ["Channel" : channel], success: { (stateVariableValue: String?) -> Void in success(Int(String(describing: stateVariableValue)) ?? 0) }, failure: failure) } open func setVolume(instanceID: String, volume: Int, channel: String = "Master", success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "Volume", stateVariableValue: "\(volume)", additionalArguments: ["Channel" : channel], success: success, failure: failure) } open func getVolumeDB(instanceID: String, channel: String = "Master", success: @escaping (_ volumeDB: Int) -> Void, failure:@escaping (_ error: NSError) -> Void) { let arguments = [ "InstanceID" : instanceID, "Channel" : channel] let parameters = SOAPRequestSerializer.Parameters(soapAction: "GetVolumeDB", serviceURN: urn, arguments: arguments as! NSDictionary) // Check if the optional SOAP action "GetVolumeDB" is supported supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in if isSupported { self.soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in let responseObject = responseObject as? [String: String] success(Int(String(describing: responseObject?["CurrentVolume"])) ?? 0) }, failure: {(task, error) in } ) } else { failure(createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)")) } } } open func setVolumeDB(instanceID: String, volumeDB: Int, channel: String = "Master", success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { let arguments = [ "InstanceID" : instanceID, "Channel" : channel, "DesiredVolume" : "\(volumeDB)"] let parameters = SOAPRequestSerializer.Parameters(soapAction: "SetVolumeDB", serviceURN: urn, arguments: arguments as! NSDictionary) // Check if the optional SOAP action "SetVolumeDB" is supported supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in if isSupported { self.soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in success() }, failure: {(task, error) in } ) } else { failure(createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)")) } } } open func getVolumeDBRange(instanceID: String, channel: String = "Master", success: @escaping (_ minimumValue: Int, _ maximumValue: Int) -> Void, failure:@escaping (_ error: NSError) -> Void) { let arguments = [ "InstanceID" : instanceID, "Channel" : channel] let parameters = SOAPRequestSerializer.Parameters(soapAction: "GetVolumeDBRange", serviceURN: urn, arguments: arguments as! NSDictionary) // Check if the optional SOAP action "getVolumeDBRange" is supported supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in if isSupported { self.soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in let responseObject = responseObject as? [String: String] success(Int(String(describing: responseObject?["MinValue"])) ?? 0, Int(String(describing: responseObject?["MaxValue"])) ?? 0) }, failure: {(task, error) in } ) } else { failure(createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)")) } } } open func getLoudness(instanceID: String, channel: String = "Master", success: @escaping (_ loudness: Bool) -> Void, failure:@escaping (_ error: NSError) -> Void) { getStateVariable(instanceID: instanceID, stateVariableName: "Loudness", additionalArguments: ["Channel" : channel], isOptional: false, success: { (stateVariableValue: String?) -> Void in success((stateVariableValue ?? "0") == "0" ? false : true) }, failure: failure) } open func setLoudness(instanceID: String, loudness: Bool, channel: String = "Master", success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { setStateVariable(instanceID: instanceID, stateVariableName: "Loudness", stateVariableValue: loudness ? "1" : "0", additionalArguments: ["Channel" : channel], isOptional: false, success: success, failure: failure) } fileprivate func getStateVariable(instanceID: String, stateVariableName: String, additionalArguments: [String: String] = [String: String](), isOptional: Bool = true, success: @escaping (_ stateVariableValue: String?) -> Void, failure:@escaping (_ error: NSError) -> Void) { let arguments = ["InstanceID" : instanceID] + additionalArguments let parameters = SOAPRequestSerializer.Parameters(soapAction: "Get\(stateVariableName)", serviceURN: urn, arguments: arguments as! NSDictionary) let performAction = { () -> Void in self.soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in let responseObject = responseObject as? [String: String] success(responseObject?["Current\(stateVariableName)"]) }, failure: {(task, error) in } ) } if isOptional { // Check if the optional SOAP action "Get<stateVariableName>" is supported supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in if isSupported { performAction() } else { failure(createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)")) } } } else { performAction() } } fileprivate func setStateVariable(instanceID: String, stateVariableName: String, stateVariableValue: String, additionalArguments: [String: String] = [String: String](), isOptional: Bool = true, success: @escaping () -> Void, failure:@escaping (_ error: NSError) -> Void) { let arguments = [ "InstanceID" : instanceID, "Desired\(stateVariableName)" : stateVariableValue] + additionalArguments let parameters = SOAPRequestSerializer.Parameters(soapAction: "Set\(stateVariableName)", serviceURN: urn, arguments: arguments as! NSDictionary) let performAction = { () -> Void in self.soapSessionManager.post(self.controlURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in success() }, failure: {(task, error) in } ) } if isOptional { // Check if the optional SOAP action "Set<stateVariableName>" is supported supportsSOAPAction(actionParameters: parameters) { (isSupported) -> Void in if isSupported { performAction() } else { failure(createError("SOAP action '\(parameters.soapAction)' unsupported by service \(self.urn) on device \(self.device?.friendlyName)")) } } } else { performAction() } } } /// for objective-c type checking extension AbstractUPnP { public func isRenderingControl1Service() -> Bool { return self is RenderingControl1Service } } /// overrides ExtendedPrintable protocol implementations extension RenderingControl1Service { override public var className: String { return "\(type(of: self))" } override open var description: String { var properties = PropertyPrinter() properties.add(super.className, property: super.description) return properties.description } }
apache-2.0
5740e98a7da58473e4b7e60356943f9b
60.020349
277
0.663522
4.772851
false
false
false
false
justindarc/focus
Blockzilla/AboutViewController.swift
4
10060
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit class AboutViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AboutHeaderViewDelegate { private lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.backgroundColor = UIConstants.colors.background tableView.layoutMargins = UIEdgeInsets.zero tableView.estimatedRowHeight = 44 tableView.separatorColor = UIConstants.colors.settingsSeparator // Don't show trailing rows. tableView.tableFooterView = UIView(frame: CGRect.zero) return tableView }() private let headerView = AboutHeaderView() override func viewDidLoad() { headerView.delegate = self title = String(format: UIConstants.strings.aboutTitle, AppInfo.productName) configureTableView() } private func configureTableView() { view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(self.view) } } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") return cell ?? UITableViewCell() } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { configureCell(cell, forRowAt: indexPath) } private func configureCell(_ cell: UITableViewCell, forRowAt indexPath: IndexPath) { switch (indexPath as NSIndexPath).row { case 0: cell.contentView.addSubview(headerView) headerView.snp.makeConstraints { make in make.edges.equalTo(cell) } case 1: cell.textLabel?.text = UIConstants.strings.aboutRowHelp case 2: cell.textLabel?.text = UIConstants.strings.aboutRowRights case 3: cell.textLabel?.text = UIConstants.strings.aboutRowPrivacy default: break } cell.backgroundColor = UIConstants.colors.background let cellBG = UIView() cellBG.backgroundColor = UIConstants.colors.cellSelected cell.selectedBackgroundView = cellBG cell.textLabel?.textColor = UIConstants.colors.defaultFont cell.layoutMargins = UIEdgeInsets.zero cell.separatorInset = UIEdgeInsets.zero } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { let cell = UITableViewCell() cell.backgroundColor = UIConstants.colors.background // Hack to cover header separator line let footer = UIView() footer.backgroundColor = UIConstants.colors.background cell.addSubview(footer) cell.sendSubviewToBack(footer) footer.snp.makeConstraints { make in make.height.equalTo(1) make.bottom.equalToSuperview().offset(1) make.leading.trailing.equalToSuperview() } return cell } return nil } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch (indexPath as NSIndexPath).row { case 0: // We ask for the height before we do a layout pass, so manually trigger a layout here // so we can calculate the view's height. headerView.layoutIfNeeded() return headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height default: break } return 44 } func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return (indexPath as NSIndexPath).row != 0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var url: URL? switch (indexPath as NSIndexPath).row { case 1: url = URL(string: "https://support.mozilla.org/\(AppInfo.config.supportPath)") case 2: url = LocalWebServer.sharedInstance.URLForPath("/\(AppInfo.config.rightsFile)") case 3: url = URL(string: "https://www.mozilla.org/privacy/firefox-focus") default: break } pushSettingsContentViewControllerWithURL(url) tableView.deselectRow(at: indexPath, animated: false) } private func pushSettingsContentViewControllerWithURL(_ url: URL?) { guard let url = url else { return } let contentViewController = SettingsContentViewController(url: url) navigationController?.pushViewController(contentViewController, animated: true) } fileprivate func aboutHeaderViewDidPressLearnMore(_ aboutHeaderView: AboutHeaderView) { let url = URL(string: "https://www.mozilla.org/\(AppInfo.languageCode)/about/manifesto/") pushSettingsContentViewControllerWithURL(url) } } private protocol AboutHeaderViewDelegate: class { func aboutHeaderViewDidPressLearnMore(_ aboutHeaderView: AboutHeaderView) } private class AboutHeaderView: UIView { weak var delegate: AboutHeaderViewDelegate? private lazy var logo: UIImageView = { let logo = UIImageView(image: AppInfo.config.wordmark) return logo }() private lazy var aboutParagraph: UILabel = { let bulletStyle = NSMutableParagraphStyle() bulletStyle.firstLineHeadIndent = 15 bulletStyle.headIndent = 29.5 let bulletAttributes: [NSAttributedString.Key: Any] = [.paragraphStyle: bulletStyle] let bulletFormat = "• %@\n" let paragraph = [ NSAttributedString(string: String(format: UIConstants.strings.aboutTopLabel, AppInfo.productName) + "\n\n"), NSAttributedString(string: UIConstants.strings.aboutPrivateBulletHeader + "\n"), NSAttributedString(string: String(format: bulletFormat, UIConstants.strings.aboutPrivateBullet1), attributes: bulletAttributes), NSAttributedString(string: String(format: bulletFormat, UIConstants.strings.aboutPrivateBullet2), attributes: bulletAttributes), NSAttributedString(string: String(format: bulletFormat, UIConstants.strings.aboutPrivateBullet3 + "\n"), attributes: bulletAttributes), NSAttributedString(string: UIConstants.strings.aboutSafariBulletHeader + "\n"), NSAttributedString(string: String(format: bulletFormat, UIConstants.strings.aboutSafariBullet1), attributes: bulletAttributes), NSAttributedString(string: String(format: bulletFormat, UIConstants.strings.aboutSafariBullet2 + "\n"), attributes: bulletAttributes), NSAttributedString(string: String(format: UIConstants.strings.aboutMissionLabel, AppInfo.productName)) ] let attributed = NSMutableAttributedString() paragraph.forEach { attributed.append($0) } let aboutParagraph = SmartLabel() aboutParagraph.attributedText = attributed aboutParagraph.textColor = UIConstants.colors.defaultFont aboutParagraph.font = UIConstants.fonts.aboutText aboutParagraph.numberOfLines = 0 return aboutParagraph }() private lazy var versionNumber: UILabel = { let label = SmartLabel() label.text = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String label.font = UIConstants.fonts.aboutText label.textColor = UIConstants.colors.defaultFont.withAlphaComponent(0.5) return label }() private lazy var learnMoreButton: UIButton = { let learnMoreButton = UIButton() learnMoreButton.setTitle(UIConstants.strings.aboutLearnMoreButton, for: .normal) learnMoreButton.setTitleColor(UIConstants.colors.settingsLink, for: .normal) learnMoreButton.setTitleColor(UIConstants.colors.buttonHighlight, for: .highlighted) learnMoreButton.titleLabel?.font = UIConstants.fonts.aboutText learnMoreButton.addTarget(self, action: #selector(didPressLearnMore), for: .touchUpInside) return learnMoreButton }() convenience init() { self.init(frame: CGRect.zero) addSubviews() configureConstraints() } @objc private func didPressLearnMore() { delegate?.aboutHeaderViewDidPressLearnMore(self) } private func addSubviews() { addSubview(logo) addSubview(aboutParagraph) addSubview(versionNumber) addSubview(learnMoreButton) } private func configureConstraints() { logo.snp.makeConstraints { make in make.centerX.equalTo(self) make.top.equalTo(self).offset(50) } versionNumber.snp.makeConstraints { make in make.centerX.equalTo(self) make.top.equalTo(logo.snp.bottom).offset(8) } aboutParagraph.snp.makeConstraints { make in // Priority hack is needed to avoid conflicting constraints with the cell height. // See http://stackoverflow.com/a/25795758 make.top.equalTo(logo.snp.bottom).offset(50).priority(999) make.centerX.equalTo(self) make.width.lessThanOrEqualTo(self).inset(20) make.width.lessThanOrEqualTo(315) } learnMoreButton.snp.makeConstraints { make in make.top.greaterThanOrEqualTo(aboutParagraph.snp.bottom).priority(.required) make.leading.equalTo(aboutParagraph) make.bottom.equalTo(self).inset(50).priority(.low) } } }
mpl-2.0
7c6083560b706209e65f35846ec7e9e1
38.443137
147
0.678167
5.26046
false
false
false
false
richardpiazza/XCServerCoreData
Sources/StatsBreakdown.swift
1
492
import Foundation import CoreData import CodeQuickKit import XCServerAPI public class StatsBreakdown: NSManagedObject { public func update(withStatsBreakdown breakdown: XCSStatsSummary) { self.sum = breakdown.sum as NSNumber? self.count = breakdown.count as NSNumber? self.min = breakdown.min as NSNumber? self.max = breakdown.max as NSNumber? self.avg = breakdown.avg as NSNumber? self.stdDev = breakdown.stdDev as NSNumber? } }
mit
966454d07f65c1b4f2e2cbe2b612f647
29.75
71
0.705285
4.1
false
false
false
false
wwu-pi/md2-framework
de.wwu.md2.framework/res/resources/ios/lib/controller/eventhandler/MD2OnRightSwipeHandler.swift
1
2070
// // MD2OnRightSwipeHandler.swift // md2-ios-library // // Created by Christoph Rieger on 05.08.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // import UIKit /// Event handler for right swipe events. class MD2OnRightSwipeHandler: MD2WidgetEventHandler { /// Convenience typealias for the tuple of action and widget typealias actionWidgetTuple = (MD2Action, MD2WidgetWrapper) /// The singleton instance. static let instance: MD2OnRightSwipeHandler = MD2OnRightSwipeHandler() /// The list of registered action-widget tuples. var actions: Dictionary<String,actionWidgetTuple> = [:] /// Singleton initializer. private init() { // Nothing to initialize } /** Register an action. :param: action The action to execute in case of an event. :param: widget The widget that the action should be bound to. */ func registerAction(action: MD2Action, widget: MD2WidgetWrapper) { actions[action.actionSignature] = (action, widget) } /** Unregister an action. :param: action The action to remove. :param: widget The widget the action was registered to. */ func unregisterAction(action: MD2Action, widget: MD2WidgetWrapper) { for (key, value) in actions { if key == action.actionSignature { actions[key] = nil break } } } /** Method that is called to fire an event. *Notice* Visible to Objective-C runtime to receive events from UI elements. :param: sender The widget sending the event. */ @objc func fire(sender: UIControl) { //println("Event fired to OnClickHandler: " + String(sender.tag) + "=" + WidgetMapping.fromRawValue(sender.tag).description) for (_, (action, widget)) in actions { if widget.widgetId == MD2WidgetMapping.fromRawValue(sender.tag) { action.execute() } } } }
apache-2.0
4142cb2be4c66fb4991296fd2e121762
28.169014
132
0.613043
4.539474
false
false
false
false
fgengine/quickly
Quickly/Compositions/Standart/QTitleDetailComposition.swift
1
3577
// // Quickly // open class QTitleDetailComposable : QComposable { public var titleStyle: QLabelStyleSheet public var titleSpacing: CGFloat public var detailStyle: QLabelStyleSheet public init( edgeInsets: UIEdgeInsets = UIEdgeInsets.zero, titleStyle: QLabelStyleSheet, titleSpacing: CGFloat = 4, detailStyle: QLabelStyleSheet ) { self.titleStyle = titleStyle self.titleSpacing = titleSpacing self.detailStyle = detailStyle super.init(edgeInsets: edgeInsets) } } open class QTitleDetailComposition< Composable: QTitleDetailComposable > : QComposition< Composable > { public private(set) lazy var titleView: QLabel = { let view = QLabel(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false view.setContentHuggingPriority( horizontal: UILayoutPriority(rawValue: 252), vertical: UILayoutPriority(rawValue: 252) ) self.contentView.addSubview(view) return view }() public private(set) lazy var detailView: QLabel = { let view = QLabel(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() private var _edgeInsets: UIEdgeInsets? private var _titleSpacing: CGFloat? private var _constraints: [NSLayoutConstraint] = [] { willSet { self.contentView.removeConstraints(self._constraints) } didSet { self.contentView.addConstraints(self._constraints) } } open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize { let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right) let titleTextSize = composable.titleStyle.size(width: availableWidth) let detailTextSize = composable.detailStyle.size(width: availableWidth) return CGSize( width: spec.containerSize.width, height: composable.edgeInsets.top + titleTextSize.height + composable.titleSpacing + detailTextSize.height + composable.edgeInsets.bottom ) } open override func preLayout(composable: Composable, spec: IQContainerSpec) { if self._edgeInsets != composable.edgeInsets || self._titleSpacing != composable.titleSpacing { self._edgeInsets = composable.edgeInsets self._titleSpacing = composable.titleSpacing self._constraints = [ self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.titleView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left), self.titleView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.titleView.bottomLayout <= self.detailView.topLayout.offset(-composable.titleSpacing), self.detailView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left), self.detailView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.detailView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets .bottom) ] } } open override func apply(composable: Composable, spec: IQContainerSpec) { self.titleView.apply(composable.titleStyle) self.detailView.apply(composable.detailStyle) } }
mit
e3a9b9ec9d06d3c3b34d3bd673d6c72e
42.096386
149
0.6922
5.387048
false
false
false
false
inamiy/ReactiveCocoaCatalog
ReactiveCocoaCatalog/Samples/ReactiveTableViewController.swift
1
2044
// // ReactiveTableViewController.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2016-04-02. // Copyright © 2016 Yasuhiro Inami. All rights reserved. // import UIKit import Result import ReactiveSwift import ReactiveArray private let _cellIdentifier = "ReactiveTableCellIdentifier" final class ReactiveTableViewController: UITableViewController, ReactiveArrayViewControllerType, StoryboardSceneProvider { static let storyboardScene = StoryboardScene<ReactiveTableViewController>(name: "ReactiveArray") @IBOutlet weak var insertButtonItem: UIBarButtonItem? @IBOutlet weak var replaceButtonItem: UIBarButtonItem? @IBOutlet weak var removeButtonItem: UIBarButtonItem? @IBOutlet weak var decrementButtonItem: UIBarButtonItem? @IBOutlet weak var incrementButtonItem: UIBarButtonItem? @IBOutlet weak var sectionOrItemButtonItem: UIBarButtonItem? let viewModel = ReactiveArrayViewModel(cellIdentifier: _cellIdentifier) let protocolSelectorForDidSelectItem = Selector._didSelectRow var itemsView: UITableView { return self.tableView } override func viewDidLoad() { super.viewDidLoad() // show toolbar self.navigationController?.setToolbarHidden(false, animated: false) self.setupSignalsForDemo() self.tableView.dataSource = self.viewModel // Set delegate after calling `rac_signal(for: _:from:)`. // - https://github.com/ReactiveCocoa/ReactiveCocoa/issues/1121 // - http://stackoverflow.com/questions/22000433/rac-signalforselector-needs-empty-implementation self.itemsView.delegate = nil // set nil to clear selector cache self.itemsView.delegate = self self.playDemo() } } // MARK: Selectors extension Selector { // NOTE: needed to upcast to `Protocol` for some reason... fileprivate static let _didSelectRow: (Selector, Protocol) = ( #selector(UITableViewDelegate.tableView(_:didSelectRowAt:)), UITableViewDelegate.self ) }
mit
d061a35aad3265c7f0913d12a28035cb
29.492537
120
0.733725
5.03202
false
false
false
false
jbruce2112/cutlines
Cutlines/Controllers/CreateViewController.swift
1
2900
// // CreateViewController.swift // Cutlines // // Created by John on 1/31/17. // Copyright © 2017 Bruce32. All rights reserved. // import UIKit import Photos class CreateViewController: UIViewController { // MARK: Properties var image: UIImage! var fileURL: URL? var photoManager: PhotoManager! private var containerView = PhotoContainerView() private var canceled = false // MARK: Functions override func viewDidLoad() { super.viewDidLoad() view.addSubview(containerView) containerView.polaroidView.image = image let flipButton = UIBarButtonItem(image: #imageLiteral(resourceName: "refresh"), style: .plain, target: containerView, action: #selector(PhotoContainerView.flip)) let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel)) navigationItem.setRightBarButtonItems([cancelButton, flipButton], animated: false) navigationItem.title = "Add" // Grow the containerView as large as the top and bottom layout guides permit // containter.top = topLayoutGuide.bottom + 10 let topEQ = containerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10) // bottomLayoutGuide.top = container.bottom + 10 let bottomEQ = view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 10) topEQ.priority = UILayoutPriority.defaultHigh bottomEQ.priority = UILayoutPriority.defaultHigh topEQ.isActive = true bottomEQ.isActive = true // container.top >= topLayoutGuide.bottom + 10 containerView.topAnchor.constraint(greaterThanOrEqualTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true // bottomLayoutGuide.top >= container.bottom + 10 view.safeAreaLayoutGuide.bottomAnchor.constraint(greaterThanOrEqualTo: containerView.bottomAnchor, constant: 10).isActive = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setTheme() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if !canceled { save() } } @objc func cancel() { canceled = true navigationController?.popViewController(animated: true) } // MARK: Actions @IBAction func backgroundTapped(_ sender: UITapGestureRecognizer) { containerView.captionView.endEditing(true) } private func save() { guard let creationDate = getCreationDate() else { return } photoManager.add(image: image, caption: containerView.captionView.getCaption(), dateTaken: creationDate, completion: nil) } private func getCreationDate() -> Date? { // If we have the fileURL, try and read the ctime from that if let fileURL = fileURL, let attrs = try? FileManager.default.attributesOfItem(atPath: fileURL.relativePath), let ctime = attrs[.creationDate] as? Date { return ctime } return nil } }
mit
f6dd7acc7895e39ec72f40fce653264b
26.609524
163
0.741635
4.238304
false
false
false
false
superpeteblaze/ScalingCarousel
Sources/ScalingCarousel/ScalingCarouselView.swift
1
11562
// // Created by Pete Smith // http://www.petethedeveloper.com // // // License // Copyright © 2017-present Pete Smith // Released under an MIT license: http://opensource.org/licenses/MIT // import UIKit /* ScalingCarouselView is a subclass of UICollectionView which is intended to be used to carousel through cells which don't extend to the edges of a screen. The previous and subsequent cells are scaled as the carousel scrolls. */ open class ScalingCarouselView: UICollectionView { // MARK: - Properties (Private) private var lastCurrentCenterCellIndex: IndexPath? // MARK: - Properties (Public) open var scrollDirection: UICollectionView.ScrollDirection = .horizontal /// Inset of the main, center cell @IBInspectable public var inset: CGFloat = 0.0 { didSet { /* Configure our layout, and add more constraints to our invisible UIScrollView */ configureLayout() } } /// Returns the current center cell of the carousel if it can be calculated open var currentCenterCell: UICollectionViewCell? { let lowerBound = inset - 20 let upperBound = inset + 20 for cell in visibleCells { let cellRect = convert(cell.frame, to: nil) if scrollDirection == .horizontal && cellRect.origin.x > lowerBound && cellRect.origin.x < upperBound { return cell } else if scrollDirection == .vertical && cellRect.origin.y > lowerBound && cellRect.origin.y < upperBound { return cell } } return nil } /// Returns the IndexPath of the current center cell if it can be calculated open var currentCenterCellIndex: IndexPath? { guard let currentCenterCell = self.currentCenterCell else { return nil } return indexPath(for: currentCenterCell) } /// Override of the collection view content size to add an observer override open var contentSize: CGSize { didSet { guard let dataSource = dataSource, let invisibleScrollView = invisibleScrollView else { return } let numberSections = dataSource.numberOfSections?(in: self) ?? 1 // Calculate total number of items in collection view var numberItems = 0 for i in 0..<numberSections { let numberSectionItems = dataSource.collectionView(self, numberOfItemsInSection: i) numberItems += numberSectionItems } // Set the invisibleScrollView contentSize width based on number of items if scrollDirection == .horizontal { let contentWidth = invisibleScrollView.frame.width * CGFloat(numberItems) invisibleScrollView.contentSize = CGSize(width: contentWidth, height: invisibleScrollView.frame.height) } else { let contentHeight = invisibleScrollView.frame.height * CGFloat(numberItems) invisibleScrollView.contentSize = CGSize(width: invisibleScrollView.frame.width, height: contentHeight) } } } // MARK: - Properties (Private) fileprivate var invisibleScrollView: UIScrollView! fileprivate var invisibleWidthOrHeightConstraint: NSLayoutConstraint? fileprivate var invisibleLeftOrTopConstraint: NSLayoutConstraint? // MARK: - Lifecycle override public init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Convenience initializer allowing setting of the carousel inset /// /// - Parameters: /// - frame: Frame /// - inset: Inset public convenience init(withFrame frame: CGRect, andInset inset: CGFloat) { self.init(frame: frame, collectionViewLayout: ScalingCarouselLayout(withCarouselInset: inset)) self.inset = inset } // MARK: - Overrides override open func scrollRectToVisible(_ rect: CGRect, animated: Bool) { invisibleScrollView.setContentOffset(rect.origin, animated: animated) } override open func scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionView.ScrollPosition, animated: Bool) { super.scrollToItem(at: indexPath, at: scrollPosition, animated: animated) var origin = (CGFloat(indexPath.item) * (frame.size.width - (inset * 2))) var rect = CGRect(x: origin, y: 0, width: frame.size.width - (inset * 2), height: frame.height) if scrollDirection == .vertical { origin = (CGFloat(indexPath.item) * (frame.size.height - (inset * 2))) rect = CGRect(x: 0, y: origin, width: frame.width, height: frame.size.height - (inset * 2)) } scrollRectToVisible(rect, animated: animated) lastCurrentCenterCellIndex = indexPath } override open func didMoveToSuperview() { super.didMoveToSuperview() addInvisibleScrollView(to: superview) } // MARK: - Public API /* This method should ALWAYS be called from the ScalingCarousel delegate when the UIScrollViewDelegate scrollViewDidScroll(_:) method is called e.g In the ScalingCarousel delegate, implement: func scrollViewDidScroll(_ scrollView: UIScrollView) { carousel.didScroll() } */ public func didScroll() { scrollViewDidScroll(self) } /* This method should ALWAYS be called from the ViewController that handles the ScalingCarousel when the viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) method is called e.g Implement: func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) carousel.deviceRotated() } */ public func deviceRotated() { guard let lastCurrentCenterCellIndex = currentCenterCellIndex ?? lastCurrentCenterCellIndex else { return } DispatchQueue.main.async { self.reloadData() var position: UICollectionView.ScrollPosition = .centeredHorizontally if self.scrollDirection == .vertical { position = .centeredVertically } self.scrollToItem(at: lastCurrentCenterCellIndex, at: position, animated: false) self.didScroll() } } } private typealias PrivateAPI = ScalingCarouselView fileprivate extension PrivateAPI { func addInvisibleScrollView(to superview: UIView?) { guard let superview = superview else { return } /// Add our 'invisible' scrollview invisibleScrollView = UIScrollView(frame: bounds) invisibleScrollView.translatesAutoresizingMaskIntoConstraints = false invisibleScrollView.isPagingEnabled = true invisibleScrollView.showsHorizontalScrollIndicator = false invisibleScrollView.showsVerticalScrollIndicator = false /* Disable user interaction on the 'invisible' scrollview, This means touch events will fall through to the underlying UICollectionView */ invisibleScrollView.isUserInteractionEnabled = false /// Set the scroll delegate to be the ScalingCarouselView invisibleScrollView.delegate = self /* Now add the invisible scrollview's pan gesture recognizer to the ScalingCarouselView */ addGestureRecognizer(invisibleScrollView.panGestureRecognizer) /* Finally, add the 'invisible' scrollview as a subview of the ScalingCarousel's superview */ superview.addSubview(invisibleScrollView) /* Add constraints for height and top, relative to the ScalingCarouselView */ if scrollDirection == .horizontal { invisibleScrollView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true invisibleScrollView.topAnchor.constraint(equalTo: topAnchor).isActive = true } else { invisibleScrollView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true invisibleScrollView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true } /* Further configure our layout and add more constraints for width and left position */ configureLayout() } func configureLayout() { // Create a ScalingCarouselLayout using our inset collectionViewLayout = ScalingCarouselLayout( withCarouselInset: inset) /* Only continue if we have a reference to our 'invisible' UIScrollView */ guard let invisibleScrollView = invisibleScrollView else { return } // Remove constraints if they already exist invisibleWidthOrHeightConstraint?.isActive = false invisibleLeftOrTopConstraint?.isActive = false /* Add constrants for width and left postion to our 'invisible' UIScrollView if scroll Direction is horizontal height and top position if scroll Direction is vertical */ if scrollDirection == .horizontal { invisibleWidthOrHeightConstraint = invisibleScrollView.widthAnchor.constraint(equalTo: widthAnchor, constant: -(2 * inset)) invisibleLeftOrTopConstraint = invisibleScrollView.leftAnchor.constraint(equalTo: leftAnchor, constant: inset) } else { invisibleWidthOrHeightConstraint = invisibleScrollView.heightAnchor.constraint(equalTo: heightAnchor, constant: -(2 * inset)) invisibleLeftOrTopConstraint = invisibleScrollView.topAnchor.constraint(equalTo: topAnchor, constant: inset) } // Activate the constraints invisibleWidthOrHeightConstraint?.isActive = true invisibleLeftOrTopConstraint?.isActive = true // To avoid carousel moving when cell is tapped isPagingEnabled = true isScrollEnabled = false } } /* Scroll view delegate extension used to respond to scrolling of the invisible scrollView */ private typealias InvisibleScrollDelegate = ScalingCarouselView extension InvisibleScrollDelegate: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { /* Move the ScalingCarousel base d on the contentOffset of the 'invisible' UIScrollView */ updateOffSet() // Also, this is where we scale our cells for cell in visibleCells { if let infoCardCell = cell as? ScalingCarouselCell { infoCardCell.scale(withCarouselInset: inset) } } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { delegate?.scrollViewDidEndDecelerating?(scrollView) guard let indexPath = currentCenterCellIndex else { return } lastCurrentCenterCellIndex = indexPath } private func updateOffSet() { contentOffset = invisibleScrollView.contentOffset } }
mit
1221300b26402f1a9506e3d78daedf4d
36.414239
137
0.650117
5.760339
false
false
false
false
arietis/codility-swift
12.2.swift
1
971
public func solution(inout A : [Int], inout _ B : [Int]) -> Int { // write your code in Swift 2.2 var count = 0 func gcd(a: Int, b: Int) -> Int { if a % b == 0 { return b } else { return gcd(b, b: a % b) } } func hasSamePrimeDivisors(var a: Int, var b: Int) -> Bool { let gcdValue = gcd(a, b: b) while a != 1 { let aGcd = gcd(a, b: gcdValue) if aGcd == 1 { break } a /= aGcd } if a != 1 { return false } while b != 1 { let bGcd = gcd(b, b: gcdValue) if bGcd == 1 { break } b /= bGcd } return b == 1 } for i in 0..<A.count { if hasSamePrimeDivisors(A[i], b: B[i]) { count += 1 } } return count }
mit
803f84752e77684684da5bd4257f2825
18.42
65
0.354274
3.853175
false
false
false
false
benlangmuir/swift
stdlib/public/core/Flatten.swift
14
12912
//===--- Flatten.swift ----------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A sequence consisting of all the elements contained in each segment /// contained in some `Base` sequence. /// /// The elements of this view are a concatenation of the elements of /// each sequence in the base. /// /// The `joined` method is always lazy, but does not implicitly /// confer laziness on algorithms applied to its result. In other /// words, for ordinary sequences `s`: /// /// * `s.joined()` does not create new storage /// * `s.joined().map(f)` maps eagerly and returns a new array /// * `s.lazy.joined().map(f)` maps lazily and returns a `LazyMapSequence` @frozen // lazy-performance public struct FlattenSequence<Base: Sequence> where Base.Element: Sequence { @usableFromInline // lazy-performance internal var _base: Base /// Creates a concatenation of the elements of the elements of `base`. /// /// - Complexity: O(1) @inlinable // lazy-performance internal init(_base: Base) { self._base = _base } } extension FlattenSequence { @frozen // lazy-performance public struct Iterator { @usableFromInline // lazy-performance internal var _base: Base.Iterator @usableFromInline // lazy-performance internal var _inner: Base.Element.Iterator? /// Construct around a `base` iterator. @inlinable // lazy-performance internal init(_base: Base.Iterator) { self._base = _base } } } extension FlattenSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element.Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @inlinable // lazy-performance public mutating func next() -> Element? { repeat { if _fastPath(_inner != nil) { let ret = _inner!.next() if _fastPath(ret != nil) { return ret } } let s = _base.next() if _slowPath(s == nil) { return nil } _inner = s!.makeIterator() } while true } } extension FlattenSequence.Iterator: Sequence { } extension FlattenSequence: Sequence { /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // lazy-performance public __consuming func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator()) } } extension Sequence where Element: Sequence { /// Returns the elements of this sequence of sequences, concatenated. /// /// In this example, an array of three ranges is flattened so that the /// elements of each range can be iterated in turn. /// /// let ranges = [0..<3, 8..<10, 15..<17] /// /// // A for-in loop over 'ranges' accesses each range: /// for range in ranges { /// print(range) /// } /// // Prints "0..<3" /// // Prints "8..<10" /// // Prints "15..<17" /// /// // Use 'joined()' to access each element of each range: /// for index in ranges.joined() { /// print(index, terminator: " ") /// } /// // Prints: "0 1 2 8 9 15 16" /// /// - Returns: A flattened view of the elements of this /// sequence of sequences. @inlinable // lazy-performance public __consuming func joined() -> FlattenSequence<Self> { return FlattenSequence(_base: self) } } extension LazySequenceProtocol where Element: Sequence { /// Returns a lazy sequence that concatenates the elements of this sequence of /// sequences. @inlinable // lazy-performance public __consuming func joined() -> LazySequence<FlattenSequence<Elements>> { return FlattenSequence(_base: elements).lazy } } public typealias FlattenCollection<T: Collection> = FlattenSequence<T> where T.Element: Collection extension FlattenSequence where Base: Collection, Base.Element: Collection { /// A position in a FlattenCollection @frozen // lazy-performance public struct Index { /// The position in the outer collection of collections. @usableFromInline // lazy-performance internal let _outer: Base.Index /// The position in the inner collection at `base[_outer]`, or `nil` if /// `_outer == base.endIndex`. /// /// When `_inner != nil`, `_inner!` is a valid subscript of `base[_outer]`; /// when `_inner == nil`, `_outer == base.endIndex` and this index is /// `endIndex` of the `FlattenCollection`. @usableFromInline // lazy-performance internal let _inner: Base.Element.Index? @inlinable // lazy-performance internal init(_ _outer: Base.Index, _ inner: Base.Element.Index?) { self._outer = _outer self._inner = inner } } } extension FlattenSequence.Index: Equatable where Base: Collection, Base.Element: Collection { @inlinable // lazy-performance public static func == ( lhs: FlattenCollection<Base>.Index, rhs: FlattenCollection<Base>.Index ) -> Bool { return lhs._outer == rhs._outer && lhs._inner == rhs._inner } } extension FlattenSequence.Index: Comparable where Base: Collection, Base.Element: Collection { @inlinable // lazy-performance public static func < ( lhs: FlattenCollection<Base>.Index, rhs: FlattenCollection<Base>.Index ) -> Bool { // FIXME: swift-3-indexing-model: tests. if lhs._outer != rhs._outer { return lhs._outer < rhs._outer } if let lhsInner = lhs._inner, let rhsInner = rhs._inner { return lhsInner < rhsInner } // When combined, the two conditions above guarantee that both // `_outer` indices are `_base.endIndex` and both `_inner` indices // are `nil`, since `_inner` is `nil` iff `_outer == base.endIndex`. _precondition(lhs._inner == nil && rhs._inner == nil) return false } } extension FlattenSequence.Index: Hashable where Base: Collection, Base.Element: Collection, Base.Index: Hashable, Base.Element.Index: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(_outer) hasher.combine(_inner) } } extension FlattenCollection: Collection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable // lazy-performance public var startIndex: Index { let end = _base.endIndex var outer = _base.startIndex while outer != end { let innerCollection = _base[outer] if !innerCollection.isEmpty { return Index(outer, innerCollection.startIndex) } _base.formIndex(after: &outer) } return endIndex } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @inlinable // lazy-performance public var endIndex: Index { return Index(_base.endIndex, nil) } @inlinable // lazy-performance internal func _index(after i: Index) -> Index { let innerCollection = _base[i._outer] let nextInner = innerCollection.index(after: i._inner!) if _fastPath(nextInner != innerCollection.endIndex) { return Index(i._outer, nextInner) } var nextOuter = _base.index(after: i._outer) while nextOuter != _base.endIndex { let nextInnerCollection = _base[nextOuter] if !nextInnerCollection.isEmpty { return Index(nextOuter, nextInnerCollection.startIndex) } _base.formIndex(after: &nextOuter) } return endIndex } @inlinable // lazy-performance internal func _index(before i: Index) -> Index { var prevOuter = i._outer if prevOuter == _base.endIndex { prevOuter = _base.index(prevOuter, offsetBy: -1) } var prevInnerCollection = _base[prevOuter] var prevInner = i._inner ?? prevInnerCollection.endIndex while prevInner == prevInnerCollection.startIndex { prevOuter = _base.index(prevOuter, offsetBy: -1) prevInnerCollection = _base[prevOuter] prevInner = prevInnerCollection.endIndex } return Index(prevOuter, prevInnerCollection.index(prevInner, offsetBy: -1)) } // TODO: swift-3-indexing-model - add docs @inlinable // lazy-performance public func index(after i: Index) -> Index { return _index(after: i) } @inlinable // lazy-performance public func formIndex(after i: inout Index) { i = index(after: i) } @inlinable // lazy-performance public func distance(from start: Index, to end: Index) -> Int { // The following check makes sure that distance(from:to:) is invoked on the // _base at least once, to trigger a _precondition in forward only // collections. if end < start { _ = _base.distance(from: _base.endIndex, to: _base.startIndex) } var _start: Index let _end: Index let step: Int if start > end { _start = end _end = start step = -1 } else { _start = start _end = end step = 1 } var count = 0 while _start != _end { count += step formIndex(after: &_start) } return count } @inline(__always) @inlinable // lazy-performance internal func _advanceIndex(_ i: inout Index, step: Int) { _internalInvariant(-1...1 ~= step, "step should be within the -1...1 range") i = step < 0 ? _index(before: i) : _index(after: i) } @inline(__always) @inlinable // lazy-performance internal func _ensureBidirectional(step: Int) { // FIXME: This seems to be the best way of checking whether _base is // forward only without adding an extra protocol requirement. // index(_:offsetBy:limitedBy:) is chosen because it is supposed to return // nil when the resulting index lands outside the collection boundaries, // and therefore likely does not trap in these cases. if step < 0 { _ = _base.index( _base.endIndex, offsetBy: step, limitedBy: _base.startIndex) } } @inlinable // lazy-performance public func index(_ i: Index, offsetBy n: Int) -> Index { var i = i let step = n.signum() _ensureBidirectional(step: step) for _ in 0 ..< abs(n) { _advanceIndex(&i, step: step) } return i } @inlinable // lazy-performance public func formIndex(_ i: inout Index, offsetBy n: Int) { i = index(i, offsetBy: n) } @inlinable // lazy-performance public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { var i = i let step = n.signum() // The following line makes sure that index(_:offsetBy:limitedBy:) is // invoked on the _base at least once, to trigger a _precondition in // forward only collections. _ensureBidirectional(step: step) for _ in 0 ..< abs(n) { if i == limit { return nil } _advanceIndex(&i, step: step) } return i } @inlinable // lazy-performance public func formIndex( _ i: inout Index, offsetBy n: Int, limitedBy limit: Index ) -> Bool { if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) { i = advancedIndex return true } i = limit return false } /// Accesses the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @inlinable // lazy-performance public subscript(position: Index) -> Base.Element.Element { return _base[position._outer][position._inner!] } @inlinable // lazy-performance public subscript(bounds: Range<Index>) -> Slice<FlattenCollection<Base>> { return Slice(base: self, bounds: bounds) } } extension FlattenCollection: BidirectionalCollection where Base: BidirectionalCollection, Base.Element: BidirectionalCollection { // FIXME(performance): swift-3-indexing-model: add custom advance/distance // methods that skip over inner collections when random-access // TODO: swift-3-indexing-model - add docs @inlinable // lazy-performance public func index(before i: Index) -> Index { return _index(before: i) } @inlinable // lazy-performance public func formIndex(before i: inout Index) { i = index(before: i) } }
apache-2.0
506c1fb5002c12da3ab7f5dab6e5586c
29.889952
104
0.644517
4.078332
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/FeedbackUI.swift
2
3026
// // FeedbackUI.swift // Client // // Created by Mahmoud Adam on 11/10/16. // Copyright © 2016 Mozilla. All rights reserved. // import Foundation import CRToast import SVProgressHUD public enum ToastMessageType { case info case error case done } class FeedbackUI: NSObject { static var defaultOptions : [AnyHashable: Any] = [ kCRToastTextAlignmentKey : NSNumber(value: NSTextAlignment.left.rawValue), kCRToastNotificationTypeKey: NSNumber(value: CRToastType.navigationBar.rawValue), kCRToastNotificationPresentationTypeKey: NSNumber(value: CRToastPresentationType.cover.rawValue), kCRToastAnimationInTypeKey : NSNumber(value: CRToastAnimationType.linear.rawValue), kCRToastAnimationOutTypeKey : NSNumber(value: CRToastAnimationType.linear.rawValue), kCRToastAnimationInDirectionKey : NSNumber(value: CRToastAnimationDirection.top.rawValue), kCRToastAnimationOutDirectionKey : NSNumber(value: CRToastAnimationDirection.top.rawValue), kCRToastImageAlignmentKey: NSNumber(value: CRToastAccessoryViewAlignment.left.rawValue) ] //MARK:- Toast class func showToastMessage(_ message: String, messageType: ToastMessageType, timeInterval: TimeInterval? = nil, tabHandler: (() -> Void)? = nil) { var options : [AnyHashable: Any] = [kCRToastTextKey: message] switch messageType { case .info: options[kCRToastBackgroundColorKey] = UIColor(colorString: "E8E8E8") options[kCRToastImageKey] = UIImage(named:"toastInfo")! options[kCRToastTextColorKey] = UIColor.black case .error: options[kCRToastBackgroundColorKey] = UIColor(colorString: "E64C66") options[kCRToastImageKey] = UIImage(named:"toastError")! case .done: options[kCRToastBackgroundColorKey] = UIColor(colorString: "2CBA84") options[kCRToastImageKey] = UIImage(named:"toastCheckmark")! } if let timeInterval = timeInterval { options[kCRToastTimeIntervalKey] = timeInterval } if let tabHandler = tabHandler { let tapInteraction = CRToastInteractionResponder.init(interactionType: .tap, automaticallyDismiss: true) { (tap) in tabHandler() } options[kCRToastInteractionRespondersKey] = [tapInteraction] } // copy default options to the current options dictionary defaultOptions.forEach { options[$0] = $1 } DispatchQueue.main.async { CRToastManager.showNotification(options: options, completionBlock: nil) } } //MARK:- HUD class func showLoadingHUD(_ message: String) { DispatchQueue.main.async { SVProgressHUD.show(withStatus: message) } } class func dismissHUD() { DispatchQueue.main.async { SVProgressHUD.dismiss() } } }
mpl-2.0
e5fa9df35eb14e75e57c3836ee9080b4
35.011905
151
0.656198
4.92671
false
false
false
false
gregomni/swift
test/attr/attr_objc.swift
2
125638
// RUN: %empty-directory(%t) // RUN: %{python} %S/Inputs/access-note-gen.py %s %t/attr_objc_access_note.swift %t/attr_objc_access_note.accessnotes // Test with @objc attrs, without access notes // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -verify-ignore-unknown %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference // RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %s // RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t/attr_objc.ast // RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t/attr_objc.ast // Test without @objc attrs, with access notes // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -verify-ignore-unknown %t/attr_objc_access_note.swift -access-notes-path %t/attr_objc_access_note.accessnotes -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference // RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %t/attr_objc_access_note.swift -access-notes-path %t/attr_objc_access_note.accessnotes -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %t/attr_objc_access_note.swift // RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %t/attr_objc_access_note.swift -access-notes-path %t/attr_objc_access_note.accessnotes -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t/attr_objc_access_note.ast // RUN: %FileCheck -check-prefix CHECK-DUMP %t/attr_objc_access_note.swift < %t/attr_objc_access_note.ast // Test with both @objc attrs and access notes // RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -verify-ignore-unknown %s -access-notes-path %t/attr_objc_access_note.accessnotes -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference // RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -access-notes-path %t/attr_objc_access_note.accessnotes -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %s // RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -access-notes-path %t/attr_objc_access_note.accessnotes -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t/attr_objc_2.ast // RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t/attr_objc_2.ast // REQUIRES: objc_interop // HOW TO WORK ON THIS TEST // // This file is primarily used to test '@objc' in source files, but it is also // processed to produce test files for access notes, which can annotate // declarations with '@objc' based on a sidecar file. This processing produces // a source file with most of the '@objc' annotations removed, plus an access // note file which adds back the removed '@objc' annotations. The three files // are then tested in various combinations. // // The processing step uses the following special commands, which must appear // at the beginning of a line comment to be recognized: // // * `access-note-adjust @±offset` (where the offset is optional) modifies the // rest of the line comment to: // // 1. Change expected errors to expected remarks // 2. Adjust the line offsets of all expected diagnostics by the offset // 3. Change the phrase "marked @objc" to "marked @objc by an access note" // 4. Change all expected fix-its to "{{none}}" // // * `access-note-move @±offset {{name}}` (where the offset is optional) can // only appear immediately after an `@objc` or `@objc(someName)` attribute. // It removes the attribute from the source code, adds a corresponding // access note for `name` to the access note file, and does the same // processing to the rest of the line as access-note-adjust. Note that in this // case, the offset is @+1, not @+0, unless something else is specified. // // Note that, in some cases, we need additional access notes to be added that // don't directly correspond to any attribute in the source code (usually // because one @objc attribute covers several declarations). When this happens, // we write a commented-out @objc attribute and use the `access-note-move` // command. import Foundation class PlainClass {} struct PlainStruct {} enum PlainEnum {} protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}} enum ErrorEnum : Error { case failed } @objc // access-note-move{{Class_ObjC1}} class Class_ObjC1 {} protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}} protocol Protocol_Class2 : class {} @objc // access-note-move{{Protocol_ObjC1}} protocol Protocol_ObjC1 {} @objc // access-note-move{{Protocol_ObjC2}} protocol Protocol_ObjC2 {} //===--- Subjects of @objc attribute. @objc // expected-error{{'@objc' can only be applied to an extension of a class}}{{1-7=}} extension PlainStruct { } class FáncyName {} @objc(FancyName) extension FáncyName {} @objc // bad-access-note-move{{subject_globalVar}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} var subject_globalVar: Int var subject_getterSetter: Int { @objc // bad-access-note-move{{getter:subject_getterSetter()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} get { return 0 } @objc // bad-access-note-move{{setter:subject_getterSetter()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} set { } } var subject_global_observingAccessorsVar1: Int = 0 { @objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} willSet { } @objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} didSet { } } class subject_getterSetter1 { var instanceVar1: Int { @objc // bad-access-note-move{{getter:subject_getterSetter1.instanceVar1()}} expected-error {{'@objc' getter for non-'@objc' property}} {{5-11=}} get { return 0 } } var instanceVar2: Int { get { return 0 } @objc // bad-access-note-move{{setter:subject_getterSetter1.instanceVar2()}} expected-error {{'@objc' setter for non-'@objc' property}} {{5-11=}} set { } } var instanceVar3: Int { @objc // bad-access-note-move{{getter:subject_getterSetter1.instanceVar3()}} expected-error {{'@objc' getter for non-'@objc' property}} {{5-11=}} get { return 0 } @objc // bad-access-note-move{{setter:subject_getterSetter1.instanceVar3()}} expected-error {{'@objc' setter for non-'@objc' property}} {{5-11=}} set { } } var observingAccessorsVar1: Int = 0 { @objc // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-11=}} willSet { } @objc // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-11=}} didSet { } } } class subject_staticVar1 { @objc // access-note-move{{subject_staticVar1.staticVar1}} class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}} @objc // access-note-move{{subject_staticVar1.staticVar2}} class var staticVar2: Int { return 42 } } @objc // bad-access-note-move{{subject_freeFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-7=}} func subject_freeFunc() { @objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} var subject_localVar: Int // expected-warning@-1 {{variable 'subject_localVar' was never used; consider replacing with '_' or removing it}} @objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} func subject_nestedFreeFunc() { } } @objc // bad-access-note-move{{subject_genericFunc(t:)}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-7=}} func subject_genericFunc<T>(t: T) { @objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} var subject_localVar: Int // expected-warning@-1 {{variable 'subject_localVar' was never used; consider replacing with '_' or removing it}} @objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} func subject_instanceFunc() {} } func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}} } @objc // bad-access-note-move{{subject_struct}} expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}} struct subject_struct { @objc // bad-access-note-move{{subject_struct.subject_instanceVar}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} var subject_instanceVar: Int @objc // bad-access-note-move{{subject_struct.init()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} init() {} @objc // bad-access-note-move{{subject_struct.subject_instanceFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} func subject_instanceFunc() {} } @objc // bad-access-note-move{{subject_genericStruct}} expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}} struct subject_genericStruct<T> { @objc // bad-access-note-move{{subject_genericStruct.subject_instanceVar}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} var subject_instanceVar: Int @objc // bad-access-note-move{{subject_genericStruct.init()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} init() {} @objc // bad-access-note-move{{subject_genericStruct.subject_instanceFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} func subject_instanceFunc() {} } @objc // access-note-move{{subject_class1}} class subject_class1 { // no-error @objc // access-note-move{{subject_class1.subject_instanceVar}} var subject_instanceVar: Int // no-error @objc // access-note-move{{subject_class1.init()}} init() {} // no-error @objc // access-note-move{{subject_class1.subject_instanceFunc()}} func subject_instanceFunc() {} // no-error } @objc // access-note-move{{subject_class2}} class subject_class2 : Protocol_Class1, PlainProtocol { // no-error } @objc // bad-access-note-move{{subject_genericClass}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}} class subject_genericClass<T> { @objc // access-note-move{{subject_genericClass.subject_instanceVar}} var subject_instanceVar: Int // no-error @objc // access-note-move{{subject_genericClass.init()}} init() {} // no-error @objc // access-note-move{{subject_genericClass.subject_instanceFunc()}} func subject_instanceFunc() {} // no_error } @objc // bad-access-note-move{{subject_genericClass2}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}} class subject_genericClass2<T> : Class_ObjC1 { @objc // access-note-move{{subject_genericClass2.subject_instanceVar}} var subject_instanceVar: Int // no-error @objc // access-note-move{{subject_genericClass2.init(foo:)}} init(foo: Int) {} // no-error @objc // access-note-move{{subject_genericClass2.subject_instanceFunc()}} func subject_instanceFunc() {} // no_error } extension subject_genericClass where T : Hashable { @objc // bad-access-note-move{{subject_genericClass.prop}} var prop: Int { return 0 } // access-note-adjust{{@objc}} expected-error{{members of constrained extensions cannot be declared @objc}} } extension subject_genericClass { @objc // bad-access-note-move{{subject_genericClass.extProp}} var extProp: Int { return 0 } // access-note-adjust{{@objc}} expected-error{{extensions of generic classes cannot contain '@objc' members}} @objc // bad-access-note-move{{subject_genericClass.extFoo()}} func extFoo() {} // access-note-adjust{{@objc}} expected-error{{extensions of generic classes cannot contain '@objc' members}} } @objc // access-note-move{{subject_enum}} enum subject_enum: Int { @objc // bad-access-note-move{{subject_enum.subject_enumElement1}} expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}} case subject_enumElement1 @objc(subject_enumElement2) // access-note-move{{subject_enum.subject_enumElement2}} case subject_enumElement2 // Fake for access notes: @objc(subject_enumElement3) // bad-access-note-move@+2{{subject_enum.subject_enumElement4}} @objc(subject_enumElement3) // bad-access-note-move{{subject_enum.subject_enumElement3}} expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-31=}} case subject_enumElement3, subject_enumElement4 // Becuase of the fake access-note-move above, we expect to see extra diagnostics when we run this test with both explicit @objc attributes *and* access notes: // expected-remark@-2 * {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}} expected-note@-2 *{{attribute 'objc' was added by access note for fancy tests}} // Fake for access notes: @objc // bad-access-note-move@+2{{subject_enum.subject_enumElement6}} @objc // bad-access-note-move{{subject_enum.subject_enumElement5}} expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}} case subject_enumElement5, subject_enumElement6 // Becuase of the fake access-note-move above, we expect to see extra diagnostics when we run this test with both explicit @objc attributes *and* access notes: // expected-remark@-2 * {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} expected-note@-2 *{{attribute 'objc' was added by access note for fancy tests}} @nonobjc // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}} case subject_enumElement7 @objc // bad-access-note-move{{subject_enum.init()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} init() {} @objc // bad-access-note-move{{subject_enum.subject_instanceFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}} func subject_instanceFunc() {} } enum subject_enum2 { @objc(subject_enum2Element1) // bad-access-note-move{{subject_enum2.subject_enumElement1}} expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-32=}} case subject_enumElement1 } @objc // access-note-move{{subject_protocol1}} protocol subject_protocol1 { @objc // access-note-move{{subject_protocol1.subject_instanceVar}} var subject_instanceVar: Int { get } @objc // access-note-move{{subject_protocol1.subject_instanceFunc()}} func subject_instanceFunc() } @objc // access-note-move{{subject_protocol2}} // no-error protocol subject_protocol2 {} // CHECK-LABEL: @objc protocol subject_protocol2 { @objc // access-note-move{{subject_protocol3}} // no-error protocol subject_protocol3 {} // CHECK-LABEL: @objc protocol subject_protocol3 { @objc // access-note-move{{subject_protocol4}} protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}} @objc // access-note-move{{subject_protocol5}} protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}} @objc // access-note-move{{subject_protocol6}} protocol subject_protocol6 : Protocol_ObjC1 {} protocol subject_containerProtocol1 { @objc // bad-access-note-move{{subject_containerProtocol1.subject_instanceVar}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} var subject_instanceVar: Int { get } @objc // bad-access-note-move{{subject_containerProtocol1.subject_instanceFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} func subject_instanceFunc() @objc // bad-access-note-move{{subject_containerProtocol1.subject_staticFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} static func subject_staticFunc() } @objc // access-note-move{{subject_containerObjCProtocol1}} protocol subject_containerObjCProtocol1 { func func_FunctionReturn1() -> PlainStruct // expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} func func_FunctionParam1(a: PlainStruct) // expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} func func_Variadic(_: AnyObject...) // expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}} // expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}} subscript(a: PlainStruct) -> Int { get } // expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} var varNonObjC1: PlainStruct { get } // expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} } @objc // access-note-move{{subject_containerObjCProtocol2}} protocol subject_containerObjCProtocol2 { init(a: Int) // expected-note@-1 {{'init' previously declared here}} @objc // FIXME: Access notes can't distinguish between init(a:) overloads init(a: Double) // expected-warning@-1 {{initializer 'init(a:)' with Objective-C selector 'initWithA:' conflicts with previous declaration with the same Objective-C selector; this is an error in Swift 6}} func func1() -> Int @objc // access-note-move{{subject_containerObjCProtocol2.func1_()}} func func1_() -> Int var instanceVar1: Int { get set } @objc // access-note-move{{subject_containerObjCProtocol2.instanceVar1_}} var instanceVar1_: Int { get set } subscript(i: Int) -> Int { get set } @objc // FIXME: Access notes can't distinguish between subscript(_:) overloads subscript(i: String) -> Int { get set} } protocol nonObjCProtocol { @objc // bad-access-note-move{{nonObjCProtocol.objcRequirement()}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} func objcRequirement() } func concreteContext1() { @objc class subject_inConcreteContext {} } class ConcreteContext2 { @objc // access-note-move{{ConcreteContext2.subject_inConcreteContext}} class subject_inConcreteContext {} } class ConcreteContext3 { func dynamicSelf1() -> Self { return self } @objc // access-note-move{{ConcreteContext3.dynamicSelf1_()}} func dynamicSelf1_() -> Self { return self } @objc // bad-access-note-move{{ConcreteContext3.genericParams()}} func genericParams<T: NSObject>() -> [T] { return [] } // access-note-adjust{{@objc}} expected-error{{instance method cannot be marked @objc because it has generic parameters}} @objc // bad-access-note-move{{ConcreteContext3.returnObjCProtocolMetatype()}} func returnObjCProtocolMetatype() -> NSCoding.Protocol { return NSCoding.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} typealias AnotherNSCoding = NSCoding typealias MetaNSCoding1 = NSCoding.Protocol typealias MetaNSCoding2 = AnotherNSCoding.Protocol @objc // bad-access-note-move{{ConcreteContext3.returnObjCAliasProtocolMetatype1()}} func returnObjCAliasProtocolMetatype1() -> AnotherNSCoding.Protocol { return NSCoding.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} @objc // bad-access-note-move{{ConcreteContext3.returnObjCAliasProtocolMetatype2()}} func returnObjCAliasProtocolMetatype2() -> MetaNSCoding1 { return NSCoding.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} @objc // bad-access-note-move{{ConcreteContext3.returnObjCAliasProtocolMetatype3()}} func returnObjCAliasProtocolMetatype3() -> MetaNSCoding2 { return NSCoding.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} typealias Composition = NSCopying & NSCoding @objc // bad-access-note-move{{ConcreteContext3.returnCompositionMetatype1()}} func returnCompositionMetatype1() -> Composition.Protocol { return Composition.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} @objc // bad-access-note-move{{ConcreteContext3.returnCompositionMetatype2()}} func returnCompositionMetatype2() -> (NSCopying & NSCoding).Protocol { return (NSCopying & NSCoding).self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}} typealias NSCodingExistential = NSCoding.Type @objc // bad-access-note-move{{ConcreteContext3.inoutFunc(a:)}} func inoutFunc(a: inout Int) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because inout parameters cannot be represented in Objective-C}} @objc // bad-access-note-move{{ConcreteContext3.metatypeOfExistentialMetatypePram1(a:)}} func metatypeOfExistentialMetatypePram1(a: NSCodingExistential.Protocol) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} @objc // bad-access-note-move{{ConcreteContext3.metatypeOfExistentialMetatypePram2(a:)}} func metatypeOfExistentialMetatypePram2(a: NSCoding.Type.Protocol) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} } func genericContext1<T>(_: T) { @objc // expected-error {{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}} class subject_inGenericContext {} // expected-error {{type 'subject_inGenericContext' cannot be nested in generic function 'genericContext1'}} @objc // expected-error {{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}} class subject_inGenericContext2 : Class_ObjC1 {} // expected-error {{type 'subject_inGenericContext2' cannot be nested in generic function 'genericContext1'}} class subject_constructor_inGenericContext { // expected-error {{type 'subject_constructor_inGenericContext' cannot be nested in generic function 'genericContext1'}} @objc init() {} // no-error } class subject_var_inGenericContext { // expected-error {{type 'subject_var_inGenericContext' cannot be nested in generic function 'genericContext1'}} @objc var subject_instanceVar: Int = 0 // no-error } class subject_func_inGenericContext { // expected-error {{type 'subject_func_inGenericContext' cannot be nested in generic function 'genericContext1'}} @objc func f() {} // no-error } } class GenericContext2<T> { @objc // bad-access-note-move{{GenericContext2.subject_inGenericContext}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}} class subject_inGenericContext {} @objc // bad-access-note-move{{GenericContext2.subject_inGenericContext2}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}} class subject_inGenericContext2 : Class_ObjC1 {} @objc // access-note-move{{GenericContext2.f()}} func f() {} // no-error } class GenericContext3<T> { class MoreNested { @objc // bad-access-note-move{{GenericContext3.MoreNested.subject_inGenericContext}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{5-11=}} class subject_inGenericContext {} @objc // bad-access-note-move{{GenericContext3.MoreNested.subject_inGenericContext2}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{5-11=}} class subject_inGenericContext2 : Class_ObjC1 {} @objc // access-note-move{{GenericContext3.MoreNested.f()}} func f() {} // no-error } } class GenericContext4<T> { @objc // bad-access-note-move{{GenericContext4.foo()}} func foo() where T: Hashable { } // access-note-adjust{{@objc}} expected-error {{instance method cannot be marked @objc because it has a 'where' clause}} } @objc // bad-access-note-move{{ConcreteSubclassOfGeneric}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}} class ConcreteSubclassOfGeneric : GenericContext3<Int> {} extension ConcreteSubclassOfGeneric { @objc // access-note-move{{ConcreteSubclassOfGeneric.foo()}} func foo() {} // okay } @objc // bad-access-note-move{{ConcreteSubclassOfGeneric2}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}} class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {} extension ConcreteSubclassOfGeneric2 { @objc // access-note-move{{ConcreteSubclassOfGeneric2.foo()}} func foo() {} // okay } @objc(CustomNameForSubclassOfGeneric) // access-note-move{{ConcreteSubclassOfGeneric3}} no-error class ConcreteSubclassOfGeneric3 : GenericContext3<Int> {} extension ConcreteSubclassOfGeneric3 { @objc // access-note-move{{ConcreteSubclassOfGeneric3.foo()}} func foo() {} // okay } class subject_subscriptIndexed1 { @objc // access-note-move{{subject_subscriptIndexed1.subscript(_:)}} subscript(a: Int) -> Int { // no-error get { return 0 } } } class subject_subscriptIndexed2 { @objc // access-note-move{{subject_subscriptIndexed2.subscript(_:)}} subscript(a: Int8) -> Int { // no-error get { return 0 } } } class subject_subscriptIndexed3 { @objc // access-note-move{{subject_subscriptIndexed3.subscript(_:)}} subscript(a: UInt8) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed1 { @objc // access-note-move{{subject_subscriptKeyed1.subscript(_:)}} subscript(a: String) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed2 { @objc // access-note-move{{subject_subscriptKeyed2.subscript(_:)}} subscript(a: Class_ObjC1) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed3 { @objc // access-note-move{{subject_subscriptKeyed3.subscript(_:)}} subscript(a: Class_ObjC1.Type) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed4 { @objc // access-note-move{{subject_subscriptKeyed4.subscript(_:)}} subscript(a: Protocol_ObjC1) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed5 { @objc // access-note-move{{subject_subscriptKeyed5.subscript(_:)}} subscript(a: Protocol_ObjC1.Type) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed6 { @objc // access-note-move{{subject_subscriptKeyed6.subscript(_:)}} subscript(a: Protocol_ObjC1 & Protocol_ObjC2) -> Int { // no-error get { return 0 } } } class subject_subscriptKeyed7 { @objc // access-note-move{{subject_subscriptKeyed7.subscript(_:)}} subscript(a: (Protocol_ObjC1 & Protocol_ObjC2).Type) -> Int { // no-error get { return 0 } } } class subject_subscriptBridgedFloat { @objc // access-note-move{{subject_subscriptBridgedFloat.subscript(_:)}} subscript(a: Float32) -> Int { get { return 0 } } } class subject_subscriptGeneric<T> { @objc // access-note-move{{subject_subscriptGeneric.subscript(_:)}} subscript(a: Int) -> Int { // no-error get { return 0 } } } class subject_subscriptInvalid1 { @objc // bad-access-note-move{{subject_subscriptInvalid1.subscript(_:)}} class subscript(_ i: Int) -> AnyObject? { // access-note-adjust{{@objc}} expected-error {{class subscript cannot be marked @objc}} return nil } } class subject_subscriptInvalid2 { @objc // bad-access-note-move{{subject_subscriptInvalid2.subscript(_:)}} subscript(a: PlainClass) -> Int { // access-note-adjust{{@objc}} expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid3 { @objc // bad-access-note-move{{subject_subscriptInvalid3.subscript(_:)}} subscript(a: PlainClass.Type) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid4 { @objc // bad-access-note-move{{subject_subscriptInvalid4.subscript(_:)}} subscript(a: PlainStruct) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{Swift structs cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid5 { @objc // bad-access-note-move{{subject_subscriptInvalid5.subscript(_:)}} subscript(a: PlainEnum) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{enums cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid6 { @objc // bad-access-note-move{{subject_subscriptInvalid6.subscript(_:)}} subscript(a: PlainProtocol) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid7 { @objc // bad-access-note-move{{subject_subscriptInvalid7.subscript(_:)}} subscript(a: Protocol_Class1) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} get { return 0 } } } class subject_subscriptInvalid8 { @objc // bad-access-note-move{{subject_subscriptInvalid8.subscript(_:)}} subscript(a: Protocol_Class1 & Protocol_Class2) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} get { return 0 } } } class subject_propertyInvalid1 { @objc // bad-access-note-move{{subject_propertyInvalid1.plainStruct}} let plainStruct = PlainStruct() // access-note-adjust{{@objc}} expected-error {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-1{{Swift structs cannot be represented in Objective-C}} } //===--- Tests for @objc inference. @objc // access-note-move{{infer_instanceFunc1}} class infer_instanceFunc1 { // CHECK-LABEL: @objc class infer_instanceFunc1 { func func1() {} // CHECK-LABEL: @objc func func1() { @objc // access-note-move{{infer_instanceFunc1.func1_()}} func func1_() {} // no-error func func2(a: Int) {} // CHECK-LABEL: @objc func func2(a: Int) { @objc // access-note-move{{infer_instanceFunc1.func2_(a:)}} func func2_(a: Int) {} // no-error func func3(a: Int) -> Int {} // CHECK-LABEL: @objc func func3(a: Int) -> Int { @objc // access-note-move{{infer_instanceFunc1.func3_(a:)}} func func3_(a: Int) -> Int {} // no-error func func4(a: Int, b: Double) {} // CHECK-LABEL: @objc func func4(a: Int, b: Double) { @objc // access-note-move{{infer_instanceFunc1.func4_(a:b:)}} func func4_(a: Int, b: Double) {} // no-error func func5(a: String) {} // CHECK-LABEL: @objc func func5(a: String) { @objc // access-note-move{{infer_instanceFunc1.func5_(a:)}} func func5_(a: String) {} // no-error func func6() -> String {} // CHECK-LABEL: @objc func func6() -> String { @objc // access-note-move{{infer_instanceFunc1.func6_()}} func func6_() -> String {} // no-error func func7(a: PlainClass) {} // CHECK-LABEL: {{^}} func func7(a: PlainClass) { @objc // bad-access-note-move{{infer_instanceFunc1.func7_(a:)}} func func7_(a: PlainClass) {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} func func7m(a: PlainClass.Type) {} // CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) { @objc // bad-access-note-move{{infer_instanceFunc1.func7m_(a:)}} func func7m_(a: PlainClass.Type) {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} func func8() -> PlainClass {} // CHECK-LABEL: {{^}} func func8() -> PlainClass { @objc // bad-access-note-move{{infer_instanceFunc1.func8_()}} func func8_() -> PlainClass {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} func func8m() -> PlainClass.Type {} // CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type { @objc // bad-access-note-move{{infer_instanceFunc1.func8m_()}} func func8m_() -> PlainClass.Type {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} func func9(a: PlainStruct) {} // CHECK-LABEL: {{^}} func func9(a: PlainStruct) { @objc // bad-access-note-move{{infer_instanceFunc1.func9_(a:)}} func func9_(a: PlainStruct) {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} func func10() -> PlainStruct {} // CHECK-LABEL: {{^}} func func10() -> PlainStruct { @objc // bad-access-note-move{{infer_instanceFunc1.func10_()}} func func10_() -> PlainStruct {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} func func11(a: PlainEnum) {} // CHECK-LABEL: {{^}} func func11(a: PlainEnum) { @objc // bad-access-note-move{{infer_instanceFunc1.func11_(a:)}} func func11_(a: PlainEnum) {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}} func func12(a: PlainProtocol) {} // CHECK-LABEL: {{^}} func func12(a: PlainProtocol) { @objc // bad-access-note-move{{infer_instanceFunc1.func12_(a:)}} func func12_(a: PlainProtocol) {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} func func13(a: Class_ObjC1) {} // CHECK-LABEL: @objc func func13(a: Class_ObjC1) { @objc // access-note-move{{infer_instanceFunc1.func13_(a:)}} func func13_(a: Class_ObjC1) {} // no-error func func14(a: Protocol_Class1) {} // CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) { @objc // bad-access-note-move{{infer_instanceFunc1.func14_(a:)}} func func14_(a: Protocol_Class1) {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} func func15(a: Protocol_ObjC1) {} // CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) { @objc // access-note-move{{infer_instanceFunc1.func15_(a:)}} func func15_(a: Protocol_ObjC1) {} // no-error func func16(a: AnyObject) {} // CHECK-LABEL: @objc func func16(a: AnyObject) { @objc // access-note-move{{infer_instanceFunc1.func16_(a:)}} func func16_(a: AnyObject) {} // no-error func func17(a: @escaping () -> ()) {} // CHECK-LABEL: {{^}} @objc func func17(a: @escaping () -> ()) { @objc // access-note-move{{infer_instanceFunc1.func17_(a:)}} func func17_(a: @escaping () -> ()) {} func func18(a: @escaping (Int) -> (), b: Int) {} // CHECK-LABEL: {{^}} @objc func func18(a: @escaping (Int) -> (), b: Int) @objc // access-note-move{{infer_instanceFunc1.func18_(a:b:)}} func func18_(a: @escaping (Int) -> (), b: Int) {} func func19(a: @escaping (String) -> (), b: Int) {} // CHECK-LABEL: {{^}} @objc func func19(a: @escaping (String) -> (), b: Int) { @objc // access-note-move{{infer_instanceFunc1.func19_(a:b:)}} func func19_(a: @escaping (String) -> (), b: Int) {} func func_FunctionReturn1() -> () -> () {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () { @objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn1_()}} func func_FunctionReturn1_() -> () -> () {} func func_FunctionReturn2() -> (Int) -> () {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () { @objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn2_()}} func func_FunctionReturn2_() -> (Int) -> () {} func func_FunctionReturn3() -> () -> Int {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int { @objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn3_()}} func func_FunctionReturn3_() -> () -> Int {} func func_FunctionReturn4() -> (String) -> () {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () { @objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn4_()}} func func_FunctionReturn4_() -> (String) -> () {} func func_FunctionReturn5() -> () -> String {} // CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String { @objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn5_()}} func func_FunctionReturn5_() -> () -> String {} func func_ZeroParams1() {} // CHECK-LABEL: @objc func func_ZeroParams1() { @objc // access-note-move{{infer_instanceFunc1.func_ZeroParams1a()}} func func_ZeroParams1a() {} // no-error func func_OneParam1(a: Int) {} // CHECK-LABEL: @objc func func_OneParam1(a: Int) { @objc // access-note-move{{infer_instanceFunc1.func_OneParam1a(a:)}} func func_OneParam1a(a: Int) {} // no-error func func_TupleStyle1(a: Int, b: Int) {} // CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) { @objc // access-note-move{{infer_instanceFunc1.func_TupleStyle1a(a:b:)}} func func_TupleStyle1a(a: Int, b: Int) {} func func_TupleStyle2(a: Int, b: Int, c: Int) {} // CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) { @objc // access-note-move{{infer_instanceFunc1.func_TupleStyle2a(a:b:c:)}} func func_TupleStyle2a(a: Int, b: Int, c: Int) {} // Check that we produce diagnostics for every parameter and return type. @objc // bad-access-note-move{{infer_instanceFunc1.func_MultipleDiags(a:b:)}} func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> Any {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // access-note-adjust{{@objc}} expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}} // expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}} // Produces an extra: expected-note@-5 * {{attribute 'objc' was added by access note for fancy tests}} @objc // access-note-move{{infer_instanceFunc1.func_UnnamedParam1(_:)}} func func_UnnamedParam1(_: Int) {} // no-error @objc // bad-access-note-move{{infer_instanceFunc1.func_UnnamedParam2(_:)}} func func_UnnamedParam2(_: PlainStruct) {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} @objc // access-note-move{{infer_instanceFunc1.func_varParam1(a:)}} func func_varParam1(a: AnyObject) { var a = a let b = a; a = b } func func_varParam2(a: AnyObject) { var a = a let b = a; a = b } // CHECK-LABEL: @objc func func_varParam2(a: AnyObject) { } @objc // access-note-move{{infer_constructor1}} class infer_constructor1 { // CHECK-LABEL: @objc class infer_constructor1 init() {} // CHECK: @objc init() init(a: Int) {} // CHECK: @objc init(a: Int) init(a: PlainStruct) {} // CHECK: {{^}} init(a: PlainStruct) init(malice: ()) {} // CHECK: @objc init(malice: ()) init(forMurder _: ()) {} // CHECK: @objc init(forMurder _: ()) } @objc // access-note-move{{infer_destructor1}} class infer_destructor1 { // CHECK-LABEL: @objc class infer_destructor1 deinit {} // CHECK: @objc deinit } // @!objc class infer_destructor2 { // CHECK-LABEL: {{^}}class infer_destructor2 deinit {} // CHECK: @objc deinit } @objc // access-note-move{{infer_instanceVar1}} class infer_instanceVar1 { // CHECK-LABEL: @objc class infer_instanceVar1 { init() {} var instanceVar1: Int // CHECK: @objc var instanceVar1: Int var (instanceVar2, instanceVar3): (Int, PlainProtocol) // CHECK: @objc var instanceVar2: Int // CHECK: {{^}} var instanceVar3: PlainProtocol @objc // bad-access-note-move{{infer_instanceVar1.instanceVar1_}} var (instanceVar1_, instanceVar2_): (Int, PlainProtocol) // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} // Fake for access notes: @objc // access-note-move@-3{{infer_instanceVar1.instanceVar2_}} var intstanceVar4: Int { // CHECK: @objc var intstanceVar4: Int { get {} // CHECK-NEXT: @objc get {} } var intstanceVar5: Int { // CHECK: @objc var intstanceVar5: Int { get {} // CHECK-NEXT: @objc get {} set {} // CHECK-NEXT: @objc set {} } @objc // access-note-move{{infer_instanceVar1.instanceVar5_}} var instanceVar5_: Int { // CHECK: @objc var instanceVar5_: Int { get {} // CHECK-NEXT: @objc get {} set {} // CHECK-NEXT: @objc set {} } var observingAccessorsVar1: Int { // CHECK: @_hasStorage @objc var observingAccessorsVar1: Int { willSet {} // CHECK-NEXT: {{^}} @objc get { // CHECK-NEXT: return // CHECK-NEXT: } didSet {} // CHECK-NEXT: {{^}} @objc set { } @objc // access-note-move{{infer_instanceVar1.observingAccessorsVar1_}} var observingAccessorsVar1_: Int { // CHECK: {{^}} @objc @_hasStorage var observingAccessorsVar1_: Int { willSet {} // CHECK-NEXT: {{^}} @objc get { // CHECK-NEXT: return // CHECK-NEXT: } didSet {} // CHECK-NEXT: {{^}} @objc set { } var var_Int: Int // CHECK-LABEL: @objc var var_Int: Int var var_Bool: Bool // CHECK-LABEL: @objc var var_Bool: Bool var var_CBool: CBool // CHECK-LABEL: @objc var var_CBool: CBool var var_String: String // CHECK-LABEL: @objc var var_String: String var var_Float: Float var var_Double: Double // CHECK-LABEL: @objc var var_Float: Float // CHECK-LABEL: @objc var var_Double: Double var var_Char: Unicode.Scalar // CHECK-LABEL: @objc var var_Char: Unicode.Scalar //===--- Tuples. var var_tuple1: () // CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple1: () @objc // bad-access-note-move{{infer_instanceVar1.var_tuple1_}} var var_tuple1_: () // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{empty tuple type cannot be represented in Objective-C}} var var_tuple2: Void // CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple2: Void @objc // bad-access-note-move{{infer_instanceVar1.var_tuple2_}} var var_tuple2_: Void // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{empty tuple type cannot be represented in Objective-C}} var var_tuple3: (Int) // CHECK-LABEL: @objc var var_tuple3: (Int) @objc // access-note-move{{infer_instanceVar1.var_tuple3_}} var var_tuple3_: (Int) // no-error var var_tuple4: (Int, Int) // CHECK-LABEL: {{^}} var var_tuple4: (Int, Int) @objc // bad-access-note-move{{infer_instanceVar1.var_tuple4_}} var var_tuple4_: (Int, Int) // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{tuples cannot be represented in Objective-C}} //===--- Stdlib integer types. var var_Int8: Int8 var var_Int16: Int16 var var_Int32: Int32 var var_Int64: Int64 // CHECK-LABEL: @objc var var_Int8: Int8 // CHECK-LABEL: @objc var var_Int16: Int16 // CHECK-LABEL: @objc var var_Int32: Int32 // CHECK-LABEL: @objc var var_Int64: Int64 var var_UInt8: UInt8 var var_UInt16: UInt16 var var_UInt32: UInt32 var var_UInt64: UInt64 // CHECK-LABEL: @objc var var_UInt8: UInt8 // CHECK-LABEL: @objc var var_UInt16: UInt16 // CHECK-LABEL: @objc var var_UInt32: UInt32 // CHECK-LABEL: @objc var var_UInt64: UInt64 var var_OpaquePointer: OpaquePointer // CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer var var_PlainClass: PlainClass // CHECK-LABEL: {{^}} var var_PlainClass: PlainClass @objc // bad-access-note-move{{infer_instanceVar1.var_PlainClass_}} var var_PlainClass_: PlainClass // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}} var var_PlainStruct: PlainStruct // CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct @objc // bad-access-note-move{{infer_instanceVar1.var_PlainStruct_}} var var_PlainStruct_: PlainStruct // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} var var_PlainEnum: PlainEnum // CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum @objc // bad-access-note-move{{infer_instanceVar1.var_PlainEnum_}} var var_PlainEnum_: PlainEnum // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}} var var_PlainProtocol: PlainProtocol // CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol @objc // bad-access-note-move{{infer_instanceVar1.var_PlainProtocol_}} var var_PlainProtocol_: PlainProtocol // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_ClassObjC: Class_ObjC1 // CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1 @objc // access-note-move{{infer_instanceVar1.var_ClassObjC_}} var var_ClassObjC_: Class_ObjC1 // no-error var var_ProtocolClass: Protocol_Class1 // CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1 @objc // bad-access-note-move{{infer_instanceVar1.var_ProtocolClass_}} var var_ProtocolClass_: Protocol_Class1 // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} var var_ProtocolObjC: Protocol_ObjC1 // CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1 @objc // access-note-move{{infer_instanceVar1.var_ProtocolObjC_}} var var_ProtocolObjC_: Protocol_ObjC1 // no-error var var_PlainClassMetatype: PlainClass.Type // CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type @objc // bad-access-note-move{{infer_instanceVar1.var_PlainClassMetatype_}} var var_PlainClassMetatype_: PlainClass.Type // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_PlainStructMetatype: PlainStruct.Type // CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type @objc // bad-access-note-move{{infer_instanceVar1.var_PlainStructMetatype_}} var var_PlainStructMetatype_: PlainStruct.Type // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_PlainEnumMetatype: PlainEnum.Type // CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type @objc // bad-access-note-move{{infer_instanceVar1.var_PlainEnumMetatype_}} var var_PlainEnumMetatype_: PlainEnum.Type // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_PlainExistentialMetatype: PlainProtocol.Type // CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type @objc // bad-access-note-move{{infer_instanceVar1.var_PlainExistentialMetatype_}} var var_PlainExistentialMetatype_: PlainProtocol.Type // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ClassObjCMetatype: Class_ObjC1.Type // CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type @objc // access-note-move{{infer_instanceVar1.var_ClassObjCMetatype_}} var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error var var_ProtocolClassMetatype: Protocol_Class1.Type // CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type @objc // bad-access-note-move{{infer_instanceVar1.var_ProtocolClassMetatype_}} var var_ProtocolClassMetatype_: Protocol_Class1.Type // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type // CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type @objc // access-note-move{{infer_instanceVar1.var_ProtocolObjCMetatype1_}} var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type // CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type @objc // access-note-move{{infer_instanceVar1.var_ProtocolObjCMetatype2_}} var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error var var_AnyObject1: AnyObject var var_AnyObject2: AnyObject.Type // CHECK-LABEL: @objc var var_AnyObject1: AnyObject // CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type var var_Existential0: Any // CHECK-LABEL: @objc var var_Existential0: Any @objc // access-note-move{{infer_instanceVar1.var_Existential0_}} var var_Existential0_: Any var var_Existential1: PlainProtocol // CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol @objc // bad-access-note-move{{infer_instanceVar1.var_Existential1_}} var var_Existential1_: PlainProtocol // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_Existential2: PlainProtocol & PlainProtocol // CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol @objc // bad-access-note-move{{infer_instanceVar1.var_Existential2_}} var var_Existential2_: PlainProtocol & PlainProtocol // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_Existential3: PlainProtocol & Protocol_Class1 // CHECK-LABEL: {{^}} var var_Existential3: PlainProtocol & Protocol_Class1 @objc // bad-access-note-move{{infer_instanceVar1.var_Existential3_}} var var_Existential3_: PlainProtocol & Protocol_Class1 // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_Existential4: PlainProtocol & Protocol_ObjC1 // CHECK-LABEL: {{^}} var var_Existential4: PlainProtocol & Protocol_ObjC1 @objc // bad-access-note-move{{infer_instanceVar1.var_Existential4_}} var var_Existential4_: PlainProtocol & Protocol_ObjC1 // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}} var var_Existential5: Protocol_Class1 // CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1 @objc // bad-access-note-move{{infer_instanceVar1.var_Existential5_}} var var_Existential5_: Protocol_Class1 // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} var var_Existential6: Protocol_Class1 & Protocol_Class2 // CHECK-LABEL: {{^}} var var_Existential6: Protocol_Class1 & Protocol_Class2 @objc // bad-access-note-move{{infer_instanceVar1.var_Existential6_}} var var_Existential6_: Protocol_Class1 & Protocol_Class2 // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1 // CHECK-LABEL: {{^}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1 @objc // bad-access-note-move{{infer_instanceVar1.var_Existential7_}} var var_Existential7_: Protocol_Class1 & Protocol_ObjC1 // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}} var var_Existential8: Protocol_ObjC1 // CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1 @objc // access-note-move{{infer_instanceVar1.var_Existential8_}} var var_Existential8_: Protocol_ObjC1 // no-error var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2 // CHECK-LABEL: @objc var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2 @objc // access-note-move{{infer_instanceVar1.var_Existential9_}} var var_Existential9_: Protocol_ObjC1 & Protocol_ObjC2 // no-error var var_ExistentialMetatype0: Any.Type var var_ExistentialMetatype1: PlainProtocol.Type var var_ExistentialMetatype2: (PlainProtocol & PlainProtocol).Type var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type var var_ExistentialMetatype5: (Protocol_Class1).Type var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type var var_ExistentialMetatype8: Protocol_ObjC1.Type var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype0: Any.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype2: (PlainProtocol).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype5: (Protocol_Class1).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type // CHECK-LABEL: {{^}} var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type // CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type // CHECK-LABEL: @objc var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int> var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool> var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool> var var_UnsafeMutablePointer4: UnsafeMutablePointer<String> var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float> var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double> var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer> var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass> var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct> var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum> var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol> var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject> var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type> var var_UnsafeMutablePointer100: UnsafeMutableRawPointer var var_UnsafeMutablePointer101: UnsafeMutableRawPointer var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)> // CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int> // CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool> // CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String> // CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float> // CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double> // CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum> // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol> // CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject> // CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type> // CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutableRawPointer // CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutableRawPointer // CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)> var var_Optional1: Class_ObjC1? var var_Optional2: Protocol_ObjC1? var var_Optional3: Class_ObjC1.Type? var var_Optional4: Protocol_ObjC1.Type? var var_Optional5: AnyObject? var var_Optional6: AnyObject.Type? var var_Optional7: String? var var_Optional8: Protocol_ObjC1? var var_Optional9: Protocol_ObjC1.Type? var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)? var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type? var var_Optional12: OpaquePointer? var var_Optional13: UnsafeMutablePointer<Int>? var var_Optional14: UnsafeMutablePointer<Class_ObjC1>? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional1: Class_ObjC1? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional2: Protocol_ObjC1? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional3: Class_ObjC1.Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional4: Protocol_ObjC1.Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional5: AnyObject? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional6: AnyObject.Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional7: String? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional8: Protocol_ObjC1? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional9: Protocol_ObjC1.Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional12: OpaquePointer? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional13: UnsafeMutablePointer<Int>? // CHECK-LABEL: @objc @_hasInitialValue var var_Optional14: UnsafeMutablePointer<Class_ObjC1>? var var_ImplicitlyUnwrappedOptional1: Class_ObjC1! var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1! var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type! var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type! var var_ImplicitlyUnwrappedOptional5: AnyObject! var var_ImplicitlyUnwrappedOptional6: AnyObject.Type! var var_ImplicitlyUnwrappedOptional7: String! var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1! var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional1: Class_ObjC1! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional5: AnyObject! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional6: AnyObject.Type! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional7: String! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1! // CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)! var var_Optional_fail1: PlainClass? var var_Optional_fail2: PlainClass.Type? var var_Optional_fail3: PlainClass! var var_Optional_fail4: PlainStruct? var var_Optional_fail5: PlainStruct.Type? var var_Optional_fail6: PlainEnum? var var_Optional_fail7: PlainEnum.Type? var var_Optional_fail8: PlainProtocol? var var_Optional_fail10: PlainProtocol? var var_Optional_fail11: (PlainProtocol & Protocol_ObjC1)? var var_Optional_fail12: Int? var var_Optional_fail13: Bool? var var_Optional_fail14: CBool? var var_Optional_fail20: AnyObject?? var var_Optional_fail21: AnyObject.Type?? var var_Optional_fail22: ComparisonResult? // a non-bridged imported value type var var_Optional_fail23: NSRange? // a bridged struct imported from C // CHECK-NOT: @objc{{.*}}Optional_fail // CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> () var var_CFunctionPointer_1: @convention(c) () -> () // CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}} // CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: <<error type>> var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int // expected-error {{'(PlainStruct) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}} // <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}} weak var var_Weak1: Class_ObjC1? weak var var_Weak2: Protocol_ObjC1? // <rdar://problem/16473062> weak and unowned variables of metatypes are rejected //weak var var_Weak3: Class_ObjC1.Type? //weak var var_Weak4: Protocol_ObjC1.Type? weak var var_Weak5: AnyObject? //weak var var_Weak6: AnyObject.Type? weak var var_Weak7: Protocol_ObjC1? weak var var_Weak8: (Protocol_ObjC1 & Protocol_ObjC2)? // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak1: @sil_weak Class_ObjC1 // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak2: @sil_weak Protocol_ObjC1 // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak5: @sil_weak AnyObject // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak7: @sil_weak Protocol_ObjC1 // CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak8: @sil_weak (Protocol_ObjC1 & Protocol_ObjC2)? weak var var_Weak_fail1: PlainClass? weak var var_Weak_bad2: PlainStruct? // expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}} weak var var_Weak_bad3: PlainEnum? // expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}} weak var var_Weak_bad4: String? // expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}} // CHECK-NOT: @objc{{.*}}Weak_fail unowned var var_Unowned1: Class_ObjC1 unowned var var_Unowned2: Protocol_ObjC1 // <rdar://problem/16473062> weak and unowned variables of metatypes are rejected //unowned var var_Unowned3: Class_ObjC1.Type //unowned var var_Unowned4: Protocol_ObjC1.Type unowned var var_Unowned5: AnyObject //unowned var var_Unowned6: AnyObject.Type unowned var var_Unowned7: Protocol_ObjC1 unowned var var_Unowned8: Protocol_ObjC1 & Protocol_ObjC2 // CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1 // CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1 // CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject // CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1 // CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned Protocol_ObjC1 & Protocol_ObjC2 unowned var var_Unowned_fail1: PlainClass unowned var var_Unowned_bad2: PlainStruct // expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}} unowned var var_Unowned_bad3: PlainEnum // expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}} unowned var var_Unowned_bad4: String // expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}} // CHECK-NOT: @objc{{.*}}Unowned_fail var var_FunctionType1: () -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> () var var_FunctionType2: (Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> () var var_FunctionType3: (Int) -> Int // CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int var var_FunctionType4: (Int, Double) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> () var var_FunctionType5: (String) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> () var var_FunctionType6: () -> String // CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String var var_FunctionType7: (PlainClass) -> () // CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> () var var_FunctionType8: () -> PlainClass // CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass var var_FunctionType9: (PlainStruct) -> () // CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> () var var_FunctionType10: () -> PlainStruct // CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct var var_FunctionType11: (PlainEnum) -> () // CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> () var var_FunctionType12: (PlainProtocol) -> () // CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> () var var_FunctionType13: (Class_ObjC1) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> () var var_FunctionType14: (Protocol_Class1) -> () // CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> () var var_FunctionType15: (Protocol_ObjC1) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> () var var_FunctionType16: (AnyObject) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> () var var_FunctionType17: (() -> ()) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> () var var_FunctionType18: ((Int) -> (), Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> () var var_FunctionType19: ((String) -> (), Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> () var var_FunctionTypeReturn1: () -> () -> () // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> () @objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn1_}} var var_FunctionTypeReturn1_: () -> () -> () // no-error var var_FunctionTypeReturn2: () -> (Int) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> () @objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn2_}} var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error var var_FunctionTypeReturn3: () -> () -> Int // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int @objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn3_}} var var_FunctionTypeReturn3_: () -> () -> Int // no-error var var_FunctionTypeReturn4: () -> (String) -> () // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> () @objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn4_}} var var_FunctionTypeReturn4_: () -> (String) -> () // no-error var var_FunctionTypeReturn5: () -> () -> String // CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String @objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn5_}} var var_FunctionTypeReturn5_: () -> () -> String // no-error var var_BlockFunctionType1: @convention(block) () -> () // CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> () @objc // access-note-move{{infer_instanceVar1.var_BlockFunctionType1_}} var var_BlockFunctionType1_: @convention(block) () -> () // no-error var var_ArrayType1: [AnyObject] // CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject] @objc // access-note-move{{infer_instanceVar1.var_ArrayType1_}} var var_ArrayType1_: [AnyObject] // no-error var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] // no-error // CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] @objc // access-note-move{{infer_instanceVar1.var_ArrayType2_}} var var_ArrayType2_: [@convention(block) (AnyObject) -> AnyObject] // no-error var var_ArrayType3: [PlainStruct] // CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct] @objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType3_}} var var_ArrayType3_: [PlainStruct] // access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType4: [(AnyObject) -> AnyObject] // no-error // CHECK-LABEL: {{^}} var var_ArrayType4: [(AnyObject) -> AnyObject] @objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType4_}} var var_ArrayType4_: [(AnyObject) -> AnyObject] // access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType5: [Protocol_ObjC1] // CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1] @objc // access-note-move{{infer_instanceVar1.var_ArrayType5_}} var var_ArrayType5_: [Protocol_ObjC1] // no-error var var_ArrayType6: [Class_ObjC1] // CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1] @objc // access-note-move{{infer_instanceVar1.var_ArrayType6_}} var var_ArrayType6_: [Class_ObjC1] // no-error var var_ArrayType7: [PlainClass] // CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass] @objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType7_}} var var_ArrayType7_: [PlainClass] // access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType8: [PlainProtocol] // CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol] @objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType8_}} var var_ArrayType8_: [PlainProtocol] // access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType9: [Protocol_ObjC1 & PlainProtocol] // CHECK-LABEL: {{^}} var var_ArrayType9: [PlainProtocol & Protocol_ObjC1] @objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType9_}} var var_ArrayType9_: [Protocol_ObjC1 & PlainProtocol] // access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2] // CHECK-LABEL: {{^}} @objc var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2] @objc // access-note-move{{infer_instanceVar1.var_ArrayType10_}} var var_ArrayType10_: [Protocol_ObjC1 & Protocol_ObjC2] // no-error var var_ArrayType11: [Any] // CHECK-LABEL: @objc var var_ArrayType11: [Any] @objc // access-note-move{{infer_instanceVar1.var_ArrayType11_}} var var_ArrayType11_: [Any] var var_ArrayType13: [Any?] // CHECK-LABEL: {{^}} var var_ArrayType13: [Any?] @objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType13_}} var var_ArrayType13_: [Any?] // access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType15: [AnyObject?] // CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?] @objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType15_}} var var_ArrayType15_: [AnyObject?] // access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} var var_ArrayType16: [[@convention(block) (AnyObject) -> AnyObject]] // no-error // CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) (AnyObject) -> AnyObject]] @objc // access-note-move{{infer_instanceVar1.var_ArrayType16_}} var var_ArrayType16_: [[@convention(block) (AnyObject) -> AnyObject]] // no-error var var_ArrayType17: [[(AnyObject) -> AnyObject]] // no-error // CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[(AnyObject) -> AnyObject]] @objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType17_}} var var_ArrayType17_: [[(AnyObject) -> AnyObject]] // access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}} } @objc // access-note-move{{ObjCBase}} class ObjCBase {} class infer_instanceVar2< GP_Unconstrained, GP_PlainClass : PlainClass, GP_PlainProtocol : PlainProtocol, GP_Class_ObjC : Class_ObjC1, GP_Protocol_Class : Protocol_Class1, GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase { // CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase where {{.*}} { override init() {} var var_GP_Unconstrained: GP_Unconstrained // CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained @objc // bad-access-note-move{{infer_instanceVar2.var_GP_Unconstrained_}} var var_GP_Unconstrained_: GP_Unconstrained // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_PlainClass: GP_PlainClass // CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass @objc // bad-access-note-move{{infer_instanceVar2.var_GP_PlainClass_}} var var_GP_PlainClass_: GP_PlainClass // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_PlainProtocol: GP_PlainProtocol // CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol @objc // bad-access-note-move{{infer_instanceVar2.var_GP_PlainProtocol_}} var var_GP_PlainProtocol_: GP_PlainProtocol // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_Class_ObjC: GP_Class_ObjC // CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC @objc // bad-access-note-move{{infer_instanceVar2.var_GP_Class_ObjC_}} var var_GP_Class_ObjC_: GP_Class_ObjC // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_Protocol_Class: GP_Protocol_Class // CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class @objc // bad-access-note-move{{infer_instanceVar2.var_GP_Protocol_Class_}} var var_GP_Protocol_Class_: GP_Protocol_Class // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC // CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC @objc // bad-access-note-move{{infer_instanceVar2.var_GP_Protocol_ObjCa}} var var_GP_Protocol_ObjCa: GP_Protocol_ObjC // access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} func func_GP_Unconstrained(a: GP_Unconstrained) {} // CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) { @objc // bad-access-note-move{{infer_instanceVar2.func_GP_Unconstrained_(a:)}} func func_GP_Unconstrained_(a: GP_Unconstrained) {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} @objc // bad-access-note-move{{infer_instanceVar2.func_GP_Unconstrained_()}} func func_GP_Unconstrained_() -> GP_Unconstrained {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} @objc // bad-access-note-move{{infer_instanceVar2.func_GP_Class_ObjC__()}} func func_GP_Class_ObjC__() -> GP_Class_ObjC {} // access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}} // expected-note@-2 {{generic type parameters cannot be represented in Objective-C}} } class infer_instanceVar3 : Class_ObjC1 { // CHECK-LABEL: @objc @_inheritsConvenienceInitializers class infer_instanceVar3 : Class_ObjC1 { var v1: Int = 0 // CHECK-LABEL: @objc @_hasInitialValue var v1: Int } @objc // access-note-move{{infer_instanceVar4}} protocol infer_instanceVar4 { // CHECK-LABEL: @objc protocol infer_instanceVar4 { var v1: Int { get } // CHECK-LABEL: @objc var v1: Int { get } } // @!objc class infer_instanceVar5 { // CHECK-LABEL: {{^}}class infer_instanceVar5 { @objc // access-note-move{{infer_instanceVar5.intstanceVar1}} var intstanceVar1: Int { // CHECK: @objc var intstanceVar1: Int get {} // CHECK: @objc get {} set {} // CHECK: @objc set {} } } @objc // access-note-move{{infer_staticVar1}} class infer_staticVar1 { // CHECK-LABEL: @objc class infer_staticVar1 { class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}} // CHECK: @objc @_hasInitialValue class var staticVar1: Int } // @!objc class infer_subscript1 { // CHECK-LABEL: class infer_subscript1 @objc // access-note-move{{infer_subscript1.subscript(_:)}} subscript(i: Int) -> Int { // CHECK: @objc subscript(i: Int) -> Int get {} // CHECK: @objc get {} set {} // CHECK: @objc set {} } } @objc // access-note-move{{infer_throughConformanceProto1}} protocol infer_throughConformanceProto1 { // CHECK-LABEL: @objc protocol infer_throughConformanceProto1 { func funcObjC1() var varObjC1: Int { get } var varObjC2: Int { get set } // CHECK: @objc func funcObjC1() // CHECK: @objc var varObjC1: Int { get } // CHECK: @objc var varObjC2: Int { get set } } class infer_class1 : PlainClass {} // CHECK-LABEL: {{^}}@_inheritsConvenienceInitializers class infer_class1 : PlainClass { class infer_class2 : Class_ObjC1 {} // CHECK-LABEL: @objc @_inheritsConvenienceInitializers class infer_class2 : Class_ObjC1 { class infer_class3 : infer_class2 {} // CHECK-LABEL: @objc @_inheritsConvenienceInitializers class infer_class3 : infer_class2 { class infer_class4 : Protocol_Class1 {} // CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 { class infer_class5 : Protocol_ObjC1 {} // CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 { // // If a protocol conforms to an @objc protocol, this does not infer @objc on // the protocol itself, or on the newly introduced requirements. Only the // inherited @objc requirements get @objc. // // Same rule applies to classes. // protocol infer_protocol1 { // CHECK-LABEL: {{^}}protocol infer_protocol1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol2 : Protocol_Class1 { // CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol3 : Protocol_ObjC1 { // CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 { // CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 { // CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_Class1, Protocol_ObjC1 { func nonObjC1() // CHECK: {{^}} func nonObjC1() } class C { // Don't crash. @objc func foo(x: Undeclared) {} // expected-error {{cannot find type 'Undeclared' in scope}} @IBAction func myAction(sender: Undeclared) {} // expected-error {{cannot find type 'Undeclared' in scope}} @IBSegueAction func myAction(coder: Undeclared, sender: Undeclared) -> Undeclared {fatalError()} // expected-error {{cannot find type 'Undeclared' in scope}} expected-error {{cannot find type 'Undeclared' in scope}} expected-error {{cannot find type 'Undeclared' in scope}} } //===--- //===--- @IBOutlet implies @objc //===--- class HasIBOutlet { // CHECK-LABEL: {{^}}class HasIBOutlet { init() {} @IBOutlet weak var goodOutlet: Class_ObjC1! // CHECK-LABEL: {{^}} @objc @IBOutlet @_hasInitialValue weak var goodOutlet: @sil_weak Class_ObjC1! @IBOutlet var badOutlet: PlainStruct // expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}} // expected-error@-2 {{@IBOutlet property has non-optional type 'PlainStruct'}} // expected-note@-3 {{add '?' to form the optional type 'PlainStruct?'}} // expected-note@-4 {{add '!' to form an implicitly unwrapped optional}} // CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct } //===--- //===--- @IBAction implies @objc //===--- // CHECK-LABEL: {{^}}class HasIBAction { class HasIBAction { @IBAction func goodAction(_ sender: AnyObject?) { } // CHECK: {{^}} @objc @IBAction @MainActor func goodAction(_ sender: AnyObject?) { @IBAction func badAction(_ sender: PlainStruct?) { } // expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}} } //===--- //===--- @IBSegueAction implies @objc //===--- // CHECK-LABEL: {{^}}class HasIBSegueAction { class HasIBSegueAction { @IBSegueAction func goodSegueAction(_ coder: AnyObject) -> AnyObject {fatalError()} // CHECK: {{^}} @objc @IBSegueAction func goodSegueAction(_ coder: AnyObject) -> AnyObject { @IBSegueAction func badSegueAction(_ coder: PlainStruct?) -> Int? {fatalError()} // expected-error@-1{{method cannot be marked @IBSegueAction because the type of the parameter cannot be represented in Objective-C}} } //===--- //===--- @IBInspectable implies @objc //===--- // CHECK-LABEL: {{^}}class HasIBInspectable { class HasIBInspectable { @IBInspectable var goodProperty: AnyObject? // CHECK: {{^}} @objc @IBInspectable @_hasInitialValue var goodProperty: AnyObject? } //===--- //===--- @GKInspectable implies @objc //===--- // CHECK-LABEL: {{^}}class HasGKInspectable { class HasGKInspectable { @GKInspectable var goodProperty: AnyObject? // CHECK: {{^}} @objc @GKInspectable @_hasInitialValue var goodProperty: AnyObject? } //===--- //===--- @NSManaged implies @objc //===--- class HasNSManaged { // CHECK-LABEL: {{^}}class HasNSManaged { init() {} @NSManaged var goodManaged: Class_ObjC1 // CHECK-LABEL: {{^}} @objc @NSManaged dynamic var goodManaged: Class_ObjC1 { // CHECK-NEXT: {{^}} @objc get // CHECK-NEXT: {{^}} @objc set // CHECK-NEXT: {{^}} } @NSManaged var badManaged: PlainStruct // expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // CHECK-LABEL: {{^}} @NSManaged dynamic var badManaged: PlainStruct { // CHECK-NEXT: {{^}} get // CHECK-NEXT: {{^}} set // CHECK-NEXT: {{^}} } } //===--- //===--- Pointer argument types //===--- @objc // access-note-move{{TakesCPointers}} class TakesCPointers { // CHECK-LABEL: {{^}}@objc class TakesCPointers { func constUnsafeMutablePointer(p: UnsafePointer<Int>) {} // CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) { func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {} // CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) { func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {} // CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) { func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {} // CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) { func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {} // CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) { func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {} // CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) { } // @objc with nullary names @objc(NSObjC2) // access-note-move{{Class_ObjC2}} class Class_ObjC2 { // CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2 @objc(initWithMalice) // access-note-move{{Class_ObjC2.init(foo:)}} init(foo: ()) { } @objc(initWithIntent) // access-note-move{{Class_ObjC2.init(bar:)}} init(bar _: ()) { } @objc(initForMurder) // access-note-move{{Class_ObjC2.init()}} init() { } @objc(isFoo) // access-note-move{{Class_ObjC2.foo()}} func foo() -> Bool {} // CHECK-LABEL: @objc(isFoo) func foo() -> Bool { } @objc() // expected-error {{expected name within parentheses of @objc attribute}} class Class_ObjC3 { } // @objc with selector names extension PlainClass { // CHECK-LABEL: @objc(setFoo:) dynamic func @objc(setFoo:) // access-note-move{{PlainClass.foo(b:)}} func foo(b: Bool) { } // CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set @objc(setWithRed:green:blue:alpha:) // access-note-move{{PlainClass.set(_:green:blue:alpha:)}} func set(_: Float, green: Float, blue: Float, alpha: Float) { } // CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith @objc(createWithRed:green blue:alpha) class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { } // expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}} // expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}} // CHECK-LABEL: @objc(::) dynamic func badlyNamed @objc(::) // access-note-move{{PlainClass.badlyNamed(_:y:)}} func badlyNamed(_: Int, y: Int) {} } @objc(Class:) // bad-access-note-move{{BadClass1}} expected-error{{'@objc' class must have a simple name}}{{12-13=}} class BadClass1 { } @objc(Protocol:) // bad-access-note-move{{BadProto1}} expected-error{{'@objc' protocol must have a simple name}}{{15-16=}} protocol BadProto1 { } @objc(Enum:) // bad-access-note-move{{BadEnum1}} expected-error{{'@objc' enum must have a simple name}}{{11-12=}} enum BadEnum1: Int { case X } @objc // access-note-move{{BadEnum2}} enum BadEnum2: Int { @objc(X:) // bad-access-note-move{{BadEnum2.X}} expected-error{{'@objc' enum case must have a simple name}}{{10-11=}} case X } class BadClass2 { @objc(realDealloc) // expected-error{{'@objc' deinitializer cannot have a name}} deinit { } @objc(badprop:foo:wibble:) // bad-access-note-move{{BadClass2.badprop}} expected-error{{'@objc' property must have a simple name}}{{16-28=}} var badprop: Int = 5 @objc(foo) // bad-access-note-move{{BadClass2.subscript(_:)}} expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}} subscript (i: Int) -> Int { get { return i } } @objc(foo) // bad-access-note-move{{BadClass2.noArgNamesOneParam(x:)}} expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}} func noArgNamesOneParam(x: Int) { } @objc(foo) // bad-access-note-move{{BadClass2.noArgNamesOneParam2(_:)}} expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}} func noArgNamesOneParam2(_: Int) { } @objc(foo) // bad-access-note-move{{BadClass2.noArgNamesTwoParams(_:y:)}} expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}} func noArgNamesTwoParams(_: Int, y: Int) { } @objc(foo:) // bad-access-note-move{{BadClass2.oneArgNameTwoParams(_:y:)}} expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}} func oneArgNameTwoParams(_: Int, y: Int) { } @objc(foo:) // bad-access-note-move{{BadClass2.oneArgNameNoParams()}} expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}} func oneArgNameNoParams() { } @objc(foo:) // bad-access-note-move{{BadClass2.init()}} expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}} init() { } var _prop = 5 @objc // access-note-move{{BadClass2.prop}} var prop: Int { @objc(property) // access-note-move{{getter:BadClass2.prop()}} get { return _prop } @objc(setProperty:) // access-note-move{{setter:BadClass2.prop()}} set { _prop = newValue } } var prop2: Int { @objc(property) // bad-access-note-move{{getter:BadClass2.prop2()}} expected-error{{'@objc' getter for non-'@objc' property}} {{5-21=}} get { return _prop } @objc(setProperty:) // bad-access-note-move{{setter:BadClass2.prop2()}} expected-error{{'@objc' setter for non-'@objc' property}} {{5-25=}} set { _prop = newValue } } var prop3: Int { @objc(setProperty:) // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-25=}} didSet { } } } // FIXME: This could be part of BadClass except that access notes can't // distinguish between overloads of `subscript(_:)`. class GoodClass { @objc // access-note-move{{GoodClass.subscript(_:)}} subscript (c: Class_ObjC1) -> Class_ObjC1 { @objc(getAtClass:) // access-note-move{{getter:GoodClass.subscript(_:)}} get { return c } @objc(setAtClass:class:) // access-note-move{{setter:GoodClass.subscript(_:)}} set { } } } // Swift overrides that aren't also @objc overrides. class Super { @objc(renamedFoo) // access-note-move{{Super.foo}} var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}} @objc // access-note-move{{Super.process(i:)}} func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}} } class Sub1 : Super { @objc(foo) // bad-access-note-move{{Sub1.foo}} expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}} override var foo: Int { get { return 5 } } override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}} } class Sub2 : Super { @objc // bad-access-note-move{{Sub2.foo}} -- @objc is already implied by overriding an @objc attribute, so access notes shouldn't emit a remark override var foo: Int { get { return 5 } } } class Sub3 : Super { override var foo: Int { get { return 5 } } } class Sub4 : Super { @objc(renamedFoo) // access-note-move{{Sub4.foo}} override var foo: Int { get { return 5 } } } class Sub5 : Super { @objc(wrongFoo) // bad-access-note-move{{Sub5.foo}} expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}} override var foo: Int { get { return 5 } } } enum NotObjCEnum { case X } struct NotObjCStruct {} // Closure arguments can only be @objc if their parameters and returns are. // CHECK-LABEL: @objc class ClosureArguments @objc // access-note-move{{ClosureArguments}} class ClosureArguments { // CHECK: @objc func foo @objc // access-note-move{{ClosureArguments.foo(f:)}} func foo(f: (Int) -> ()) {} // CHECK: @objc func bar @objc // bad-access-note-move{{ClosureArguments.bar(f:)}} func bar(f: (NotObjCEnum) -> NotObjCStruct) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func bas @objc // bad-access-note-move{{ClosureArguments.bas(f:)}} func bas(f: (NotObjCEnum) -> ()) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func zim @objc // bad-access-note-move{{ClosureArguments.zim(f:)}} func zim(f: () -> NotObjCStruct) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func zang @objc // bad-access-note-move{{ClosureArguments.zang(f:)}} func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} @objc // bad-access-note-move{{ClosureArguments.zangZang(f:)}} func zangZang(f: (Int...) -> ()) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}} // CHECK: @objc func fooImplicit func fooImplicit(f: (Int) -> ()) {} // CHECK: {{^}} func barImplicit func barImplicit(f: (NotObjCEnum) -> NotObjCStruct) {} // CHECK: {{^}} func basImplicit func basImplicit(f: (NotObjCEnum) -> ()) {} // CHECK: {{^}} func zimImplicit func zimImplicit(f: () -> NotObjCStruct) {} // CHECK: {{^}} func zangImplicit func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // CHECK: {{^}} func zangZangImplicit func zangZangImplicit(f: (Int...) -> ()) {} } typealias GoodBlock = @convention(block) (Int) -> () typealias BadBlock = @convention(block) (NotObjCEnum) -> () // expected-error{{'(NotObjCEnum) -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}} @objc // access-note-move{{AccessControl}} class AccessControl { // CHECK: @objc func foo func foo() {} // CHECK: {{^}} private func bar private func bar() {} // CHECK: @objc private func baz @objc // access-note-move{{AccessControl.baz()}} private func baz() {} } //===--- Ban @objc +load methods class Load1 { // Okay: not @objc class func load() { } class func alloc() {} class func allocWithZone(_: Int) {} class func initialize() {} } @objc // access-note-move{{Load2}} class Load2 { class func load() { } // expected-error {{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}} class func alloc() {} // expected-error {{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}} class func allocWithZone(_: Int) {} // expected-error {{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}} class func initialize() {} // expected-error {{method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}} } @objc // access-note-move{{Load3}} class Load3 { class var load: Load3 { get { return Load3() } // expected-error {{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}} set { } } @objc(alloc) // access-note-move{{Load3.prop}} class var prop: Int { return 0 } // expected-error {{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}} @objc(allocWithZone:) // access-note-move{{Load3.fooWithZone(_:)}} class func fooWithZone(_: Int) {} // expected-error {{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}} @objc(initialize) // access-note-move{{Load3.barnitialize()}} class func barnitialize() {} // expected-error {{method 'barnitialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}} } // Members of protocol extensions cannot be @objc extension PlainProtocol { @objc // bad-access-note-move{{PlainProtocol.property}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} var property: Int { return 5 } @objc // bad-access-note-move{{PlainProtocol.subscript(_:)}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } @objc // bad-access-note-move{{PlainProtocol.fun()}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} func fun() { } } extension Protocol_ObjC1 { @objc // bad-access-note-move{{Protocol_ObjC1.property}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} var property: Int { return 5 } @objc // bad-access-note-move{{Protocol_ObjC1.subscript(_:)}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } @objc // bad-access-note-move{{Protocol_ObjC1.fun()}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} func fun() { } } extension Protocol_ObjC1 { // Don't infer @objc for extensions of @objc protocols. // CHECK: {{^}} var propertyOK: Int var propertyOK: Int { return 5 } } //===--- //===--- Error handling //===--- class ClassThrows1 { // CHECK: @objc func methodReturnsVoid() throws @objc // access-note-move{{ClassThrows1.methodReturnsVoid()}} func methodReturnsVoid() throws { } // CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1 @objc // access-note-move{{ClassThrows1.methodReturnsObjCClass()}} func methodReturnsObjCClass() throws -> Class_ObjC1 { return Class_ObjC1() } // CHECK: @objc func methodReturnsBridged() throws -> String @objc // access-note-move{{ClassThrows1.methodReturnsBridged()}} func methodReturnsBridged() throws -> String { return String() } // CHECK: @objc func methodReturnsArray() throws -> [String] @objc // access-note-move{{ClassThrows1.methodReturnsArray()}} func methodReturnsArray() throws -> [String] { return [String]() } // CHECK: @objc init(degrees: Double) throws @objc // access-note-move{{ClassThrows1.init(degrees:)}} init(degrees: Double) throws { } // Errors @objc // bad-access-note-move{{ClassThrows1.methodReturnsOptionalObjCClass()}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // access-note-adjust{{@objc}} expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}} @objc // bad-access-note-move{{ClassThrows1.methodReturnsOptionalArray()}} func methodReturnsOptionalArray() throws -> [String]? { return nil } // access-note-adjust{{@objc}} expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}} @objc // bad-access-note-move{{ClassThrows1.methodReturnsInt()}} func methodReturnsInt() throws -> Int { return 0 } // access-note-adjust{{@objc}} expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}} @objc // bad-access-note-move{{ClassThrows1.methodAcceptsThrowingFunc(fn:)}} func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { } // access-note-adjust{{@objc}} expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{throwing function types cannot be represented in Objective-C}} @objc // bad-access-note-move{{ClassThrows1.init(radians:)}} init?(radians: Double) throws { } // access-note-adjust{{@objc}} expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}} @objc // bad-access-note-move{{ClassThrows1.init(string:)}} init!(string: String) throws { } // access-note-adjust{{@objc}} expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}} @objc // bad-access-note-move{{ClassThrows1.fooWithErrorEnum1(x:)}} func fooWithErrorEnum1(x: ErrorEnum) {} // access-note-adjust{{@objc}} expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}} // CHECK: {{^}} func fooWithErrorEnum2(x: ErrorEnum) func fooWithErrorEnum2(x: ErrorEnum) {} @objc // bad-access-note-move{{ClassThrows1.fooWithErrorProtocolComposition1(x:)}} func fooWithErrorProtocolComposition1(x: Error & Protocol_ObjC1) { } // access-note-adjust{{@objc}} expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2{{protocol-constrained type containing 'Error' cannot be represented in Objective-C}} // CHECK: {{^}} func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) { } } // CHECK-DUMP-LABEL: class_decl{{.*}}"ImplicitClassThrows1" @objc // access-note-move{{ImplicitClassThrows1}} class ImplicitClassThrows1 { // CHECK: @objc func methodReturnsVoid() throws // CHECK-DUMP: func_decl{{.*}}"methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool func methodReturnsVoid() throws { } // CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1 // CHECK-DUMP: func_decl{{.*}}"methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>> func methodReturnsObjCClass() throws -> Class_ObjC1 { return Class_ObjC1() } // CHECK: @objc func methodReturnsBridged() throws -> String func methodReturnsBridged() throws -> String { return String() } // CHECK: @objc func methodReturnsArray() throws -> [String] func methodReturnsArray() throws -> [String] { return [String]() } // CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) // CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) throws { } // CHECK: @objc init(degrees: Double) throws // CHECK-DUMP: constructor_decl{{.*}}"init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>> init(degrees: Double) throws { } // CHECK: {{^}} func methodReturnsBridgedValueType() throws -> NSRange func methodReturnsBridgedValueType() throws -> NSRange { return NSRange() } @objc // bad-access-note-move{{ImplicitClassThrows1.methodReturnsBridgedValueType2()}} func methodReturnsBridgedValueType2() throws -> NSRange { return NSRange() } // access-note-adjust{{@objc}} expected-error@-3{{throwing method cannot be marked @objc because it returns a value of type 'NSRange' (aka '_NSRange'); return 'Void' or a type that bridges to an Objective-C class}} // CHECK: {{^}} @objc func methodReturnsError() throws -> Error func methodReturnsError() throws -> Error { return ErrorEnum.failed } // CHECK: @objc func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) { func add(x: Int) -> (Int) -> Int { return { x + $0 } } } } // CHECK-DUMP-LABEL: class_decl{{.*}}"SubclassImplicitClassThrows1" @objc // access-note-move{{SubclassImplicitClassThrows1}} class SubclassImplicitClassThrows1 : ImplicitClassThrows1 { // CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping ((Int) -> Int), fn3: @escaping ((Int) -> Int)) // CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool override func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: (@escaping (Int) -> Int), fn3: (@escaping (Int) -> Int)) throws { } } class ThrowsRedecl1 { @objc // access-note-move{{ThrowsRedecl1.method1(_:error:)}} func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}} @objc // bad-access-note-move{{ThrowsRedecl1.method1(_:)}} func method1(_ x: Int) throws { } // access-note-adjust{{@objc}} expected-error {{method 'method1' with Objective-C selector 'method1:error:' conflicts with method 'method1(_:error:)' with the same Objective-C selector}} @objc // access-note-move{{ThrowsRedecl1.method2AndReturnError(_:)}} func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}} @objc // bad-access-note-move{{ThrowsRedecl1.method2()}} func method2() throws { } // access-note-adjust{{@objc}} expected-error {{method 'method2()' with Objective-C selector 'method2AndReturnError:' conflicts with method 'method2AndReturnError' with the same Objective-C selector}} @objc // access-note-move{{ThrowsRedecl1.method3(_:error:closure:)}} func method3(_ x: Int, error: Int, closure: @escaping (Int) -> Int) { } // expected-note{{declared here}} @objc // bad-access-note-move{{ThrowsRedecl1.method3(_:closure:)}} func method3(_ x: Int, closure: (Int) -> Int) throws { } // access-note-adjust{{@objc}} expected-error {{method 'method3(_:closure:)' with Objective-C selector 'method3:error:closure:' conflicts with method 'method3(_:error:closure:)' with the same Objective-C selector}} @objc(initAndReturnError:) // access-note-move{{ThrowsRedecl1.initMethod1(error:)}} func initMethod1(error: Int) { } // expected-note{{declared here}} @objc // bad-access-note-move{{ThrowsRedecl1.init()}} init() throws { } // access-note-adjust{{@objc}} expected-error {{initializer 'init()' with Objective-C selector 'initAndReturnError:' conflicts with method 'initMethod1(error:)' with the same Objective-C selector}} @objc(initWithString:error:) // access-note-move{{ThrowsRedecl1.initMethod2(string:error:)}} func initMethod2(string: String, error: Int) { } // expected-note{{declared here}} @objc // bad-access-note-move{{ThrowsRedecl1.init(string:)}} init(string: String) throws { } // access-note-adjust{{@objc}} expected-error {{initializer 'init(string:)' with Objective-C selector 'initWithString:error:' conflicts with method 'initMethod2(string:error:)' with the same Objective-C selector}} @objc(initAndReturnError:fn:) // access-note-move{{ThrowsRedecl1.initMethod3(error:fn:)}} func initMethod3(error: Int, fn: @escaping (Int) -> Int) { } // expected-note{{declared here}} @objc // bad-access-note-move{{ThrowsRedecl1.init(fn:)}} init(fn: (Int) -> Int) throws { } // access-note-adjust{{@objc}} expected-error {{initializer 'init(fn:)' with Objective-C selector 'initAndReturnError:fn:' conflicts with method 'initMethod3(error:fn:)' with the same Objective-C selector}} } class ThrowsObjCName { @objc(method4:closure:error:) // access-note-move{{ThrowsObjCName.method4(x:closure:)}} func method4(x: Int, closure: @escaping (Int) -> Int) throws { } @objc(method5AndReturnError:x:closure:) // access-note-move{{ThrowsObjCName.method5(x:closure:)}} func method5(x: Int, closure: @escaping (Int) -> Int) throws { } @objc(method6) // bad-access-note-move{{ThrowsObjCName.method6()}} expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}} func method6() throws { } @objc(method7) // bad-access-note-move{{ThrowsObjCName.method7(x:)}} expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}} func method7(x: Int) throws { } // CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool @objc(method8:fn1:error:fn2:) // access-note-move{{ThrowsObjCName.method8(_:fn1:fn2:)}} func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { } // CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool @objc(method9AndReturnError:s:fn1:fn2:) // access-note-move{{ThrowsObjCName.method9(_:fn1:fn2:)}} func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { } } class SubclassThrowsObjCName : ThrowsObjCName { // CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool override func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { } // CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool override func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { } } @objc // access-note-move{{ProtocolThrowsObjCName}} protocol ProtocolThrowsObjCName { @objc // Access notes don't allow the `optional` keyword, that's fine, honestly. optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}} } class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName { @objc // bad-access-note-move{{ConformsToProtocolThrowsObjCName1.doThing(_:)}} -- @objc inherited, so no remarks func doThing(_ x: String) throws -> String { return x } // okay } class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName { @objc // access-note-move{{ConformsToProtocolThrowsObjCName2.doThing(_:)}} func doThing(_ x: Int) throws -> String { return "" } // expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}} // expected-note@-2{{move 'doThing' to an extension to silence this warning}} // expected-note@-3{{make 'doThing' private to silence this warning}}{{3-3=private }} // expected-note@-4{{candidate has non-matching type '(Int) throws -> String'}} } @objc // access-note-move{{DictionaryTest}} class DictionaryTest { // CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { } // CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) @objc // access-note-move{{DictionaryTest.func_dictionary1b(x:)}} func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { } func func_dictionary2a(x: Dictionary<String, Int>) { } @objc // access-note-move{{DictionaryTest.func_dictionary2b(x:)}} func func_dictionary2b(x: Dictionary<String, Int>) { } } @objc extension PlainClass { // CHECK-LABEL: @objc final func objc_ext_objc_okay(_: Int) { final func objc_ext_objc_okay(_: Int) { } final func objc_ext_objc_not_okay(_: PlainStruct) { } // expected-error@-1{{method cannot be in an @objc extension of a class (without @nonobjc) because the type of the parameter cannot be represented in Objective-C}} // expected-note@-2 {{Swift structs cannot be represented in Objective-C}} // CHECK-LABEL: {{^}} @nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) { @nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) { } } @objc // access-note-move{{ObjC_Class1}} class ObjC_Class1 : Hashable { func hash(into hasher: inout Hasher) {} } func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool { return true } // CHECK-LABEL: @objc class OperatorInClass @objc // access-note-move{{OperatorInClass}} class OperatorInClass { // CHECK: {{^}} static func == (lhs: OperatorInClass, rhs: OperatorInClass) -> Bool static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool { return true } // CHECK: {{^}} @objc static func + (lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass @objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass { // expected-error {{operator methods cannot be declared @objc}} return lhs } } // CHECK: {{^}$}} @objc // access-note-move{{OperatorInProtocol}} protocol OperatorInProtocol { static func +(lhs: Self, rhs: Self) -> Self // expected-error {{@objc protocols must not have operator requirements}} } class AdoptsOperatorInProtocol : OperatorInProtocol { static func +(lhs: AdoptsOperatorInProtocol, rhs: AdoptsOperatorInProtocol) -> Self {} // expected-error@-1 {{operator methods cannot be declared @objc}} } //===--- @objc inference for witnesses @objc // access-note-move{{InferFromProtocol}} protocol InferFromProtocol { @objc(inferFromProtoMethod1:) optional func method1(value: Int) } // Infer when in the same declaration context. // CHECK-LABEL: ClassInfersFromProtocol1 class ClassInfersFromProtocol1 : InferFromProtocol{ // CHECK: {{^}} @objc func method1(value: Int) func method1(value: Int) { } } // Infer when in a different declaration context of the same class. // CHECK-LABEL: ClassInfersFromProtocol2a class ClassInfersFromProtocol2a { // CHECK: {{^}} @objc func method1(value: Int) func method1(value: Int) { } } extension ClassInfersFromProtocol2a : InferFromProtocol { } // Infer when in a different declaration context of the same class. class ClassInfersFromProtocol2b : InferFromProtocol { } // CHECK-LABEL: ClassInfersFromProtocol2b extension ClassInfersFromProtocol2b { // CHECK: {{^}} @objc dynamic func method1(value: Int) func method1(value: Int) { } } // Don't infer when there is a signature mismatch. // CHECK-LABEL: ClassInfersFromProtocol3 class ClassInfersFromProtocol3 : InferFromProtocol { } extension ClassInfersFromProtocol3 { // CHECK: {{^}} func method1(value: String) func method1(value: String) { } } // Inference for subclasses. class SuperclassImplementsProtocol : InferFromProtocol { } class SubclassInfersFromProtocol1 : SuperclassImplementsProtocol { // CHECK: {{^}} @objc func method1(value: Int) func method1(value: Int) { } } class SubclassInfersFromProtocol2 : SuperclassImplementsProtocol { } extension SubclassInfersFromProtocol2 { // CHECK: {{^}} @objc dynamic func method1(value: Int) func method1(value: Int) { } } @objc // access-note-move{{NeverReturningMethod}} class NeverReturningMethod { @objc // access-note-move{{NeverReturningMethod.doesNotReturn()}} func doesNotReturn() -> Never {} } // SR-5025 class User: NSObject { } @objc extension User { var name: String { get { return "No name" } set { // Nothing } } var other: String { unsafeAddress { // expected-error {{addressors are not allowed to be marked @objc}} } } } // 'dynamic' methods cannot be @inlinable. class BadClass { @objc // access-note-move{{BadClass.badMethod1()}} @inlinable dynamic func badMethod1() {} // expected-error@-1 {{'@inlinable' attribute cannot be applied to 'dynamic' declarations}} } @objc // access-note-move{{ObjCProtocolWithWeakProperty}} protocol ObjCProtocolWithWeakProperty { weak var weakProp: AnyObject? { get set } // okay } @objc // access-note-move{{ObjCProtocolWithUnownedProperty}} protocol ObjCProtocolWithUnownedProperty { unowned var unownedProp: AnyObject { get set } // okay } // rdar://problem/46699152: errors about read/modify accessors being implicitly // marked @objc. @objc // access-note-move{{MyObjCClass}} class MyObjCClass: NSObject {} @objc extension MyObjCClass { @objc // access-note-move{{MyObjCClass.objCVarInObjCExtension}} static var objCVarInObjCExtension: Bool { get { return true } set {} } // CHECK: {{^}} @objc private dynamic func stillExposedToObjCDespiteBeingPrivate() private func stillExposedToObjCDespiteBeingPrivate() {} } @objc private extension MyObjCClass { // CHECK: {{^}} @objc dynamic func alsoExposedToObjCDespiteBeingPrivate() func alsoExposedToObjCDespiteBeingPrivate() {} } @objcMembers class VeryObjCClass: NSObject { // CHECK: {{^}} private func notExposedToObjC() private func notExposedToObjC() {} } // SR-9035 class SR_9035_C {} @objc // access-note-move{{SR_9035_P}} protocol SR_9035_P { func throwingMethod1() throws -> Unmanaged<CFArray> // Ok func throwingMethod2() throws -> Unmanaged<SR_9035_C> // expected-error {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}} // expected-note@-1 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}} } // SR-12801: Make sure we reject an @objc generic subscript. class SR12801 { @objc // bad-access-note-move{{SR12801.subscript(_:)}} subscript<T>(foo : [T]) -> Int { return 0 } // access-note-adjust{{@objc}} expected-error@-1 {{subscript cannot be marked @objc because it has generic parameters}} } // @_backDeploy public class BackDeployClass { @available(macOS 11.0, *) @_backDeploy(before: macOS 12.0) @objc // expected-error {{'@objc' cannot be applied to a back deployed instance method}} final public func objcMethod() {} }
apache-2.0
011693c6b8bcfe7875c792f621186c4f
46.089205
462
0.712458
3.840139
false
false
false
false
umich-software-prototyping-clinic/ios-app
iOS app/confirmPageViewController.swift
1
7744
import UIKit class confirmPageViewController: UIViewController,PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, UITextFieldDelegate { let button = UIButton() let resetPasswordButton = UIButton() let printButton = UIButton() let userListButton = UIButton() let message = UILabel() let message2 = UILabel() let exampleTitle = UILabel() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.view.addSubview(exampleTitle) exampleTitle.backgroundColor = UIColor.lightGrayColor() exampleTitle.sizeToHeight(30) exampleTitle.sizeToWidth(600) exampleTitle.pinToTopEdgeOfSuperview(20) exampleTitle.centerHorizontallyInSuperview() exampleTitle.font = UIFont(name: "AvenirNext-DemiBold", size: 30) exampleTitle.textAlignment = NSTextAlignment.Center exampleTitle.text = "Example App" exampleTitle.textColor = UIColor.whiteColor() self.view.addSubview(message) message.sizeToHeight(30) message.sizeToWidth(600) message.centerHorizontallyInSuperview() message.positionBelowItem(exampleTitle, offset: 30) message.font = UIFont(name: "AvenirNext-DemiBold", size: 15) message.text = "Password Reset Succeeded!" self.view.addSubview(message2) message2.sizeToHeight(30) message2.sizeToWidth(600) message2.pinToLeftEdgeOfSuperview(20) message2.positionBelowItem(message, offset: 20) message2.font = UIFont(name: "AvenirNext-DemiBold", size: 15) message2.text = "An email has been sent to:" self.view.addSubview(button) button.backgroundColor = UIColor.darkGrayColor() button.sizeToHeight(40) button.sizeToWidth(100) button.pinToBottomEdgeOfSuperview() button.setTitle("Logout", forState: UIControlState.Normal) button.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) button.addTarget(self, action: "logoutAction", forControlEvents: .TouchUpInside) self.view.addSubview(resetPasswordButton) resetPasswordButton.backgroundColor = UIColor.darkGrayColor() resetPasswordButton.pinToBottomEdgeOfSuperview() resetPasswordButton.sizeToHeight(40) resetPasswordButton.sizeToWidth(100) resetPasswordButton.positionToTheRightOfItem(button, offset: 5) resetPasswordButton.setTitle("Reset Pswd", forState: UIControlState.Normal) resetPasswordButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) resetPasswordButton.addTarget(self, action: "resetAction", forControlEvents: .TouchUpInside) self.view.addSubview(printButton) printButton.backgroundColor = UIColor.darkGrayColor() printButton.sizeToHeight(40) printButton.sizeToWidth(100) printButton.pinToRightEdgeOfSuperview() printButton.pinToBottomEdgeOfSuperview() printButton.setTitle("Print Text", forState: UIControlState.Normal) printButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) printButton.addTarget(self, action: "printAction", forControlEvents: .TouchUpInside) self.view.addSubview(userListButton) userListButton.backgroundColor = UIColor.darkGrayColor() userListButton.sizeToHeight(40) userListButton.sizeToWidth(100) userListButton.positionToTheLeftOfItem(printButton, offset: 5) userListButton.pinToBottomEdgeOfSuperview() userListButton.setTitle("User List", forState: UIControlState.Normal) userListButton.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15) userListButton.addTarget(self, action: "userListAction", forControlEvents: .TouchUpInside) }//viewDidLoad func loginSetup() { if (PFUser.currentUser() == nil) { let loginViewController = PFLogInViewController() loginViewController.delegate = self let signupViewController = PFSignUpViewController() signupViewController.delegate = self loginViewController.signUpController = signupViewController loginViewController.fields = ([PFLogInFields.LogInButton, PFLogInFields.SignUpButton, PFLogInFields.UsernameAndPassword, PFLogInFields.PasswordForgotten , PFLogInFields.DismissButton]) // let signupTitle = UILabel() // signupTitle.text = "Barter Signup" //loginLogo let loginLogoImageView = UIImageView() loginLogoImageView.image = UIImage(named: "swap") loginLogoImageView.contentMode = UIViewContentMode.ScaleAspectFit //signupLogo let signupLogoImageView = UIImageView() signupLogoImageView.image = UIImage(named: "swap") signupLogoImageView.contentMode = UIViewContentMode.ScaleAspectFit loginViewController.view.backgroundColor = UIColor.whiteColor() signupViewController.view.backgroundColor = UIColor.whiteColor() loginViewController.logInView?.logo = loginLogoImageView signupViewController.signUpView?.logo = signupLogoImageView self.presentViewController(loginViewController, animated: true, completion: nil) }//if }//func //Checks if username and password are empty func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool { if (!username.isEmpty || !password.isEmpty) { return true }//if else { return false }//else }//func //Closes login view after user logs in func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) }//func //Checks for login error func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) { print("Failed to login....") }//func //MARK: Parse SignUp //Closes signup view after user signs in func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) }//func //Checks for signup error func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) { print("Failed to signup") }//func //Checks if user cancelled signup func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) { print("User dismissed signup") }//func //Logs out user func logoutAction() { print("logging out") PFUser.logOut() self.loginSetup() }//func func printAction() { print("clicked") let PVC = printViewController() self.presentViewController(PVC, animated: false, completion: nil) }//func func userListAction() { print("clicked") let PVC = LoginViewController() self.presentViewController(PVC, animated: false, completion: nil) }//func func resetAction() { print("clicked") let RVC = resetPasswordViewController() self.presentViewController(RVC, animated: false, completion: nil) }//func }
mit
4b4421de82432e79bafcf285488655de
38.309645
197
0.670455
5.660819
false
false
false
false
loudnate/LoopKit
LoopKit/GlucoseKit/GlucoseTrend.swift
1
1616
// // GlucoseTrend.swift // Loop // // Created by Nate Racklyeft on 8/2/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation public enum GlucoseTrend: Int, CaseIterable { case upUpUp = 1 case upUp = 2 case up = 3 case flat = 4 case down = 5 case downDown = 6 case downDownDown = 7 public var symbol: String { switch self { case .upUpUp: return "⇈" case .upUp: return "↑" case .up: return "↗︎" case .flat: return "→" case .down: return "↘︎" case .downDown: return "↓" case .downDownDown: return "⇊" } } public var localizedDescription: String { switch self { case .upUpUp: return LocalizedString("Rising very fast", comment: "Glucose trend up-up-up") case .upUp: return LocalizedString("Rising fast", comment: "Glucose trend up-up") case .up: return LocalizedString("Rising", comment: "Glucose trend up") case .flat: return LocalizedString("Flat", comment: "Glucose trend flat") case .down: return LocalizedString("Falling", comment: "Glucose trend down") case .downDown: return LocalizedString("Falling fast", comment: "Glucose trend down-down") case .downDownDown: return LocalizedString("Falling very fast", comment: "Glucose trend down-down-down") } } }
mit
b315502ce964dac7f49bc8f3bb268571
26.534483
96
0.540388
4.316216
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Utils/Trendlines/TrendlineGenerator.swift
4
1550
// // TrendlineGenerator.swift // Examples // // Created by ischuetz on 03/08/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public struct TrendlineGenerator { public static func trendline(_ chartPoints: [ChartPoint]) -> [ChartPoint] { guard chartPoints.count > 1 else {return []} let doubleO: Double = 0 let (sumX, sumY, sumXY, sumXX): (sumX: Double, sumY: Double, sumXY: Double, sumXX: Double) = chartPoints.reduce((sumX: doubleO, sumY: doubleO, sumXY: doubleO, sumXX: doubleO)) {(tuple, chartPoint) in let x: Double = chartPoint.x.scalar let y: Double = chartPoint.y.scalar return ( tuple.sumX + x, tuple.sumY + y, tuple.sumXY + x * y, tuple.sumXX + x * x ) } let count = Double(chartPoints.count) let b = (count * sumXY - sumX * sumY) / (count * sumXX - sumX * sumX) let a = (sumY - b * sumX) / count // equation of line: y = a + bx func y(_ x: Double) -> Double { return a + b * x } let first = chartPoints.first! let last = chartPoints.last! return [ ChartPoint(x: ChartAxisValueDouble(first.x.scalar), y: ChartAxisValueDouble(y(first.x.scalar))), ChartPoint(x: ChartAxisValueDouble(last.x.scalar), y: ChartAxisValueDouble(y(last.x.scalar))) ] } }
apache-2.0
75b8b2b91451824b2f736147488a35a3
30.653061
207
0.534194
4.293629
false
false
false
false
kpedersen00/patronus
Patronus/InfoResourceViewController.swift
1
4042
// // InfoResourceViewController.swift // Patronus // // Created by Monica Sun on 7/12/15. // Copyright (c) 2015 Monica Sun. All rights reserved. // import UIKit class InfoResourceViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var backButton: UIButton! var numRows: Int! var infoSectionToShow: Int! var rowPosition: Int! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numRows } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("detailedInfoCell", forIndexPath: indexPath) as! DetailedInfoCell // TODO replace these w/ each section's rows cell.textLabel!.font = UIFont.systemFontOfSize(14); cell.textLabel!.numberOfLines = 0; switch (infoSectionToShow) { case 1: if (indexPath.row == 1) { cell.textLabel?.text = "What is Domestic Violence?\nFrom National Coalition Against Domestic Violence" } else if (indexPath.row == 2) { cell.textLabel?.text = "About Domestic Violence\nFrom Violence Against Women" } else if (indexPath.row == 3) { cell.textLabel?.text = "What Is Abuse?\nFrom The National Domestic Violence Hotline" } else if (indexPath.row == 4) { cell.textLabel?.text = "What Is Domestic Violence?\nFrom The US Dept of Justice" } case 2: if (indexPath.row == 1) { cell.textLabel?.text = "Help a Loved One or Friend\nFrom Domestic Abuse Intervention Services " } else if (indexPath.row == 2) { cell.textLabel?.text = "How to Help a Friend\nWho Is Being Abused From Violence Against Women" } else if (indexPath.row == 3) { cell.textLabel?.text = "Get Help for Someone Else?\nFrom Love Is Respect Org" } case 3: if (indexPath.row == 1) { cell.textLabel?.text = "Domestic Violence Safety Tips\nFrom National Resource Center on Domestic Violence" } else if (indexPath.row == 2) { cell.textLabel?.text = "Safety Tips for You and Your Family\nFrom American Bar Association" } else if (indexPath.row == 3) { cell.textLabel?.text = "What Is Safety Planning?\nFrom The National Domestic Violence Hotline" } else if (indexPath.row == 4) { cell.textLabel?.text = "Help for Abused and Battered Women\nFrom HelpGuide.org" } case 4: if (indexPath.row == 1) { cell.textLabel?.text = "National Domestic Violence Hotline\n1-800-799-7233 or 1-800-787-3224 (TTY)" } else if (indexPath.row == 2) { cell.textLabel?.text = "National Center for Victims of Crimes, Stalking Resource Center\n1-800-394-2255 or 1-800-211-7996 (TTY)" } else if (indexPath.row == 3) { cell.textLabel?.text = "National Teen Dating Abuse Helpline\n1-866-331-9474 or 1-866-331-8453 (TTY)" } default: NSLog("UNEXPECTED: \(indexPath.row)") } return cell } @IBAction func backButtonClicked(sender: AnyObject) { self.dismissViewControllerAnimated(false, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
2c8191d29a7f442462c1c625e2b3b421
44.931818
173
0.661306
4.162719
false
false
false
false
giridharvc7/ScreenRecord
ScreenRecordDemo/Source/FileUtil.swift
1
1935
// // FileManager.swift // BugReporterTest // // Created by Giridhar on 20/06/17. // Copyright © 2017 Giridhar. All rights reserved. // import Foundation class ReplayFileUtil { internal class func createReplaysFolder() { // path to documents directory let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first if let documentDirectoryPath = documentDirectoryPath { // create the custom folder path let replayDirectoryPath = documentDirectoryPath.appending("/Replays") let fileManager = FileManager.default if !fileManager.fileExists(atPath: replayDirectoryPath) { do { try fileManager.createDirectory(atPath: replayDirectoryPath, withIntermediateDirectories: false, attributes: nil) } catch { print("Error creating Replays folder in documents dir: \(error)") } } } } internal class func filePath(_ fileName: String) -> String { createReplaysFolder() let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentsDirectory = paths[0] as String let filePath : String = "\(documentsDirectory)/Replays/\(fileName).mp4" return filePath } internal class func fetchAllReplays() -> Array<URL> { let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first let replayPath = documentsDirectory?.appendingPathComponent("/Replays") let directoryContents = try! FileManager.default.contentsOfDirectory(at: replayPath!, includingPropertiesForKeys: nil, options: []) return directoryContents } }
mit
06700415b51fe1c6c043af3148c046c1
36.192308
139
0.627715
5.860606
false
false
false
false
ndagrawal/MovieFeed
MovieFeed/CurrentMoviesDetailViewController.swift
1
1878
// // CurrentMoviesDetailViewController.swift // MovieFeed // // Created by Nilesh Agrawal on 9/17/15. // Copyright © 2015 Nilesh Agrawal. All rights reserved. // import UIKit class CurrentMoviesDetailViewController: UIViewController { var selectedCurrentMovie:CurrentMovie? @IBOutlet weak var selectedMovieSummary: UITextView! @IBOutlet weak var selectedMovieImage:UIImageView! // @IBOutlet weak var selectedMovieCasts: UILabel! @IBOutlet weak var selectedMovieName: UILabel! // @IBOutlet weak var selectedMoviePercentage: UILabel! // @IBOutlet weak var selectedMovieMinutes: UILabel! // @IBOutlet weak var selectedMovieRating: UILabel! // override func viewDidLoad() { super.viewDidLoad() selectedMovieName.text = selectedCurrentMovie?.movieName! // selectedMovieCasts.text = "Casts:\n"+(selectedCurrentMovie?.movieCasts)! let url:NSURL = NSURL(string: (selectedCurrentMovie?.movieImageURL)!)! selectedMovieImage.setImageWithURL(url) // selectedMoviePercentage.text = String(selectedCurrentMovie?.moviePercentage) // selectedMovieMinutes.text = String(selectedCurrentMovie?.movieTime) // selectedMovieRating.text = selectedCurrentMovie?.movieRating! selectedMovieSummary.text = selectedCurrentMovie?.movieSummary! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
6083c7b45e6d3625165c6cda30772687
35.803922
106
0.721364
4.800512
false
false
false
false
t-ballz/coopclocker-osx
CoopClocker-osx/Source/Extensions.swift
1
1720
// // Extensions.swift // StatusBarPomodoro // // Created by TaileS Ballz on 23/10/15. // Copyright (c) 2015 ballz. All rights reserved. // import Cocoa import RxSwift import RxCocoa extension NSView { func setBorder(width: CGFloat = 1.0, color: NSColor = NSColor.blackColor()) { self.layer?.borderWidth = width self.layer?.borderColor = color.CGColor } func viewWithTagAs<T:NSView>(tag: Int) -> T? { return self.viewWithTag(tag) as? T } } extension NSDate { func minutes_seconds() -> (Int, Int) { let calendar = NSCalendar.currentCalendar() let components = calendar.components(NSCalendarUnit.CalendarUnitMinute | .CalendarUnitSecond, fromDate: self) return (components.minute, components.second) } } // RX helpers extension Observable { class func rx_return<T>(value: T) -> Observable<T> { return create { sink in sendNext(sink, value) sendCompleted(sink) return NopDisposable.instance } } } infix operator <~ {} func <~<T>(variable: Variable<T>, value: T) { variable.next(value) } func <~<T>(variable: Variable<T>, signal: Observable<T>) -> Disposable { return signal.subscribe(variable) } infix operator ~> {} func ~><T>(signal: Observable<T>, nextBlock:(T) -> ()) { signal >- subscribeNext(nextBlock) } infix operator *~> {} func *~><T>(signal: Observable<T>, completedBlock: () -> ()) { signal >- subscribeCompleted(completedBlock) } extension NSButton { func bindToHandler<T>(handler: (NSView) -> Observable<T>) -> Observable<Observable<T>> { return self.rx_tap >- map { handler(self) } } }
bsd-3-clause
883f3497b7d71c62c5e64c715241d2e2
19.97561
117
0.623256
3.747277
false
false
false
false